removemach.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package main
  2. import (
  3. "bytes"
  4. "debug/elf"
  5. "flag"
  6. "fmt"
  7. "io/ioutil"
  8. "os"
  9. "path/filepath"
  10. "strings"
  11. )
  12. var dry = flag.Bool("dryrun", true, "don't really do it")
  13. func main() {
  14. flag.Parse()
  15. a := flag.Args()
  16. for _, n := range a {
  17. f, err := elf.Open(n)
  18. if err != nil {
  19. fmt.Printf("%v %v\n", n, err)
  20. continue
  21. }
  22. s, err := f.Symbols()
  23. if err != nil {
  24. fmt.Printf("%v %v\n", n, err)
  25. continue
  26. }
  27. usem := false
  28. for _, v := range s {
  29. if v.Name == "m" && v.Section == elf.SHN_UNDEF {
  30. usem = true
  31. cf := strings.Split(n, ".")
  32. globs, err := filepath.Glob("../*/" + cf[0] + ".c")
  33. if err != nil || len(globs) == 0 {
  34. fmt.Fprintf(os.Stderr, "%v has NO source?\n", cf[0])
  35. continue
  36. }
  37. if len(globs) > 1 {
  38. fmt.Fprintf(os.Stderr, "Skipping %v has more than one source?\n", cf[0])
  39. continue
  40. }
  41. file := globs[0]
  42. fi, err := os.Stat(file)
  43. if err != nil {
  44. fmt.Fprintf(os.Stderr, "%v\n", err)
  45. continue
  46. }
  47. /* OK, read it in, write it out */
  48. b, err := ioutil.ReadFile(file)
  49. if err != nil {
  50. fmt.Fprintf(os.Stderr, "%v: %v\n", file, err)
  51. }
  52. header := []byte("extern Mach *m; // REMOVE ME\n")
  53. if bytes.Compare(header[:], b[0:len(header)]) == 0 {
  54. fmt.Fprintf(os.Stderr, "%v already done; skipping\n", file)
  55. continue
  56. }
  57. out := append([]byte("typedef struct Mach Mach; extern Mach *m; // REMOVE ME\n"), b...)
  58. if *dry {
  59. fmt.Fprintf(os.Stderr, "Would do %v mode %v\n", file, fi.Mode())
  60. continue
  61. }
  62. if err := ioutil.WriteFile(file, out, fi.Mode()); err != nil {
  63. fmt.Fprintf(os.Stderr, "Write %v failed: %v; git checkout %v\n", file, err, file)
  64. }
  65. }
  66. }
  67. if !usem {
  68. fmt.Fprintf(os.Stderr, "Ignored %v as it did not reference Mach *m\n", n)
  69. } else {
  70. fmt.Fprintf(os.Stderr, "Procssed %v as it did reference Mach *m\n", n)
  71. }
  72. }
  73. }