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

     1  //go:build darwin
     2  // +build darwin
     3  
     4  //
     5  // Copyright 2024 CloudWeGo Authors
     6  //
     7  // Licensed under the Apache License, Version 2.0 (the "License");
     8  // you may not use this file except in compliance with the License.
     9  // You may obtain a copy of the License at
    10  //
    11  //     http://www.apache.org/licenses/LICENSE-2.0
    12  //
    13  // Unless required by applicable law or agreed to in writing, software
    14  // distributed under the License is distributed on an "AS IS" BASIS,
    15  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    16  // See the License for the specific language governing permissions and
    17  // limitations under the License.
    18  //
    19  
    20  package x86_64
    21  
    22  import (
    23      `fmt`
    24      `os`
    25      `os/exec`
    26      `testing`
    27  
    28      `github.com/cloudwego/iasm/obj`
    29      `github.com/davecgh/go-spew/spew`
    30      `github.com/stretchr/testify/require`
    31  )
    32  
    33  func TestAssembler_Assemble(t *testing.T) {
    34      p := new(Assembler)
    35      e := p.Assemble(`
    36  .org 0x08000000
    37  .entry start
    38  
    39  msg:
    40      .ascii "hello, world\n"
    41  
    42  start:
    43      movl    $1, %edi
    44      leaq    msg(%rip), %rsi
    45      movl    $13, %edx
    46      movl    $0x02000004, %eax
    47      syscall
    48      xorl    %edi, %edi
    49      movl    $0x02000001, %eax
    50      syscall
    51  `)
    52      require.NoError(t, e)
    53      code := p.Code()
    54      base := p.Base()
    55      entry := p.Entry()
    56      spew.Dump(code)
    57      fmt.Printf("Image Base  : %#x\n", base)
    58      fmt.Printf("Entry Point : %#x\n", entry)
    59      fp, err := os.CreateTemp("", "macho_out-")
    60      require.NoError(t, err)
    61      err = obj.MachO.Write(fp, code, uint64(base), uint64(entry))
    62      require.NoError(t, err)
    63      err = fp.Close()
    64      require.NoError(t, err)
    65      err = os.Chmod(fp.Name(), 0755)
    66      require.NoError(t, err)
    67      println("Saved to", fp.Name())
    68      out, err := exec.Command(fp.Name()).Output()
    69      require.NoError(t, err)
    70      spew.Dump(out)
    71      require.Equal(t, []byte("hello, world\n"), out)
    72      err = os.Remove(fp.Name())
    73      require.NoError(t, err)
    74  }