build.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Modified by MiniMax for MCode Sandbox Runtime.
  2. import { readFileSync, rmSync, writeFileSync } from 'node:fs'
  3. import { join } from 'node:path'
  4. import { run, setup } from '../build-common.js'
  5. const { SRC, OUT } = setup({
  6. importMetaUrl: import.meta.url,
  7. requirePlatform: 'linux',
  8. srcDirName: 'seccomp-src',
  9. })
  10. function toCArray(bytes: Buffer): string {
  11. const hex = Array.from(bytes, b => '0x' + b.toString(16).padStart(2, '0'))
  12. const lines: string[] = []
  13. for (let i = 0; i < hex.length; i += 8) {
  14. lines.push(' ' + hex.slice(i, i + 8).join(', ') + ',')
  15. }
  16. return lines.join('\n')
  17. }
  18. const cflags = ['-static', '-O2', '-Wall', '-Wextra']
  19. const hostCc = process.env.HOST_CC ?? 'gcc'
  20. const targetCc = process.env.CC ?? 'gcc'
  21. const targetStrip = process.env.STRIP ?? 'strip'
  22. const gen = join(OUT, 'seccomp-unix-block')
  23. run([
  24. hostCc,
  25. ...cflags,
  26. '-o',
  27. gen,
  28. join(SRC, 'seccomp-unix-block.c'),
  29. '-lseccomp',
  30. ])
  31. const bpf: Record<string, Buffer> = {}
  32. for (const target of ['x86_64', 'aarch64']) {
  33. const tmp = join(OUT, target + '.bpf')
  34. run([gen, tmp, target])
  35. bpf[target] = readFileSync(tmp)
  36. rmSync(tmp)
  37. }
  38. rmSync(gen)
  39. const header = join(OUT, 'unix-block-bpf.h')
  40. writeFileSync(
  41. header,
  42. '#if defined(__x86_64__)\n' +
  43. 'static const unsigned char unix_block_bpf[] = {\n' +
  44. toCArray(bpf.x86_64) +
  45. '\n};\n' +
  46. '#elif defined(__aarch64__)\n' +
  47. 'static const unsigned char unix_block_bpf[] = {\n' +
  48. toCArray(bpf.aarch64) +
  49. '\n};\n' +
  50. '#else\n' +
  51. '#error "unsupported architecture for unix-block BPF filter"\n' +
  52. '#endif\n',
  53. )
  54. run([
  55. targetCc,
  56. ...cflags,
  57. '-I',
  58. OUT,
  59. '-o',
  60. join(OUT, 'apply-seccomp'),
  61. join(SRC, 'apply-seccomp.c'),
  62. ])
  63. run([targetStrip, join(OUT, 'apply-seccomp')])
  64. rmSync(header)
  65. console.log('built ' + join(OUT, 'apply-seccomp'))