build.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. // Build builds code as directed by json files.
  2. // We slurp in the JSON, and recursively process includes.
  3. // At the end, we issue a single cc command for all the files.
  4. // Compilers are fast.
  5. //
  6. // ENVIRONMENT
  7. //
  8. // Needed: HARVEY, ARCH
  9. //
  10. // HARVEY should point to a harvey root.
  11. // A best-effort to autodetect the harvey root is made if not explicitly set.
  12. //
  13. // Optional: CC, AR, LD, RANLIB, STRIP, SH, TOOLPREFIX
  14. //
  15. // These all control how the needed tools are found.
  16. //
  17. package main
  18. import (
  19. "encoding/json"
  20. "flag"
  21. "fmt"
  22. "io/ioutil"
  23. "log"
  24. "os"
  25. "os/exec"
  26. "path"
  27. "path/filepath"
  28. "regexp"
  29. "strings"
  30. )
  31. type kernconfig struct {
  32. Code []string
  33. Dev []string
  34. Ip []string
  35. Link []string
  36. Sd []string
  37. Uart []string
  38. VGA []string
  39. }
  40. type kernel struct {
  41. Systab string
  42. Config kernconfig
  43. Ramfiles map[string]string
  44. }
  45. type build struct {
  46. // jsons is unexported so can not be set in a .json file
  47. jsons map[string]bool
  48. path string
  49. name string
  50. // Projects name a whole subproject which is built independently of
  51. // this one. We'll need to be able to use environment variables at some point.
  52. Projects []string
  53. Pre []string
  54. Post []string
  55. Cflags []string
  56. Oflags []string
  57. Include []string
  58. SourceFiles []string
  59. ObjectFiles []string
  60. Libs []string
  61. Env []string
  62. ToolOpts map[string][]string
  63. // cmd's
  64. SourceFilesCmd []string
  65. // Targets.
  66. Program string
  67. Library string
  68. Install string // where to place the resulting binary/lib
  69. Kernel *kernel
  70. }
  71. type buildfile map[string]build
  72. // UnmarshalJSON works like the stdlib unmarshal would, except it adjusts all
  73. // paths.
  74. func (bf *buildfile) UnmarshalJSON(s []byte) error {
  75. r := make(map[string]build)
  76. if err := json.Unmarshal(s, &r); err != nil {
  77. return err
  78. }
  79. for k, b := range r {
  80. // we're getting a copy of the struct, remember.
  81. b.jsons = make(map[string]bool)
  82. b.Projects = adjust(b.Projects)
  83. b.Libs = adjust(b.Libs)
  84. b.Cflags = adjust(b.Cflags)
  85. b.ObjectFiles = adjust(b.ObjectFiles)
  86. b.Include = adjust(b.Include)
  87. b.Install = fromRoot(b.Install)
  88. for i, e := range b.Env {
  89. b.Env[i] = os.ExpandEnv(e)
  90. }
  91. r[k] = b
  92. }
  93. *bf = r
  94. return nil
  95. }
  96. var (
  97. cwd string
  98. harvey string
  99. regexpAll = []*regexp.Regexp{regexp.MustCompile(".")}
  100. // findTools looks at all env vars and absolutizes these paths
  101. // also respects TOOLPREFIX
  102. tools = map[string]string{
  103. "cc": "gcc",
  104. "ar": "ar",
  105. "ld": "ld",
  106. "ranlib": "ranlib",
  107. "strip": "strip",
  108. "sh": "sh",
  109. }
  110. arch = map[string]bool{
  111. "amd64": true,
  112. "riscv": true,
  113. "aarch64": true,
  114. }
  115. debugPrint = flag.Bool("debug", false, "enable debug prints")
  116. shellhack = flag.Bool("shellhack", false, "spawn every command in a shell (forced on if LD_PRELOAD is set)")
  117. )
  118. func debug(fmt string, s ...interface{}) {
  119. if *debugPrint {
  120. log.Printf(fmt, s...)
  121. }
  122. }
  123. // fail with message, if err is not nil
  124. func failOn(err error) {
  125. if err != nil {
  126. log.Fatalf("%v", err)
  127. }
  128. }
  129. func adjust(s []string) []string {
  130. for i, v := range s {
  131. s[i] = fromRoot(v)
  132. }
  133. return s
  134. }
  135. // return the given absolute path as an absolute path rooted at the harvey tree.
  136. func fromRoot(p string) string {
  137. p = os.ExpandEnv(p)
  138. if path.IsAbs(p) {
  139. return path.Join(harvey, p)
  140. }
  141. return p
  142. }
  143. // Sh sends cmd to a shell. It's needed to enable $LD_PRELOAD tricks,
  144. // see https://github.com/Harvey-OS/harvey/issues/8#issuecomment-131235178
  145. func sh(cmd *exec.Cmd) {
  146. shell := exec.Command(tools["sh"])
  147. shell.Env = cmd.Env
  148. if cmd.Args[0] == tools["sh"] && cmd.Args[1] == "-c" {
  149. cmd.Args = cmd.Args[2:]
  150. }
  151. commandString := strings.Join(cmd.Args, " ")
  152. if shStdin, e := shell.StdinPipe(); e == nil {
  153. go func() {
  154. defer shStdin.Close()
  155. io.WriteString(shStdin, commandString)
  156. }()
  157. } else {
  158. log.Fatalf("cannot pipe [%v] to %s: %v", commandString, tools["sh"], e)
  159. }
  160. shell.Stderr = os.Stderr
  161. shell.Stdout = os.Stdout
  162. debug("%q | sh\n", commandString)
  163. failOn(shell.Run())
  164. }
  165. func process(f, which string, b *build) {
  166. r := regexp.MustCompile(which)
  167. if b.jsons[f] {
  168. return
  169. }
  170. b.jsons[f] = true
  171. log.Printf("Including %v", f)
  172. d, err := ioutil.ReadFile(f)
  173. failOn(err)
  174. var builds buildfile
  175. failOn(json.Unmarshal(d, &builds))
  176. for n, build := range builds {
  177. log.Printf("Merging %v", n)
  178. for t,v := range build.ToolOpts {
  179. b.ToolOpts[t] = v
  180. }
  181. b.SourceFiles = append(b.SourceFiles, build.SourceFiles...)
  182. b.Cflags = append(b.Cflags, build.Cflags...)
  183. b.Oflags = append(b.Oflags, build.Oflags...)
  184. b.Pre = append(b.Pre, build.Pre...)
  185. b.Post = append(b.Post, build.Post...)
  186. b.Libs = append(b.Libs, build.Libs...)
  187. b.Projects = append(b.Projects, build.Projects...)
  188. b.Env = append(b.Env, build.Env...)
  189. b.SourceFilesCmd = append(b.SourceFilesCmd, build.SourceFilesCmd...)
  190. b.Program += build.Program
  191. b.Library += build.Library
  192. if build.Install != "" {
  193. if b.Install != "" {
  194. log.Fatalf("In file %s (target %s) included by %s (target %s): redefined Install.", f, n, build.path, build.name)
  195. }
  196. b.Install = build.Install
  197. }
  198. b.ObjectFiles = append(b.ObjectFiles, build.ObjectFiles...)
  199. // For each source file, assume we create an object file with the last char replaced
  200. // with 'o'. We can get smarter later.
  201. for _, v := range build.SourceFiles {
  202. f := path.Base(v)
  203. o := f[:len(f)-1] + "o"
  204. b.ObjectFiles = append(b.ObjectFiles, o)
  205. }
  206. for _, v := range build.Include {
  207. if !path.IsAbs(v) {
  208. wd := path.Dir(f)
  209. v = path.Join(wd, v)
  210. }
  211. include(v, b)
  212. }
  213. }
  214. }
  215. func appendIfMissing(s []string, v string) []string {
  216. for _, a := range s {
  217. if a == v {
  218. return s
  219. }
  220. }
  221. return append(s, v)
  222. }
  223. func process(f string, r []*regexp.Regexp) []build {
  224. log.Printf("Processing %v", f)
  225. var builds buildfile
  226. var results []build
  227. d, err := ioutil.ReadFile(f)
  228. failOn(err)
  229. failOn(json.Unmarshal(d, &builds))
  230. for n, build := range builds {
  231. build.name = n
  232. build.jsons = make(map[string]bool)
  233. build.ToolOpts = make(map[string][]string)
  234. skip := true
  235. for _, re := range r {
  236. if re.MatchString(build.name) {
  237. skip = false
  238. break
  239. }
  240. }
  241. if skip {
  242. continue
  243. }
  244. log.Printf("Run %v", build.name)
  245. build.jsons[f] = true
  246. build.path = path.Dir(f)
  247. // For each source file, assume we create an object file with the last char replaced
  248. // with 'o'. We can get smarter later.
  249. for _, v := range build.SourceFiles {
  250. f := path.Base(v)
  251. o := f[:len(f)-1] + "o"
  252. build.ObjectFiles = appendIfMissing(build.ObjectFiles, o)
  253. }
  254. for _, v := range build.Include {
  255. include(v, &build)
  256. }
  257. results = append(results, build)
  258. }
  259. return results
  260. }
  261. func buildkernel(b *build) {
  262. if b.Kernel == nil {
  263. return
  264. }
  265. codebuf := confcode(b.path, b.Kernel)
  266. failOn(ioutil.WriteFile(b.name+".c", codebuf, 0666))
  267. }
  268. func compile(b *build) {
  269. log.Printf("Building %s\n", b.name)
  270. // N.B. Plan 9 has a very well defined include structure, just three things:
  271. // /amd64/include, /sys/include, .
  272. args := []string{
  273. "-std=c11", "-c",
  274. "-I", fromRoot("/$ARCH/include"),
  275. "-I", fromRoot("/sys/include"),
  276. "-I", ".",
  277. }
  278. if toolOpts, ok := b.ToolOpts[tools["cc"]]; ok {
  279. args = append(args, toolOpts...)
  280. }
  281. args = append(args, b.Cflags...)
  282. if len(b.SourceFilesCmd) > 0 {
  283. for _, i := range b.SourceFilesCmd {
  284. cmd := exec.Command(tools["cc"], append(args, i)...)
  285. run(b, *shellhack, cmd)
  286. }
  287. return
  288. }
  289. args = append(args, b.SourceFiles...)
  290. cmd := exec.Command(tools["cc"], args...)
  291. run(b, *shellhack, cmd)
  292. }
  293. func link(b *build) {
  294. log.Printf("Linking %s\n", b.name)
  295. if len(b.SourceFilesCmd) > 0 {
  296. for _, n := range b.SourceFilesCmd {
  297. // Split off the last element of the file
  298. var ext = filepath.Ext(n)
  299. if len(ext) == 0 {
  300. log.Fatalf("refusing to overwrite extension-less source file %v", n)
  301. continue
  302. }
  303. n = n[:len(n)-len(ext)]
  304. f := path.Base(n)
  305. o := f[:len(f)] + ".o"
  306. args := []string{"-o", n, o}
  307. args = append(args, b.Oflags...)
  308. if toolOpts, ok := b.ToolOpts[tools["ld"]]; ok {
  309. args = append(args, toolOpts...)
  310. }
  311. args = append(args, "-L", fromRoot("/$ARCH/lib"))
  312. args = append(args, b.Libs...)
  313. run(b, *shellhack, exec.Command(tools["ld"], args...))
  314. }
  315. return
  316. }
  317. args := []string{"-o", b.Program}
  318. if toolOpts, ok := b.ToolOpts[tools["ld"]]; ok {
  319. args = append(args, toolOpts...)
  320. }
  321. args = append(args, b.ObjectFiles...)
  322. args = append(args, b.Oflags...)
  323. args = append(args, "-L", fromRoot("/$ARCH/lib"))
  324. args = append(args, b.Libs...)
  325. run(b, *shellhack, exec.Command(tools["ld"], args...))
  326. }
  327. func install(b *build) {
  328. if b.Install == "" {
  329. return
  330. }
  331. log.Printf("Installing %s\n", b.name)
  332. failOn(os.MkdirAll(b.Install, 0755))
  333. switch {
  334. case len(b.SourceFilesCmd) > 0:
  335. for _, n := range b.SourceFilesCmd {
  336. ext := filepath.Ext(n)
  337. exe := n[:len(n)-len(ext)]
  338. move(exe, b.Install)
  339. }
  340. case len(b.Program) > 0:
  341. move(b.Program, b.Install)
  342. case len(b.Library) > 0:
  343. libpath := path.Join(b.Install, b.Library)
  344. args := append([]string{"-rs", libpath}, b.ObjectFiles...)
  345. run(b, *shellhack, exec.Command(tools["ar"], args...))
  346. run(b, *shellhack, exec.Command(tools["ranlib"], libpath))
  347. }
  348. }
  349. func move(from, to string) {
  350. final := path.Join(to, from)
  351. log.Printf("move %s %s\n", from, final)
  352. _ = os.Remove(final)
  353. failOn(os.Link(from, final))
  354. failOn(os.Remove(from))
  355. }
  356. func run(b *build, pipe bool, cmd *exec.Cmd) {
  357. if b != nil {
  358. cmd.Env = append(os.Environ(), b.Env...)
  359. }
  360. cmd.Stdout = os.Stdout
  361. cmd.Stderr = os.Stderr
  362. if pipe {
  363. // Sh sends cmd to a shell. It's needed to enable $LD_PRELOAD tricks, see https://github.com/Harvey-OS/harvey/issues/8#issuecomment-131235178
  364. shell := exec.Command(tools["sh"])
  365. shell.Env = cmd.Env
  366. shell.Stderr = os.Stderr
  367. shell.Stdout = os.Stdout
  368. commandString := strings.Join(cmd.Args, " ")
  369. shStdin, err := shell.StdinPipe()
  370. if err != nil {
  371. log.Fatalf("cannot pipe [%v] to %s: %v", commandString, tools["sh"], err)
  372. }
  373. go func() {
  374. defer shStdin.Close()
  375. io.WriteString(shStdin, commandString)
  376. }()
  377. log.Printf("%q | sh\n", commandString)
  378. failOn(shell.Run())
  379. return
  380. }
  381. log.Println(strings.Join(cmd.Args, " "))
  382. failOn(cmd.Run())
  383. }
  384. func projects(b *build, r []*regexp.Regexp) {
  385. for _, v := range b.Projects {
  386. log.Printf("Doing %s\n", strings.TrimSuffix(v, ".json"))
  387. project(v, r)
  388. }
  389. }
  390. func dirPop(s string) {
  391. fmt.Printf("Leaving directory `%v'\n", s)
  392. failOn(os.Chdir(s))
  393. }
  394. func dirPush(s string) {
  395. fmt.Printf("Entering directory `%v'\n", s)
  396. failOn(os.Chdir(s))
  397. }
  398. // assumes we are in the wd of the project.
  399. func project(bf string, which []*regexp.Regexp) {
  400. cwd, err := os.Getwd()
  401. failOn(err)
  402. debug("Start new project cwd is %v", cwd)
  403. defer dirPop(cwd)
  404. dir := path.Dir(bf)
  405. root := path.Base(bf)
  406. debug("CD to %v and build using %v", dir, root)
  407. dirPush(dir)
  408. builds := process(root, which)
  409. debug("Processing %v: %d target", root, len(builds))
  410. for _, b := range builds {
  411. debug("Processing %v: %v", b.name, b)
  412. projects(&b, regexpAll)
  413. for _, c := range b.Pre {
  414. // this is a hack: we just pass the command through as an exec.Cmd
  415. run(&b, true, exec.Command(c))
  416. }
  417. buildkernel(&b)
  418. if len(b.SourceFiles) > 0 || len(b.SourceFilesCmd) > 0 {
  419. compile(&b)
  420. }
  421. if b.Program != "" || len(b.SourceFilesCmd) > 0 {
  422. link(&b)
  423. }
  424. install(&b)
  425. for _, c := range b.Post {
  426. run(&b, true, exec.Command(c))
  427. }
  428. }
  429. install(b)
  430. run(b, b.Post)
  431. }
  432. func main() {
  433. // A small amount of setup is done in the paths*.go files. They are
  434. // OS-specific path setup/manipulation. "harvey" is set there and $PATH is
  435. // adjusted.
  436. var err error
  437. findTools(os.Getenv("TOOLPREFIX"))
  438. flag.Parse()
  439. cwd, err = os.Getwd()
  440. failOn(err)
  441. a := os.Getenv("ARCH")
  442. if a == "" || !arch[a] {
  443. s := []string{}
  444. for i := range arch {
  445. s = append(s, i)
  446. }
  447. log.Fatalf("You need to set the ARCH environment variable from: %v", s)
  448. }
  449. // ensure this is exported, in case we used a default value
  450. os.Setenv("HARVEY", harvey)
  451. if os.Getenv("LD_PRELOAD") != "" {
  452. log.Println("Using shellhack")
  453. *shellhack = true
  454. }
  455. // If no args, assume 'build.json'
  456. // If 1 arg, that's a dir or file name.
  457. // if two args, that's a dir and a regular expression.
  458. f := "build.json"
  459. if len(flag.Args()) > 0 {
  460. f = flag.Arg(0)
  461. }
  462. bf, err := findBuildfile(f)
  463. failOn(err)
  464. re := []*regexp.Regexp{regexp.MustCompile(".")}
  465. if len(flag.Args()) > 1 {
  466. re = re[:0]
  467. for _, r := range flag.Args()[1:] {
  468. rx, err := regexp.Compile(r)
  469. failOn(err)
  470. re = append(re, rx)
  471. }
  472. }
  473. project(bf, re)
  474. }
  475. func findTools(toolprefix string) {
  476. var err error
  477. for k, v := range tools {
  478. if x := os.Getenv(strings.ToUpper(k)); x != "" {
  479. v = x
  480. }
  481. v, err = exec.LookPath(toolprefix + v)
  482. failOn(err)
  483. tools[k] = v
  484. }
  485. }
  486. // disambiguate the buildfile argument
  487. func findBuildfile(f string) (string, error) {
  488. try := []string{
  489. f,
  490. path.Join(f, "build.json"),
  491. fromRoot(path.Join("/sys/src", f+".json")),
  492. fromRoot(path.Join("/sys/src", f, "build.json")),
  493. }
  494. for _, p := range try {
  495. if fi, err := os.Stat(p); err == nil && !fi.IsDir() {
  496. return p, nil
  497. }
  498. }
  499. return "", fmt.Errorf("unable to find buildfile (tried %s)", strings.Join(try, ", "))
  500. }