github.com/cloudwego/iasm@v0.2.0/obj/obj.go (about)

     1  //
     2  // Copyright 2024 CloudWeGo Authors
     3  //
     4  // Licensed under the Apache License, Version 2.0 (the "License");
     5  // you may not use this file except in compliance with the License.
     6  // You may obtain a copy of the License at
     7  //
     8  //     http://www.apache.org/licenses/LICENSE-2.0
     9  //
    10  // Unless required by applicable law or agreed to in writing, software
    11  // distributed under the License is distributed on an "AS IS" BASIS,
    12  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  // See the License for the specific language governing permissions and
    14  // limitations under the License.
    15  //
    16  
    17  package obj
    18  
    19  import (
    20      `fmt`
    21      `io`
    22      `os`
    23  )
    24  
    25  // Format represents the saved binary file format.
    26  type Format int
    27  
    28  const (
    29      // ELF indicates it should be saved as an ELF binary.
    30      ELF Format = iota
    31  
    32      // MachO indicates it should be saved as a Mach-O binary.
    33      MachO
    34  )
    35  
    36  var formatTab = [...]func(w io.Writer, code []byte, base uint64, entry uint64) error {
    37      ELF   : nil,
    38      MachO : assembleMachO,
    39  }
    40  
    41  var formatNames = map[Format]string {
    42      ELF   : "ELF",
    43      MachO : "Mach-O",
    44  }
    45  
    46  // String returns the name of a specified format.
    47  func (self Format) String() string {
    48      if v, ok := formatNames[self]; ok {
    49          return v
    50      } else {
    51          return fmt.Sprintf("Format(%d)", self)
    52      }
    53  }
    54  
    55  // Write assembles a binary executable.
    56  func (self Format) Write(w io.Writer, code []byte, base uint64, entry uint64) error {
    57      if self >= 0 && int(self) < len(formatTab) && formatTab[self] != nil {
    58          return formatTab[self](w, code, base, entry)
    59      } else {
    60          return fmt.Errorf("unsupported format: %s", self)
    61      }
    62  }
    63  
    64  // Generate generates a binary executable file from the specified code.
    65  func (self Format) Generate(name string, code []byte, base uint64, entry uint64) error {
    66      var fp *os.File
    67      var err error
    68  
    69      /* create the output file */
    70      if fp, err = os.Create(name); err != nil {
    71          return err
    72      }
    73  
    74      /* generate the code */
    75      if err = self.Write(fp, code, base, entry); err != nil {
    76          _ = fp.Close()
    77          _ = os.Remove(name)
    78          return err
    79      }
    80  
    81      /* close the file and make it executable */
    82      _ = fp.Close()
    83      _ = os.Chmod(name, 0755)
    84      return nil
    85  }