github.com/chenzhuoyu/iasm@v0.9.1/obj/obj.go (about) 1 package obj 2 3 import ( 4 `fmt` 5 `io` 6 `os` 7 ) 8 9 // Format represents the saved binary file format. 10 type Format int 11 12 const ( 13 // ELF indicates it should be saved as an ELF binary. 14 ELF Format = iota 15 16 // MachO indicates it should be saved as a Mach-O binary. 17 MachO 18 ) 19 20 var formatTab = [...]func(w io.Writer, code []byte, base uint64, entry uint64) error { 21 ELF : nil, 22 MachO : assembleMachO, 23 } 24 25 var formatNames = map[Format]string { 26 ELF : "ELF", 27 MachO : "Mach-O", 28 } 29 30 // String returns the name of a specified format. 31 func (self Format) String() string { 32 if v, ok := formatNames[self]; ok { 33 return v 34 } else { 35 return fmt.Sprintf("Format(%d)", self) 36 } 37 } 38 39 // Write assembles a binary executable. 40 func (self Format) Write(w io.Writer, code []byte, base uint64, entry uint64) error { 41 if self >= 0 && int(self) < len(formatTab) && formatTab[self] != nil { 42 return formatTab[self](w, code, base, entry) 43 } else { 44 return fmt.Errorf("unsupported format: %s", self) 45 } 46 } 47 48 // Generate generates a binary executable file from the specified code. 49 func (self Format) Generate(name string, code []byte, base uint64, entry uint64) error { 50 var fp *os.File 51 var err error 52 53 /* create the output file */ 54 if fp, err = os.Create(name); err != nil { 55 return err 56 } 57 58 /* generate the code */ 59 if err = self.Write(fp, code, base, entry); err != nil { 60 _ = fp.Close() 61 _ = os.Remove(name) 62 return err 63 } 64 65 /* close the file and make it executable */ 66 _ = fp.Close() 67 _ = os.Chmod(name, 0755) 68 return nil 69 }