gpt4 book ai didi

Xcode 和 NASM 编码

转载 作者:行者123 更新时间:2023-12-02 15:03:32 25 4
gpt4 key购买 nike

如何在 Xcode 中用汇编语言编写和构建程序?

我搜索过,但没有成功。你能帮助我吗?如果无法在 xcode 中编写 NASM,请推荐一些好的 IDE。

最佳答案

自从您提出这个问题以来,这可能已经发生了变化,但目前正在安装 Xcode command line tools (安装 Xcode 后)安装 NASM (网络汇编器)和GASM (GNU 汇编器)。要开始在汇编中进行编码,您有几个选项,具体取决于您正在执行的操作:即在 Xcode 中构建,或使用 NASM 在终端中构建。或GASM直接地。

Xcode 9.4.1

如果您想使用 IDE,您可以通过单击“文件 > 新文件”将程序集文件添加到 Xcode 中,然后搜索“程序集”,您将看到程序集文件类型。或者,您可以添加一个空白文件,然后从文件检查器的“类型”下拉列表中手动选择文件类型。除非您的应用程序需要 Cocoa 框架,否则您应该在项目/目标创建期间创建命令行应用程序而不是 Cocoa 应用程序。作为示例命令行程序:

hello.asm(来自引用文献中列出的教程站点):

global    _start

section .text

_start: mov rax, 0x02000004 ; system call for write
mov rdi, 1 ; file handle 1 is stdout
mov rsi, message ; address of string to output
mov rdx, 13 ; number of bytes
syscall ; invoke operating system to do the write
mov rax, 0x02000001 ; system call for exit
xor rdi, rdi ; exit code 0
syscall ; invoke operating system to exit

section .data
message: db "Hello, World", 10 ; note the newline at the end

main.swift:

import Foundation

// Generate a "name" for the assembler operation that may be used
// as a Swift function.
@_silgen_name("start") func start() -> String

// Create a fake struct to use our function. We return 0 so that we
// can call `variable()` below without any warnings (because we're
// we're setting something).
struct Test {
func variable() -> Int32 {
print(start())
return 0
}
}

// Declare a test instance and call `variable`. `x` is merely acting
// as a placeholder so we can call variable and not get warnings for
// this test example.
let x = Test().variable()

如果您希望使用 C 而不是 Swift 进行汇编操作,则需要创建头文件而不是使用 @_silgen_name :

#ifndef Bridging_Header_h
#define Bridging_Header_h

const char *start(void);

#endif /* Bridging-Header_h */
装配体构建规则

重要的是,您还需要为目标提供“构建规则”。为此:

  1. 点击项目导航器中的项目图标
  2. 在目标列表中选择适当的目标
  3. 点击“构建规则”选项卡
  4. 在搜索字段中搜索 NASM
  5. 点击“复制到目标”,并确保“进程”设置为“NASM 程序集文件”,“使用”设置为“自定义脚本”
  6. 在下面的“自定义脚本”部分中,输入以下命令(确保路径指向您的 NASM 汇编程序的位置):
    /usr/local/bin/nasm -f macho64 ${INPUT_FILE_PATH} -o ${SCRIPT_OUTPUT_FILE_0}这是一个终端命令——要了解更多信息,请输入 man nasm在终端中。
  7. 然后点击“输出文件”部分中的加号并添加以下内容:
    $(DERIVED_FILE_DIR)/${INPUT_FILE_BASE}.o

此构建规则对于避免出现“未找到架构 x86_64 的符号”的编译器错误至关重要。

终端

如果您不介意,或者可能更喜欢在终端中工作,您可以使用您选择的文本编辑器( vimnanoemacs 内置于终端中,并且 TextEdit 内置于 macOS 中)来创建您的程序集文件。然后使用nasmgasm组合文件的命令。类型man nasmman gasm了解您可以使用的各种选项。

引用文献:
汇编代码示例 - hello.asm
从 Swift 或 C 引用程序集(需要桥接头)- Daniel Tran
构建规则 - Metric Panda

关于Xcode 和 NASM 编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20556241/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com