diff options
| author | ruki <[email protected]> | 2025-12-07 17:47:01 +0800 |
|---|---|---|
| committer | ruki <[email protected]> | 2025-12-07 17:47:01 +0800 |
| commit | f4cd87b0135d84932f186bc068a5232912ee43b9 (patch) | |
| tree | 1e1bba0e8a5160cc4a9cd8f5de0bdef15ea2ba64 /core/src/xmake/binutils | |
| parent | 35aeaac3f956f26f188ebab40c443b64d2cb2f95 (diff) | |
update bin2c
Diffstat (limited to 'core/src/xmake/binutils')
| -rw-r--r-- | core/src/xmake/binutils/bin2c.c | 222 | ||||
| -rw-r--r-- | core/src/xmake/binutils/bin2coff.c | 406 | ||||
| -rw-r--r-- | core/src/xmake/binutils/bin2elf.c | 856 | ||||
| -rw-r--r-- | core/src/xmake/binutils/bin2macho.c | 887 | ||||
| -rw-r--r-- | core/src/xmake/binutils/prefix.h | 70 |
5 files changed, 2441 insertions, 0 deletions
diff --git a/core/src/xmake/binutils/bin2c.c b/core/src/xmake/binutils/bin2c.c new file mode 100644 index 000000000..b5054c55f --- /dev/null +++ b/core/src/xmake/binutils/bin2c.c @@ -0,0 +1,222 @@ +/*!A cross-platform build utility based on Lua + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright (C) 2015-present, Xmake Open Source Community. + * + * @author ruki + * @file bin2c.c + * + */ + +/* ////////////////////////////////////////////////////////////////////////////////////// + * trace + */ +#define TB_TRACE_MODULE_NAME "bin2c" +#define TB_TRACE_MODULE_DEBUG (0) + +/* ////////////////////////////////////////////////////////////////////////////////////// + * includes + */ +#include "prefix.h" + +/* ////////////////////////////////////////////////////////////////////////////////////// + * macros + */ + +#define XM_BIN2C_DATA_SIZE (8 * 1024) +#define XM_BIN2C_LINE_SIZE (4 * 1024) +#define XM_BIN2C_LINEWIDTH_MAX ((XM_BIN2C_LINE_SIZE - 2) / 6) + +/* ////////////////////////////////////////////////////////////////////////////////////// + * private implementation + */ + +// optimized hex conversion table +static tb_char_t const *xm_binutils_bin2c_digits = "0123456789ABCDEF"; + +// inline hex conversion for better performance +static __tb_inline__ tb_void_t xm_binutils_bin2c_write_hex(tb_char_t *str, tb_byte_t value) { + str[0] = ' '; + str[1] = '0'; + str[2] = 'x'; + str[3] = xm_binutils_bin2c_digits[(value >> 4) & 15]; + str[4] = xm_binutils_bin2c_digits[value & 15]; +} + +static tb_bool_t xm_binutils_bin2c_dump(tb_stream_ref_t istream, + tb_stream_ref_t ostream, + tb_int_t linewidth, + tb_bool_t nozeroend) { + + tb_bool_t first = tb_true; + tb_bool_t zero_pending = tb_false; + tb_byte_t data[XM_BIN2C_DATA_SIZE]; + tb_char_t line[XM_BIN2C_LINE_SIZE]; + tb_size_t linesize = 0; + tb_size_t bytes_in_line = 0; + tb_size_t data_pos = 0; + tb_size_t data_size = 0; + tb_assert_and_check_return_val(linewidth > 0 && linewidth <= XM_BIN2C_LINEWIDTH_MAX, tb_false); + + while (!tb_stream_beof(istream) || data_pos < data_size || zero_pending) { + // read a large chunk of data if buffer is empty + if (data_pos >= data_size) { + // handle pending zero terminator + if (zero_pending) { + data[0] = '\0'; + data_size = 1; + data_pos = 0; + zero_pending = tb_false; + } else { + tb_hong_t left = tb_stream_left(istream); + tb_size_t to_read = (tb_size_t)tb_min(left, (tb_hong_t)XM_BIN2C_DATA_SIZE); + tb_check_break(to_read); + + if (!tb_stream_bread(istream, data, to_read)) { + break; + } + data_size = to_read; + data_pos = 0; + + // check if we need to add zero terminator at the end + if (!nozeroend && tb_stream_beof(istream)) { + if (data_size < XM_BIN2C_DATA_SIZE) { + // can add directly to current buffer + data[data_size++] = '\0'; + } else { + // buffer is full, need to add zero in next iteration + zero_pending = tb_true; + } + } + } + } + + // process bytes from buffer + while (data_pos < data_size) { + // check if we need a new line + if (bytes_in_line >= (tb_size_t)linewidth) { + // write line (tb_stream_bwrit_line will add newline automatically) + if (tb_stream_bwrit_line(ostream, line, linesize) < 0) { + return tb_false; + } + + linesize = 0; + bytes_in_line = 0; + first = tb_false; + } + + // ensure we have enough space in line buffer (6 chars per byte: ", 0xXX") + if (linesize + 6 > sizeof(line)) { + // flush partial line if buffer is full + if (linesize > 0) { + if (!tb_stream_bwrit(ostream, (tb_byte_t *)line, linesize)) { + return tb_false; + } + linesize = 0; + } + } + + // add separator + if (bytes_in_line == 0 && first) { + line[linesize++] = ' '; + first = tb_false; + } else { + line[linesize++] = ','; + } + + // write hex value (inline for performance) + xm_binutils_bin2c_write_hex(line + linesize, data[data_pos]); + linesize += 5; + bytes_in_line++; + data_pos++; + } + } + + // flush remaining line + if (linesize > 0) { + // write line (tb_stream_bwrit_line will add newline automatically) + if (tb_stream_bwrit_line(ostream, line, linesize) < 0) { + return tb_false; + } + } + + return tb_stream_beof(istream); +} + +/* ////////////////////////////////////////////////////////////////////////////////////// + * implementation + */ + +/* generate c/c++ code from the binary file + * + * local ok, errors = binutils.bin2c(binaryfile, outputfile, linewidth, nozeroend) + */ +tb_int_t xm_binutils_bin2c(lua_State *lua) { + tb_assert_and_check_return_val(lua, 0); + + // get the binaryfile + tb_char_t const *binaryfile = luaL_checkstring(lua, 1); + tb_check_return_val(binaryfile, 0); + + // get the outputfile + tb_char_t const *outputfile = luaL_checkstring(lua, 2); + tb_check_return_val(outputfile, 0); + + // get line width + tb_int_t linewidth = (tb_int_t)lua_tointeger(lua, 3); + + // no zero end? + tb_bool_t nozeroend = (tb_bool_t)lua_toboolean(lua, 4); + + // do dump + tb_bool_t ok = tb_false; + tb_stream_ref_t istream = tb_stream_init_from_file(binaryfile, TB_FILE_MODE_RO); + tb_stream_ref_t ostream = tb_stream_init_from_file(outputfile, + TB_FILE_MODE_RW | TB_FILE_MODE_CREAT | TB_FILE_MODE_TRUNC); + do { + if (!tb_stream_open(istream)) { + lua_pushboolean(lua, tb_false); + lua_pushfstring(lua, "bin2c: open %s failed", binaryfile); + break; + } + + if (!tb_stream_open(ostream)) { + lua_pushboolean(lua, tb_false); + lua_pushfstring(lua, "bin2c: open %s failed", outputfile); + break; + } + + if (!xm_binutils_bin2c_dump(istream, ostream, linewidth, nozeroend)) { + lua_pushboolean(lua, tb_false); + lua_pushfstring(lua, "bin2c: dump data failed"); + break; + } + + ok = tb_true; + lua_pushboolean(lua, ok); + + } while (0); + + if (istream) { + tb_stream_clos(istream); + } + istream = tb_null; + + if (ostream) { + tb_stream_clos(ostream); + } + ostream = tb_null; + + return ok ? 1 : 2; +} diff --git a/core/src/xmake/binutils/bin2coff.c b/core/src/xmake/binutils/bin2coff.c new file mode 100644 index 000000000..686b89fac --- /dev/null +++ b/core/src/xmake/binutils/bin2coff.c @@ -0,0 +1,406 @@ +/*!A cross-platform build utility based on Lua + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright (C) 2015-present, Xmake Open Source Community. + * + * @author ruki + * @file bin2coff.c + * + */ + +/* ////////////////////////////////////////////////////////////////////////////////////// + * trace + */ +#define TB_TRACE_MODULE_NAME "bin2coff" +#define TB_TRACE_MODULE_DEBUG (0) + +/* ////////////////////////////////////////////////////////////////////////////////////// + * includes + */ +#include "prefix.h" + +/* ////////////////////////////////////////////////////////////////////////////////////// + * macros + */ +#define XM_COFF_MACHINE_I386 0x014c +#define XM_COFF_MACHINE_AMD64 0x8664 +#define XM_COFF_MACHINE_ARM 0x01c0 +#define XM_COFF_MACHINE_ARM64 0xaa64 + +#define XM_COFF_SECTION_RDATA 0x40000040 // IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ + +/* ////////////////////////////////////////////////////////////////////////////////////// + * types + */ +#include "tbox/prefix/packed.h" +typedef struct __xm_coff_header_t { + tb_uint16_t machine; + tb_uint16_t nsects; + tb_uint32_t time; + tb_uint32_t symtabofs; + tb_uint32_t nsyms; + tb_uint16_t opthdr; + tb_uint16_t flags; +} __tb_packed__ xm_coff_header_t; + +typedef struct __xm_coff_section_t { + tb_char_t name[8]; + tb_uint32_t vsize; + tb_uint32_t vaddr; + tb_uint32_t size; + tb_uint32_t ofs; + tb_uint32_t relocofs; + tb_uint32_t linenoofs; + tb_uint16_t nreloc; + tb_uint16_t nlineno; + tb_uint32_t flags; +} __tb_packed__ xm_coff_section_t; + +typedef struct __xm_coff_symbol_t { + union { + struct { + tb_char_t name[8]; + } shortname; + struct { + tb_uint32_t zeros; + tb_uint32_t offset; + } longname; + } n; + tb_uint32_t value; + tb_int16_t sect; + tb_uint16_t type; + tb_uint8_t scl; + tb_uint8_t naux; +} __tb_packed__ xm_coff_symbol_t; + +typedef struct __xm_coff_aux_section_t { + tb_uint32_t length; + tb_uint16_t nreloc; + tb_uint16_t nlineno; + tb_uint8_t reserved[10]; +} __tb_packed__ xm_coff_aux_section_t; + +typedef struct __xm_coff_symbol_tail_t { + tb_uint32_t value; + tb_int16_t sect; + tb_uint16_t type; + tb_uint8_t scl; + tb_uint8_t naux; +} __tb_packed__ xm_coff_symbol_tail_t; +#include "tbox/prefix/packed.h" + +/* ////////////////////////////////////////////////////////////////////////////////////// + * private implementation + */ +static tb_uint16_t xm_binutils_bin2coff_get_machine(tb_char_t const *arch) { + if (!arch) { + return XM_COFF_MACHINE_I386; + } + if (tb_strcmp(arch, "x86_64") == 0 || tb_strcmp(arch, "x64") == 0) { + return XM_COFF_MACHINE_AMD64; + } else if (tb_strcmp(arch, "arm64") == 0 || tb_strcmp(arch, "aarch64") == 0) { + return XM_COFF_MACHINE_ARM64; + } else if (tb_strcmp(arch, "arm") == 0) { + return XM_COFF_MACHINE_ARM; + } else if (tb_strcmp(arch, "i386") == 0 || tb_strcmp(arch, "x86") == 0) { + return XM_COFF_MACHINE_I386; + } + return XM_COFF_MACHINE_I386; +} + +static tb_void_t xm_binutils_bin2coff_write_string(tb_stream_ref_t ostream, tb_char_t const *str, tb_size_t len) { + tb_assert_and_check_return(ostream && str); + if (len == 0) { + len = tb_strlen(str); + } + tb_stream_bwrit(ostream, (tb_byte_t const *)str, len); +} + +static tb_void_t xm_binutils_bin2coff_write_padding(tb_stream_ref_t ostream, tb_size_t count) { + tb_assert_and_check_return(ostream); + tb_byte_t zero = 0; + while (count-- > 0) { + tb_stream_bwrit(ostream, &zero, 1); + } +} + +static tb_void_t xm_binutils_bin2coff_write_symbol_name(tb_stream_ref_t ostream, tb_char_t const *name, tb_uint32_t *strtab_offset) { + tb_assert_and_check_return(ostream && name && strtab_offset); + tb_size_t len = tb_strlen(name); + if (len <= 8) { + // short name: store directly in symbol name field + xm_binutils_bin2coff_write_string(ostream, name, len); + if (len < 8) { + xm_binutils_bin2coff_write_padding(ostream, 8 - len); + } + } else { + // long name: store offset in string table + tb_uint32_t zeros = 0; + tb_stream_bwrit(ostream, (tb_byte_t const *)&zeros, 4); + tb_stream_bwrit(ostream, (tb_byte_t const *)strtab_offset, 4); + *strtab_offset += (tb_uint32_t)(len + 1); // +1 for null terminator + } +} + +static tb_bool_t xm_binutils_bin2coff_dump(tb_stream_ref_t istream, + tb_stream_ref_t ostream, + tb_char_t const *symbol_prefix, + tb_char_t const *arch, + tb_char_t const *basename, + tb_bool_t zeroend) { + tb_assert_and_check_return_val(istream && ostream, tb_false); + + // get file size + tb_hong_t filesize = tb_stream_size(istream); + if (filesize < 0 || filesize > 0xffffffffU) { + return tb_false; + } + tb_uint32_t datasize = (tb_uint32_t)filesize; + // add null terminator if zeroend is true + if (zeroend) { + if (datasize >= 0xffffffffU) { + return tb_false; // would overflow + } + datasize++; + } + + // generate symbol names from filename + tb_char_t symbol_name[256] = {0}; + tb_char_t symbol_start[256] = {0}; + tb_char_t symbol_end[256] = {0}; + + // use basename or default to "data" + if (!basename || !basename[0]) { + basename = "data"; + } + + // build symbol name + if (symbol_prefix) { + tb_snprintf(symbol_name, sizeof(symbol_name), "%s%s", symbol_prefix, basename); + } else { + tb_snprintf(symbol_name, sizeof(symbol_name), "_binary_%s", basename); + } + + // replace non-alphanumeric with underscore + for (tb_size_t i = 0; symbol_name[i]; i++) { + if (!tb_isalpha(symbol_name[i]) && !tb_isdigit(symbol_name[i]) && symbol_name[i] != '_') { + symbol_name[i] = '_'; + } + } + + tb_snprintf(symbol_start, sizeof(symbol_start), "%s_start", symbol_name); + tb_snprintf(symbol_end, sizeof(symbol_end), "%s_end", symbol_name); + + // calculate offsets + tb_uint32_t header_size = sizeof(xm_coff_header_t); + tb_uint32_t section_header_size = sizeof(xm_coff_section_t); + tb_uint32_t section_data_ofs = header_size + section_header_size; + tb_uint32_t section_data_size = datasize; + tb_uint32_t symbol_table_ofs = section_data_ofs + ((section_data_size + 3) & ~3); // align to 4 bytes + tb_uint32_t string_table_size = 4; // initial 4-byte size field + + // calculate string table size + tb_size_t start_len = tb_strlen(symbol_start); + tb_size_t end_len = tb_strlen(symbol_end); + if (start_len > 8) { + string_table_size += (tb_uint32_t)(start_len + 1); + } + if (end_len > 8) { + string_table_size += (tb_uint32_t)(end_len + 1); + } + + // write COFF header + xm_coff_header_t header; + tb_memset(&header, 0, sizeof(header)); + header.machine = xm_binutils_bin2coff_get_machine(arch); + header.nsects = 1; + header.time = 0; + header.symtabofs = symbol_table_ofs; + header.nsyms = 4; // .rdata section symbol (1) + auxiliary entry (1) + 2 data symbols (start, end) + header.opthdr = 0; + header.flags = 0; + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)&header, sizeof(header))) { + return tb_false; + } + + // write section header (.rdata) + xm_coff_section_t section; + tb_memset(§ion, 0, sizeof(section)); + tb_strncpy(section.name, ".rdata", 8); + section.vsize = datasize; + section.vaddr = 0; + section.size = datasize; + section.ofs = section_data_ofs; + section.relocofs = 0; + section.linenoofs = 0; + section.nreloc = 0; + section.nlineno = 0; + section.flags = XM_COFF_SECTION_RDATA; + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)§ion, sizeof(section))) { + return tb_false; + } + + // write section data + if (!xm_binutils_stream_copy(istream, ostream, filesize)) { + return tb_false; + } + // append null terminator if zeroend is true + if (zeroend) { + tb_byte_t zero = 0; + if (!tb_stream_bwrit(ostream, &zero, 1)) { + return tb_false; + } + } + + // align to 4 bytes + tb_uint32_t padding = (4 - (section_data_size & 3)) & 3; + if (padding > 0) { + xm_binutils_bin2coff_write_padding(ostream, padding); + } + + // write symbol table + // symbol 0: .rdata section symbol + xm_coff_symbol_t sym_section; + tb_memset(&sym_section, 0, sizeof(sym_section)); + tb_strncpy(sym_section.n.shortname.name, ".rdata", 8); + sym_section.value = 0; + sym_section.sect = 1; // section index (1-based) + sym_section.type = 0; // IMAGE_SYM_TYPE_NULL + sym_section.scl = 3; // IMAGE_SYM_CLASS_STATIC + sym_section.naux = 1; // auxiliary entry + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)&sym_section, sizeof(sym_section))) { + return tb_false; + } + // auxiliary entry for section (18 bytes total) + xm_coff_aux_section_t aux_section; + tb_memset(&aux_section, 0, sizeof(aux_section)); + aux_section.length = datasize; + aux_section.nreloc = 0; + aux_section.nlineno = 0; + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)&aux_section, sizeof(aux_section))) { + return tb_false; + } + + // symbol 1: _binary_xxx_start + tb_uint32_t strtab_offset = 4; // start after size field + xm_binutils_bin2coff_write_symbol_name(ostream, symbol_start, &strtab_offset); + xm_coff_symbol_tail_t sym_start_tail; + tb_memset(&sym_start_tail, 0, sizeof(sym_start_tail)); + sym_start_tail.value = 0; + sym_start_tail.sect = 1; + sym_start_tail.scl = 2; // IMAGE_SYM_CLASS_EXTERNAL + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)&sym_start_tail, sizeof(sym_start_tail))) { + return tb_false; + } + + // symbol 2: _binary_xxx_end + xm_binutils_bin2coff_write_symbol_name(ostream, symbol_end, &strtab_offset); + xm_coff_symbol_tail_t sym_end_tail; + tb_memset(&sym_end_tail, 0, sizeof(sym_end_tail)); + sym_end_tail.value = datasize; + sym_end_tail.sect = 1; + sym_end_tail.scl = 2; // IMAGE_SYM_CLASS_EXTERNAL + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)&sym_end_tail, sizeof(sym_end_tail))) { + return tb_false; + } + + // write string table + tb_stream_bwrit(ostream, (tb_byte_t const *)&string_table_size, 4); + if (start_len > 8) { + xm_binutils_bin2coff_write_string(ostream, symbol_start, start_len); + tb_byte_t null = 0; + tb_stream_bwrit(ostream, &null, 1); + } + if (end_len > 8) { + xm_binutils_bin2coff_write_string(ostream, symbol_end, end_len); + tb_byte_t null = 0; + tb_stream_bwrit(ostream, &null, 1); + } + + return tb_true; +} + +/* ////////////////////////////////////////////////////////////////////////////////////// + * implementation + */ + +/* generate COFF object file from binary file + * + * local ok, errors = binutils.bin2coff(binaryfile, outputfile, symbol_prefix, arch, basename) + */ +tb_int_t xm_binutils_bin2coff(lua_State *lua) { + tb_assert_and_check_return_val(lua, 0); + + // get the binaryfile + tb_char_t const *binaryfile = luaL_checkstring(lua, 1); + tb_check_return_val(binaryfile, 0); + + // get the outputfile + tb_char_t const *outputfile = luaL_checkstring(lua, 2); + tb_check_return_val(outputfile, 0); + + // get symbol prefix (optional) + tb_char_t const *symbol_prefix = lua_isstring(lua, 3) ? lua_tostring(lua, 3) : tb_null; + + // get arch (optional) + tb_char_t const *arch = lua_isstring(lua, 4) ? lua_tostring(lua, 4) : tb_null; + + // get basename (optional) + tb_char_t const *basename = lua_isstring(lua, 5) ? lua_tostring(lua, 5) : tb_null; + + // get zeroend (optional, default: false) + tb_bool_t zeroend = lua_toboolean(lua, 6); + + // do dump + tb_bool_t ok = tb_false; + tb_stream_ref_t istream = tb_stream_init_from_file(binaryfile, TB_FILE_MODE_RO); + tb_stream_ref_t ostream = tb_stream_init_from_file(outputfile, + TB_FILE_MODE_RW | TB_FILE_MODE_CREAT | TB_FILE_MODE_TRUNC); + do { + if (!tb_stream_open(istream)) { + lua_pushboolean(lua, tb_false); + lua_pushfstring(lua, "bin2coff: open %s failed", binaryfile); + break; + } + + if (!tb_stream_open(ostream)) { + lua_pushboolean(lua, tb_false); + lua_pushfstring(lua, "bin2coff: open %s failed", outputfile); + break; + } + + if (!xm_binutils_bin2coff_dump(istream, ostream, symbol_prefix, arch, basename, zeroend)) { + lua_pushboolean(lua, tb_false); + lua_pushfstring(lua, "bin2coff: dump data failed"); + break; + } + + ok = tb_true; + lua_pushboolean(lua, ok); + + } while (0); + + if (istream) { + tb_stream_clos(istream); + } + istream = tb_null; + + if (ostream) { + tb_stream_clos(ostream); + } + ostream = tb_null; + + return ok ? 1 : 2; +} + diff --git a/core/src/xmake/binutils/bin2elf.c b/core/src/xmake/binutils/bin2elf.c new file mode 100644 index 000000000..bb2507a34 --- /dev/null +++ b/core/src/xmake/binutils/bin2elf.c @@ -0,0 +1,856 @@ +/*!A cross-platform build utility based on Lua + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright (C) 2015-present, Xmake Open Source Community. + * + * @author ruki + * @file bin2elf.c + * + */ + +/* ////////////////////////////////////////////////////////////////////////////////////// + * trace + */ +#define TB_TRACE_MODULE_NAME "bin2elf" +#define TB_TRACE_MODULE_DEBUG (0) + +/* ////////////////////////////////////////////////////////////////////////////////////// + * includes + */ +#include "prefix.h" + +/* ////////////////////////////////////////////////////////////////////////////////////// + * macros + */ +#define XM_ELF_MACHINE_X86_64 0x3e +#define XM_ELF_MACHINE_ARM64 0xb7 +#define XM_ELF_MACHINE_ARM 0x28 +#define XM_ELF_MACHINE_I386 0x03 + +#define XM_ELF_SHT_PROGBITS 0x1 +#define XM_ELF_SHT_SYMTAB 0x2 +#define XM_ELF_SHT_STRTAB 0x3 + +#define XM_ELF_SHF_ALLOC 0x2 +#define XM_ELF_SHF_WRITE 0x1 + +#define XM_ELF_STB_GLOBAL 0x1 +#define XM_ELF_STT_OBJECT 0x1 + +/* ////////////////////////////////////////////////////////////////////////////////////// + * types + */ +#include "tbox/prefix/packed.h" +typedef struct __xm_elf32_header_t { + tb_uint8_t e_ident[16]; + tb_uint16_t e_type; + tb_uint16_t e_machine; + tb_uint32_t e_version; + tb_uint32_t e_entry; + tb_uint32_t e_phoff; + tb_uint32_t e_shoff; + tb_uint32_t e_flags; + tb_uint16_t e_ehsize; + tb_uint16_t e_phentsize; + tb_uint16_t e_phnum; + tb_uint16_t e_shentsize; + tb_uint16_t e_shnum; + tb_uint16_t e_shstrndx; +} __tb_packed__ xm_elf32_header_t; + +typedef struct __xm_elf32_section_t { + tb_uint32_t sh_name; + tb_uint32_t sh_type; + tb_uint32_t sh_flags; + tb_uint32_t sh_addr; + tb_uint32_t sh_offset; + tb_uint32_t sh_size; + tb_uint32_t sh_link; + tb_uint32_t sh_info; + tb_uint32_t sh_addralign; + tb_uint32_t sh_entsize; +} __tb_packed__ xm_elf32_section_t; + +typedef struct __xm_elf32_symbol_t { + tb_uint32_t st_name; + tb_uint32_t st_value; + tb_uint32_t st_size; + tb_uint8_t st_info; + tb_uint8_t st_other; + tb_uint16_t st_shndx; +} __tb_packed__ xm_elf32_symbol_t; + +typedef struct __xm_elf64_header_t { + tb_uint8_t e_ident[16]; + tb_uint16_t e_type; + tb_uint16_t e_machine; + tb_uint32_t e_version; + tb_uint64_t e_entry; + tb_uint64_t e_phoff; + tb_uint64_t e_shoff; + tb_uint32_t e_flags; + tb_uint16_t e_ehsize; + tb_uint16_t e_phentsize; + tb_uint16_t e_phnum; + tb_uint16_t e_shentsize; + tb_uint16_t e_shnum; + tb_uint16_t e_shstrndx; +} __tb_packed__ xm_elf64_header_t; + +typedef struct __xm_elf64_section_t { + tb_uint32_t sh_name; + tb_uint32_t sh_type; + tb_uint64_t sh_flags; + tb_uint64_t sh_addr; + tb_uint64_t sh_offset; + tb_uint64_t sh_size; + tb_uint32_t sh_link; + tb_uint32_t sh_info; + tb_uint64_t sh_addralign; + tb_uint64_t sh_entsize; +} __tb_packed__ xm_elf64_section_t; + +typedef struct __xm_elf64_symbol_t { + tb_uint32_t st_name; + tb_uint8_t st_info; + tb_uint8_t st_other; + tb_uint16_t st_shndx; + tb_uint64_t st_value; + tb_uint64_t st_size; +} __tb_packed__ xm_elf64_symbol_t; + +#include "tbox/prefix/packed.h" + +/* ////////////////////////////////////////////////////////////////////////////////////// + * private implementation + */ +static tb_uint16_t xm_binutils_bin2elf_get_machine(tb_char_t const *arch) { + if (!arch) { + return XM_ELF_MACHINE_X86_64; + } + if (tb_strcmp(arch, "x86_64") == 0 || tb_strcmp(arch, "x64") == 0) { + return XM_ELF_MACHINE_X86_64; + } else if (tb_strcmp(arch, "arm64") == 0 || tb_strcmp(arch, "aarch64") == 0 || + tb_strcmp(arch, "arm64-v8a") == 0) { + return XM_ELF_MACHINE_ARM64; + } else if (tb_strcmp(arch, "arm") == 0 || tb_strcmp(arch, "armv7") == 0 || + tb_strcmp(arch, "armeabi-v7a") == 0) { + return XM_ELF_MACHINE_ARM; + } else if (tb_strcmp(arch, "i386") == 0 || tb_strcmp(arch, "x86") == 0) { + return XM_ELF_MACHINE_I386; + } + return XM_ELF_MACHINE_X86_64; +} + +static tb_bool_t xm_binutils_bin2elf_is_64bit(tb_char_t const *arch) { + if (!arch) { + return tb_true; + } + if (tb_strcmp(arch, "x86_64") == 0 || tb_strcmp(arch, "x64") == 0 || + tb_strcmp(arch, "arm64") == 0 || tb_strcmp(arch, "aarch64") == 0 || + tb_strcmp(arch, "arm64-v8a") == 0) { + return tb_true; + } + return tb_false; +} + +static tb_bool_t xm_binutils_bin2elf_dump_32(tb_stream_ref_t istream, + tb_stream_ref_t ostream, + tb_char_t const *symbol_prefix, + tb_char_t const *arch, + tb_char_t const *basename, + tb_bool_t zeroend) { + tb_assert_and_check_return_val(istream && ostream, tb_false); + + // get file size + tb_hong_t filesize = tb_stream_size(istream); + if (filesize < 0 || filesize > 0xffffffffU) { + return tb_false; + } + tb_uint32_t datasize = (tb_uint32_t)filesize; + // add null terminator if zeroend is true + if (zeroend) { + if (datasize >= 0xffffffffU) { + return tb_false; // would overflow + } + datasize++; + } + + // generate symbol names from filename + tb_char_t symbol_name[256] = {0}; + tb_char_t symbol_start[256] = {0}; + tb_char_t symbol_end[256] = {0}; + + // use basename or default to "data" + if (!basename || !basename[0]) { + basename = "data"; + } + + // build symbol name + if (symbol_prefix) { + tb_snprintf(symbol_name, sizeof(symbol_name), "%s%s", symbol_prefix, basename); + } else { + tb_snprintf(symbol_name, sizeof(symbol_name), "_binary_%s", basename); + } + + // replace non-alphanumeric with underscore + for (tb_size_t i = 0; symbol_name[i]; i++) { + if (!tb_isalpha(symbol_name[i]) && !tb_isdigit(symbol_name[i]) && symbol_name[i] != '_') { + symbol_name[i] = '_'; + } + } + + tb_snprintf(symbol_start, sizeof(symbol_start), "%s_start", symbol_name); + tb_snprintf(symbol_end, sizeof(symbol_end), "%s_end", symbol_name); + + // calculate offsets + tb_uint32_t header_size = sizeof(xm_elf32_header_t); + tb_uint32_t section_header_size = sizeof(xm_elf32_section_t); + tb_uint32_t section_count = 6; // NULL, .rodata, .symtab, .strtab, .shstrtab, .note.GNU-stack + tb_uint32_t section_headers_ofs = header_size; + tb_uint32_t rodata_ofs = section_headers_ofs + section_count * section_header_size; + tb_uint32_t rodata_size = datasize; + tb_uint32_t rodata_padding = (4 - (rodata_size & 3)) & 3; // align to 4 bytes for 32-bit + tb_uint32_t symtab_ofs = rodata_ofs + rodata_size + rodata_padding; + tb_uint32_t symtab_size = 3 * sizeof(xm_elf32_symbol_t); // NULL, start, end + tb_uint32_t symtab_padding = (4 - (symtab_size & 3)) & 3; // align to 4 bytes + tb_uint32_t strtab_ofs = symtab_ofs + symtab_size + symtab_padding; + + // calculate string table size + tb_size_t start_len = tb_strlen(symbol_start); + tb_size_t end_len = tb_strlen(symbol_end); + tb_uint32_t strtab_size = 1; // initial null byte + strtab_size += (tb_uint32_t)(start_len + 1); + strtab_size += (tb_uint32_t)(end_len + 1); + tb_uint32_t strtab_padding = (4 - (strtab_size & 3)) & 3; // align to 4 bytes + tb_uint32_t shstrtab_ofs = strtab_ofs + strtab_size + strtab_padding; + + // calculate section header string table size + tb_uint32_t shstrtab_size = 1; // initial null byte + shstrtab_size += 8; // ".rodata\0" (7 + 1) + shstrtab_size += 8; // ".symtab\0" (7 + 1) + shstrtab_size += 8; // ".strtab\0" (7 + 1) + shstrtab_size += 10; // ".shstrtab\0" (9 + 1) + shstrtab_size += 16; // ".note.GNU-stack\0" (15 + 1) + + // write ELF header + xm_elf32_header_t header; + tb_memset(&header, 0, sizeof(header)); + header.e_ident[0] = 0x7f; + header.e_ident[1] = 'E'; + header.e_ident[2] = 'L'; + header.e_ident[3] = 'F'; + header.e_ident[4] = 1; // ELFCLASS32 + header.e_ident[5] = 1; // ELFDATA2LSB + header.e_ident[6] = 1; // EV_CURRENT + header.e_ident[7] = 0; // ELFOSABI_SYSV + header.e_type = 1; // ET_REL + header.e_machine = xm_binutils_bin2elf_get_machine(arch); + header.e_version = 1; + header.e_shoff = section_headers_ofs; + header.e_ehsize = header_size; + header.e_shentsize = section_header_size; + header.e_shnum = section_count; + header.e_shstrndx = 4; // .shstrtab section index + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)&header, sizeof(header))) { + return tb_false; + } + + // write section headers + xm_elf32_section_t section_null; + tb_memset(§ion_null, 0, sizeof(section_null)); + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)§ion_null, sizeof(section_null))) { + return tb_false; + } + + // write .rodata section header + xm_elf32_section_t section_rodata; + tb_memset(§ion_rodata, 0, sizeof(section_rodata)); + section_rodata.sh_name = 1; // ".rodata" in shstrtab + section_rodata.sh_type = XM_ELF_SHT_PROGBITS; + section_rodata.sh_flags = XM_ELF_SHF_ALLOC; + section_rodata.sh_offset = rodata_ofs; + section_rodata.sh_size = rodata_size; + section_rodata.sh_addralign = 4; + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)§ion_rodata, sizeof(section_rodata))) { + return tb_false; + } + + // write .symtab section header + xm_elf32_section_t section_symtab; + tb_memset(§ion_symtab, 0, sizeof(section_symtab)); + section_symtab.sh_name = 9; // ".symtab" in shstrtab + section_symtab.sh_type = XM_ELF_SHT_SYMTAB; + section_symtab.sh_offset = symtab_ofs; + section_symtab.sh_size = symtab_size; + section_symtab.sh_link = 3; // .strtab section index + section_symtab.sh_info = 1; // first global symbol index + section_symtab.sh_addralign = 4; + section_symtab.sh_entsize = sizeof(xm_elf32_symbol_t); + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)§ion_symtab, sizeof(section_symtab))) { + return tb_false; + } + + // write .strtab section header + xm_elf32_section_t section_strtab; + tb_memset(§ion_strtab, 0, sizeof(section_strtab)); + section_strtab.sh_name = 17; // ".strtab" in shstrtab + section_strtab.sh_type = XM_ELF_SHT_STRTAB; + section_strtab.sh_offset = strtab_ofs; + section_strtab.sh_size = strtab_size; + section_strtab.sh_addralign = 1; + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)§ion_strtab, sizeof(section_strtab))) { + return tb_false; + } + + // write .shstrtab section header + xm_elf32_section_t section_shstrtab; + tb_memset(§ion_shstrtab, 0, sizeof(section_shstrtab)); + section_shstrtab.sh_name = 25; // ".shstrtab" in shstrtab + section_shstrtab.sh_type = XM_ELF_SHT_STRTAB; + section_shstrtab.sh_offset = shstrtab_ofs; + section_shstrtab.sh_size = shstrtab_size; + section_shstrtab.sh_addralign = 1; + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)§ion_shstrtab, sizeof(section_shstrtab))) { + return tb_false; + } + + // write .note.GNU-stack section header (empty section to mark stack as non-executable) + xm_elf32_section_t section_note_gnu_stack; + tb_memset(§ion_note_gnu_stack, 0, sizeof(section_note_gnu_stack)); + section_note_gnu_stack.sh_name = 35; // ".note.GNU-stack" in shstrtab (25 + 10) + section_note_gnu_stack.sh_type = XM_ELF_SHT_PROGBITS; + section_note_gnu_stack.sh_flags = 0; // no flags + section_note_gnu_stack.sh_offset = shstrtab_ofs + shstrtab_size; // after .shstrtab + section_note_gnu_stack.sh_size = 0; // empty section + section_note_gnu_stack.sh_addralign = 1; + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)§ion_note_gnu_stack, sizeof(section_note_gnu_stack))) { + return tb_false; + } + + // write .rodata section data + if (!xm_binutils_stream_copy(istream, ostream, filesize)) { + return tb_false; + } + // append null terminator if zeroend is true + if (zeroend) { + tb_byte_t zero = 0; + if (!tb_stream_bwrit(ostream, &zero, 1)) { + return tb_false; + } + } + + // align .rodata to 4 bytes + if (rodata_padding > 0) { + tb_byte_t zero = 0; + while (rodata_padding-- > 0) { + if (!tb_stream_bwrit(ostream, &zero, 1)) { + return tb_false; + } + } + } + + // write symbol table + // symbol 0: NULL symbol + xm_elf32_symbol_t sym_null; + tb_memset(&sym_null, 0, sizeof(sym_null)); + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)&sym_null, sizeof(sym_null))) { + return tb_false; + } + + // symbol 1: _binary_xxx_start + xm_elf32_symbol_t sym_start; + tb_memset(&sym_start, 0, sizeof(sym_start)); + sym_start.st_name = 1; // offset in .strtab (after initial null) + sym_start.st_info = (XM_ELF_STB_GLOBAL << 4) | XM_ELF_STT_OBJECT; + sym_start.st_shndx = 1; // .rodata section index + sym_start.st_value = 0; + sym_start.st_size = 0; + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)&sym_start, sizeof(sym_start))) { + return tb_false; + } + + // symbol 2: _binary_xxx_end + xm_elf32_symbol_t sym_end; + tb_memset(&sym_end, 0, sizeof(sym_end)); + sym_end.st_name = 1 + (tb_uint32_t)(start_len + 1); // offset in .strtab + sym_end.st_info = (XM_ELF_STB_GLOBAL << 4) | XM_ELF_STT_OBJECT; + sym_end.st_shndx = 1; // .rodata section index + sym_end.st_value = rodata_size; + sym_end.st_size = 0; + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)&sym_end, sizeof(sym_end))) { + return tb_false; + } + + // align .symtab to 4 bytes + if (symtab_padding > 0) { + tb_byte_t zero = 0; + while (symtab_padding-- > 0) { + if (!tb_stream_bwrit(ostream, &zero, 1)) { + return tb_false; + } + } + } + + // write string table + tb_byte_t null = 0; + if (!tb_stream_bwrit(ostream, &null, 1)) { + return tb_false; + } + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)symbol_start, start_len)) { + return tb_false; + } + if (!tb_stream_bwrit(ostream, &null, 1)) { + return tb_false; + } + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)symbol_end, end_len)) { + return tb_false; + } + if (!tb_stream_bwrit(ostream, &null, 1)) { + return tb_false; + } + + // align .strtab to 4 bytes + if (strtab_padding > 0) { + tb_byte_t zero = 0; + while (strtab_padding-- > 0) { + if (!tb_stream_bwrit(ostream, &zero, 1)) { + return tb_false; + } + } + } + + // write section header string table + if (!tb_stream_bwrit(ostream, &null, 1)) { + return tb_false; + } + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)".rodata", 7)) { + return tb_false; + } + if (!tb_stream_bwrit(ostream, &null, 1)) { + return tb_false; + } + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)".symtab", 7)) { + return tb_false; + } + if (!tb_stream_bwrit(ostream, &null, 1)) { + return tb_false; + } + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)".strtab", 7)) { + return tb_false; + } + if (!tb_stream_bwrit(ostream, &null, 1)) { + return tb_false; + } + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)".shstrtab", 9)) { + return tb_false; + } + if (!tb_stream_bwrit(ostream, &null, 1)) { + return tb_false; + } + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)".note.GNU-stack", 15)) { + return tb_false; + } + if (!tb_stream_bwrit(ostream, &null, 1)) { + return tb_false; + } + + return tb_true; +} + +static tb_bool_t xm_binutils_bin2elf_dump_64(tb_stream_ref_t istream, + tb_stream_ref_t ostream, + tb_char_t const *symbol_prefix, + tb_char_t const *arch, + tb_char_t const *basename, + tb_bool_t zeroend) { + tb_assert_and_check_return_val(istream && ostream, tb_false); + + // get file size + tb_hong_t filesize = tb_stream_size(istream); + if (filesize < 0 || filesize > 0xffffffffU) { + return tb_false; + } + tb_uint32_t datasize = (tb_uint32_t)filesize; + // add null terminator if zeroend is true + if (zeroend) { + if (datasize >= 0xffffffffU) { + return tb_false; // would overflow + } + datasize++; + } + + // generate symbol names from filename + tb_char_t symbol_name[256] = {0}; + tb_char_t symbol_start[256] = {0}; + tb_char_t symbol_end[256] = {0}; + + // use basename or default to "data" + if (!basename || !basename[0]) { + basename = "data"; + } + + // build symbol name + if (symbol_prefix) { + tb_snprintf(symbol_name, sizeof(symbol_name), "%s%s", symbol_prefix, basename); + } else { + tb_snprintf(symbol_name, sizeof(symbol_name), "_binary_%s", basename); + } + + // replace non-alphanumeric with underscore + for (tb_size_t i = 0; symbol_name[i]; i++) { + if (!tb_isalpha(symbol_name[i]) && !tb_isdigit(symbol_name[i]) && symbol_name[i] != '_') { + symbol_name[i] = '_'; + } + } + + tb_snprintf(symbol_start, sizeof(symbol_start), "%s_start", symbol_name); + tb_snprintf(symbol_end, sizeof(symbol_end), "%s_end", symbol_name); + + // calculate offsets + tb_uint32_t header_size = sizeof(xm_elf64_header_t); + tb_uint32_t section_header_size = sizeof(xm_elf64_section_t); + tb_uint32_t section_count = 6; // NULL, .rodata, .symtab, .strtab, .shstrtab, .note.GNU-stack + tb_uint32_t section_headers_ofs = header_size; + tb_uint32_t rodata_ofs = section_headers_ofs + section_count * section_header_size; + tb_uint32_t rodata_size = datasize; + tb_uint32_t rodata_padding = (8 - (rodata_size & 7)) & 7; + tb_uint32_t symtab_ofs = rodata_ofs + rodata_size + rodata_padding; + tb_uint32_t symtab_size = 3 * sizeof(xm_elf64_symbol_t); // NULL, start, end + tb_uint32_t symtab_padding = (8 - (symtab_size & 7)) & 7; + tb_uint32_t strtab_ofs = symtab_ofs + symtab_size + symtab_padding; + + // calculate string table size + tb_size_t start_len = tb_strlen(symbol_start); + tb_size_t end_len = tb_strlen(symbol_end); + tb_uint32_t strtab_size = 1; // initial null byte + strtab_size += (tb_uint32_t)(start_len + 1); + strtab_size += (tb_uint32_t)(end_len + 1); + tb_uint32_t strtab_padding = (8 - (strtab_size & 7)) & 7; + + // calculate section header string table size + tb_uint32_t shstrtab_size = 1; // initial null byte + shstrtab_size += 8; // ".rodata\0" (7 + 1) + shstrtab_size += 8; // ".symtab\0" (7 + 1) + shstrtab_size += 8; // ".strtab\0" (7 + 1) + shstrtab_size += 10; // ".shstrtab\0" (9 + 1) + shstrtab_size += 16; // ".note.GNU-stack\0" (15 + 1) + tb_uint32_t shstrtab_ofs = strtab_ofs + strtab_size + strtab_padding; + + // write ELF header + xm_elf64_header_t header; + tb_memset(&header, 0, sizeof(header)); + header.e_ident[0] = 0x7f; + header.e_ident[1] = 'E'; + header.e_ident[2] = 'L'; + header.e_ident[3] = 'F'; + header.e_ident[4] = 2; // ELFCLASS64 + header.e_ident[5] = 1; // ELFDATA2LSB + header.e_ident[6] = 1; // EV_CURRENT + header.e_ident[7] = 0; // ELFOSABI_SYSV + header.e_type = 1; // ET_REL + header.e_machine = xm_binutils_bin2elf_get_machine(arch); + header.e_version = 1; + header.e_shoff = section_headers_ofs; + header.e_ehsize = header_size; + header.e_shentsize = section_header_size; + header.e_shnum = section_count; + header.e_shstrndx = 4; // .shstrtab section index + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)&header, sizeof(header))) { + return tb_false; + } + + // write section headers + xm_elf64_section_t section_null; + tb_memset(§ion_null, 0, sizeof(section_null)); + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)§ion_null, sizeof(section_null))) { + return tb_false; + } + + // write .rodata section header + xm_elf64_section_t section_rodata; + tb_memset(§ion_rodata, 0, sizeof(section_rodata)); + section_rodata.sh_name = 1; // ".rodata" in shstrtab + section_rodata.sh_type = XM_ELF_SHT_PROGBITS; + section_rodata.sh_flags = XM_ELF_SHF_ALLOC; + section_rodata.sh_offset = rodata_ofs; + section_rodata.sh_size = rodata_size; + section_rodata.sh_addralign = 8; + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)§ion_rodata, sizeof(section_rodata))) { + return tb_false; + } + + // write .symtab section header + xm_elf64_section_t section_symtab; + tb_memset(§ion_symtab, 0, sizeof(section_symtab)); + section_symtab.sh_name = 9; // ".symtab" in shstrtab + section_symtab.sh_type = XM_ELF_SHT_SYMTAB; + section_symtab.sh_offset = symtab_ofs; + section_symtab.sh_size = symtab_size; + section_symtab.sh_link = 3; // .strtab section index + section_symtab.sh_info = 1; // first global symbol index + section_symtab.sh_addralign = 8; + section_symtab.sh_entsize = sizeof(xm_elf64_symbol_t); + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)§ion_symtab, sizeof(section_symtab))) { + return tb_false; + } + + // write .strtab section header + xm_elf64_section_t section_strtab; + tb_memset(§ion_strtab, 0, sizeof(section_strtab)); + section_strtab.sh_name = 17; // ".strtab" in shstrtab + section_strtab.sh_type = XM_ELF_SHT_STRTAB; + section_strtab.sh_offset = strtab_ofs; + section_strtab.sh_size = strtab_size; + section_strtab.sh_addralign = 1; + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)§ion_strtab, sizeof(section_strtab))) { + return tb_false; + } + + // write .shstrtab section header + xm_elf64_section_t section_shstrtab; + tb_memset(§ion_shstrtab, 0, sizeof(section_shstrtab)); + section_shstrtab.sh_name = 25; // ".shstrtab" in shstrtab + section_shstrtab.sh_type = XM_ELF_SHT_STRTAB; + section_shstrtab.sh_offset = shstrtab_ofs; // points to initial null byte + section_shstrtab.sh_size = shstrtab_size; // size includes initial null and all strings + section_shstrtab.sh_addralign = 1; + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)§ion_shstrtab, sizeof(section_shstrtab))) { + return tb_false; + } + + // write .note.GNU-stack section header (empty section to mark stack as non-executable) + xm_elf64_section_t section_note_gnu_stack; + tb_memset(§ion_note_gnu_stack, 0, sizeof(section_note_gnu_stack)); + section_note_gnu_stack.sh_name = 35; // ".note.GNU-stack" in shstrtab (25 + 10) + section_note_gnu_stack.sh_type = XM_ELF_SHT_PROGBITS; + section_note_gnu_stack.sh_flags = 0; // no flags + section_note_gnu_stack.sh_offset = shstrtab_ofs + shstrtab_size; // after .shstrtab + section_note_gnu_stack.sh_size = 0; // empty section + section_note_gnu_stack.sh_addralign = 1; + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)§ion_note_gnu_stack, sizeof(section_note_gnu_stack))) { + return tb_false; + } + + // write .rodata section data + if (!xm_binutils_stream_copy(istream, ostream, filesize)) { + return tb_false; + } + // append null terminator if zeroend is true + if (zeroend) { + tb_byte_t zero = 0; + if (!tb_stream_bwrit(ostream, &zero, 1)) { + return tb_false; + } + } + + // align .rodata to 8 bytes + if (rodata_padding > 0) { + tb_byte_t zero = 0; + while (rodata_padding-- > 0) { + if (!tb_stream_bwrit(ostream, &zero, 1)) { + return tb_false; + } + } + } + + // write symbol table + // symbol 0: NULL symbol + xm_elf64_symbol_t sym_null; + tb_memset(&sym_null, 0, sizeof(sym_null)); + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)&sym_null, sizeof(sym_null))) { + return tb_false; + } + + // symbol 1: _binary_xxx_start + xm_elf64_symbol_t sym_start; + tb_memset(&sym_start, 0, sizeof(sym_start)); + sym_start.st_name = 1; // offset in .strtab (after initial null) + sym_start.st_info = (XM_ELF_STB_GLOBAL << 4) | XM_ELF_STT_OBJECT; + sym_start.st_shndx = 1; // .rodata section index + sym_start.st_value = 0; + sym_start.st_size = 0; + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)&sym_start, sizeof(sym_start))) { + return tb_false; + } + + // symbol 2: _binary_xxx_end + xm_elf64_symbol_t sym_end; + tb_memset(&sym_end, 0, sizeof(sym_end)); + sym_end.st_name = 1 + (tb_uint32_t)(start_len + 1); // offset in .strtab + sym_end.st_info = (XM_ELF_STB_GLOBAL << 4) | XM_ELF_STT_OBJECT; + sym_end.st_shndx = 1; // .rodata section index + sym_end.st_value = rodata_size; + sym_end.st_size = 0; + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)&sym_end, sizeof(sym_end))) { + return tb_false; + } + + // align .symtab to 8 bytes + if (symtab_padding > 0) { + tb_byte_t zero = 0; + while (symtab_padding-- > 0) { + if (!tb_stream_bwrit(ostream, &zero, 1)) { + return tb_false; + } + } + } + + // write string table + tb_byte_t null = 0; + if (!tb_stream_bwrit(ostream, &null, 1)) { + return tb_false; + } + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)symbol_start, start_len)) { + return tb_false; + } + if (!tb_stream_bwrit(ostream, &null, 1)) { + return tb_false; + } + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)symbol_end, end_len)) { + return tb_false; + } + if (!tb_stream_bwrit(ostream, &null, 1)) { + return tb_false; + } + + // align .strtab to 8 bytes + if (strtab_padding > 0) { + tb_byte_t zero = 0; + while (strtab_padding-- > 0) { + if (!tb_stream_bwrit(ostream, &zero, 1)) { + return tb_false; + } + } + } + + // write section header string table + if (!tb_stream_bwrit(ostream, &null, 1)) { + return tb_false; + } + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)".rodata", 7)) { + return tb_false; + } + if (!tb_stream_bwrit(ostream, &null, 1)) { + return tb_false; + } + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)".symtab", 7)) { + return tb_false; + } + if (!tb_stream_bwrit(ostream, &null, 1)) { + return tb_false; + } + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)".strtab", 7)) { + return tb_false; + } + if (!tb_stream_bwrit(ostream, &null, 1)) { + return tb_false; + } + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)".shstrtab", 9)) { + return tb_false; + } + if (!tb_stream_bwrit(ostream, &null, 1)) { + return tb_false; + } + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)".note.GNU-stack", 15)) { + return tb_false; + } + if (!tb_stream_bwrit(ostream, &null, 1)) { + return tb_false; + } + + return tb_true; +} + +/* ////////////////////////////////////////////////////////////////////////////////////// + * implementation + */ + +/* generate ELF object file from binary file + * + * local ok, errors = binutils.bin2elf(binaryfile, outputfile, symbol_prefix, arch, basename, zeroend) + */ +tb_int_t xm_binutils_bin2elf(lua_State *lua) { + tb_assert_and_check_return_val(lua, 0); + + // get the binaryfile + tb_char_t const *binaryfile = luaL_checkstring(lua, 1); + tb_check_return_val(binaryfile, 0); + + // get the outputfile + tb_char_t const *outputfile = luaL_checkstring(lua, 2); + tb_check_return_val(outputfile, 0); + + // get symbol prefix (optional) + tb_char_t const *symbol_prefix = lua_isstring(lua, 3) ? lua_tostring(lua, 3) : tb_null; + + // get arch (optional) + tb_char_t const *arch = lua_isstring(lua, 4) ? lua_tostring(lua, 4) : tb_null; + + // get basename (optional) + tb_char_t const *basename = lua_isstring(lua, 5) ? lua_tostring(lua, 5) : tb_null; + + // get zeroend (optional, default: false) + tb_bool_t zeroend = lua_toboolean(lua, 6); + + // do dump + tb_bool_t ok = tb_false; + tb_stream_ref_t istream = tb_stream_init_from_file(binaryfile, TB_FILE_MODE_RO); + tb_stream_ref_t ostream = tb_stream_init_from_file(outputfile, + TB_FILE_MODE_RW | TB_FILE_MODE_CREAT | TB_FILE_MODE_TRUNC); + do { + if (!tb_stream_open(istream)) { + lua_pushboolean(lua, tb_false); + lua_pushfstring(lua, "bin2elf: open %s failed", binaryfile); + break; + } + + if (!tb_stream_open(ostream)) { + lua_pushboolean(lua, tb_false); + lua_pushfstring(lua, "bin2elf: open %s failed", outputfile); + break; + } + + // choose 32-bit or 64-bit ELF based on architecture + tb_bool_t is_64bit = xm_binutils_bin2elf_is_64bit(arch); + if (is_64bit) { + if (!xm_binutils_bin2elf_dump_64(istream, ostream, symbol_prefix, arch, basename, zeroend)) { + lua_pushboolean(lua, tb_false); + lua_pushfstring(lua, "bin2elf: dump data failed"); + break; + } + } else { + if (!xm_binutils_bin2elf_dump_32(istream, ostream, symbol_prefix, arch, basename, zeroend)) { + lua_pushboolean(lua, tb_false); + lua_pushfstring(lua, "bin2elf: dump data failed"); + break; + } + } + + ok = tb_true; + lua_pushboolean(lua, ok); + + } while (0); + + if (istream) + tb_stream_clos(istream); + istream = tb_null; + + if (ostream) + tb_stream_clos(ostream); + ostream = tb_null; + + return ok ? 1 : 2; +} + diff --git a/core/src/xmake/binutils/bin2macho.c b/core/src/xmake/binutils/bin2macho.c new file mode 100644 index 000000000..5add65d6c --- /dev/null +++ b/core/src/xmake/binutils/bin2macho.c @@ -0,0 +1,887 @@ +/*!A cross-platform build utility based on Lua + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright (C) 2015-present, Xmake Open Source Community. + * + * @author ruki + * @file bin2macho.c + * + */ + +/* ////////////////////////////////////////////////////////////////////////////////////// + * trace + */ +#define TB_TRACE_MODULE_NAME "bin2macho" +#define TB_TRACE_MODULE_DEBUG (0) + +/* ////////////////////////////////////////////////////////////////////////////////////// + * includes + */ +#include "prefix.h" + +/* ////////////////////////////////////////////////////////////////////////////////////// + * macros + */ +#define XM_MACHO_MAGIC_32 0xfeedface +#define XM_MACHO_MAGIC_64 0xfeedfacf +#define XM_MACHO_MAGIC_FAT 0xcafebabe + +#define XM_MACHO_CPU_TYPE_X86 7 +#define XM_MACHO_CPU_TYPE_X86_64 0x01000007 +#define XM_MACHO_CPU_TYPE_ARM 12 +#define XM_MACHO_CPU_TYPE_ARM64 0x0100000c + +#define XM_MACHO_CPU_SUBTYPE_X86 3 +#define XM_MACHO_CPU_SUBTYPE_X86_64 3 +#define XM_MACHO_CPU_SUBTYPE_ARM 9 +#define XM_MACHO_CPU_SUBTYPE_ARM64 0 + +#define XM_MACHO_FILE_TYPE_OBJECT 1 + +#define XM_MACHO_LC_SEGMENT 0x1 +#define XM_MACHO_LC_SEGMENT_64 0x19 +#define XM_MACHO_LC_SYMTAB 0x2 +#define XM_MACHO_LC_BUILD_VERSION 0x32 + +#define XM_MACHO_PLATFORM_MACOS 1 +#define XM_MACHO_PLATFORM_IOS 2 +#define XM_MACHO_PLATFORM_TVOS 3 +#define XM_MACHO_PLATFORM_WATCHOS 4 + +#define XM_MACHO_SECT_TYPE_REGULAR 0x0 +#define XM_MACHO_SECT_ATTR_SOME_INITS 0x400 +#define XM_MACHO_SECT_ATTR_PURE_INSTRUCTIONS 0x80000000 + +#define XM_MACHO_N_TYPE_MASK 0x0e +#define XM_MACHO_N_TYPE_SECT 0x0e +#define XM_MACHO_N_EXT 0x01 + +#define XM_MACHO_VM_PROT_READ 1 +#define XM_MACHO_VM_PROT_WRITE 2 +#define XM_MACHO_VM_PROT_EXECUTE 4 + +/* ////////////////////////////////////////////////////////////////////////////////////// + * types + */ +#include "tbox/prefix/packed.h" +typedef struct __xm_macho_header_t { + tb_uint32_t magic; + tb_uint32_t cputype; + tb_uint32_t cpusubtype; + tb_uint32_t filetype; + tb_uint32_t ncmds; + tb_uint32_t sizeofcmds; + tb_uint32_t flags; +} __tb_packed__ xm_macho_header_t; + +typedef struct __xm_macho_header_64_t { + tb_uint32_t magic; + tb_uint32_t cputype; + tb_uint32_t cpusubtype; + tb_uint32_t filetype; + tb_uint32_t ncmds; + tb_uint32_t sizeofcmds; + tb_uint32_t flags; + tb_uint32_t reserved; +} __tb_packed__ xm_macho_header_64_t; + +typedef struct __xm_macho_segment_command_t { + tb_uint32_t cmd; + tb_uint32_t cmdsize; + tb_char_t segname[16]; + tb_uint32_t vmaddr; + tb_uint32_t vmsize; + tb_uint32_t fileoff; + tb_uint32_t filesize; + tb_uint32_t maxprot; + tb_uint32_t initprot; + tb_uint32_t nsects; + tb_uint32_t flags; +} __tb_packed__ xm_macho_segment_command_t; + +typedef struct __xm_macho_segment_command_64_t { + tb_uint32_t cmd; + tb_uint32_t cmdsize; + tb_char_t segname[16]; + tb_uint64_t vmaddr; + tb_uint64_t vmsize; + tb_uint64_t fileoff; + tb_uint64_t filesize; + tb_uint32_t maxprot; + tb_uint32_t initprot; + tb_uint32_t nsects; + tb_uint32_t flags; +} __tb_packed__ xm_macho_segment_command_64_t; + +typedef struct __xm_macho_section_t { + tb_char_t sectname[16]; + tb_char_t segname[16]; + tb_uint32_t addr; + tb_uint32_t size; + tb_uint32_t offset; + tb_uint32_t align; + tb_uint32_t reloff; + tb_uint32_t nreloc; + tb_uint32_t flags; + tb_uint32_t reserved1; + tb_uint32_t reserved2; +} __tb_packed__ xm_macho_section_t; + +typedef struct __xm_macho_section_64_t { + tb_char_t sectname[16]; + tb_char_t segname[16]; + tb_uint64_t addr; + tb_uint64_t size; + tb_uint32_t offset; + tb_uint32_t align; + tb_uint32_t reloff; + tb_uint32_t nreloc; + tb_uint32_t flags; + tb_uint32_t reserved1; + tb_uint32_t reserved2; + tb_uint32_t reserved3; +} __tb_packed__ xm_macho_section_64_t; + +typedef struct __xm_macho_symtab_command_t { + tb_uint32_t cmd; + tb_uint32_t cmdsize; + tb_uint32_t symoff; + tb_uint32_t nsyms; + tb_uint32_t stroff; + tb_uint32_t strsize; +} __tb_packed__ xm_macho_symtab_command_t; + +typedef struct __xm_macho_build_version_command_t { + tb_uint32_t cmd; + tb_uint32_t cmdsize; + tb_uint32_t platform; + tb_uint32_t minos; + tb_uint32_t sdk; + tb_uint32_t ntools; +} __tb_packed__ xm_macho_build_version_command_t; + +typedef struct __xm_macho_nlist_t { + tb_uint32_t strx; + tb_uint8_t type; + tb_uint8_t sect; + tb_int16_t desc; + tb_uint32_t value; +} __tb_packed__ xm_macho_nlist_t; + +typedef struct __xm_macho_nlist_64_t { + tb_uint32_t strx; + tb_uint8_t type; + tb_uint8_t sect; + tb_uint16_t desc; + tb_uint64_t value; +} __tb_packed__ xm_macho_nlist_64_t; +#include "tbox/prefix/packed.h" + +/* ////////////////////////////////////////////////////////////////////////////////////// + * private implementation + */ +static tb_uint32_t xm_binutils_bin2macho_get_cputype(tb_char_t const *arch) { + if (!arch) { + return XM_MACHO_CPU_TYPE_X86_64; + } + if (tb_strcmp(arch, "x86_64") == 0 || tb_strcmp(arch, "x64") == 0) { + return XM_MACHO_CPU_TYPE_X86_64; + } else if (tb_strcmp(arch, "arm64") == 0 || tb_strcmp(arch, "aarch64") == 0) { + return XM_MACHO_CPU_TYPE_ARM64; + } else if (tb_strcmp(arch, "arm") == 0) { + return XM_MACHO_CPU_TYPE_ARM; + } else if (tb_strcmp(arch, "x86") == 0 || tb_strcmp(arch, "i386") == 0) { + return XM_MACHO_CPU_TYPE_X86; + } + return XM_MACHO_CPU_TYPE_X86_64; +} + +static tb_uint32_t xm_binutils_bin2macho_get_cpusubtype(tb_char_t const *arch) { + if (!arch) { + return XM_MACHO_CPU_SUBTYPE_X86_64; + } + if (tb_strcmp(arch, "x86_64") == 0 || tb_strcmp(arch, "x64") == 0) { + return XM_MACHO_CPU_SUBTYPE_X86_64; + } else if (tb_strcmp(arch, "arm64") == 0 || tb_strcmp(arch, "aarch64") == 0) { + return XM_MACHO_CPU_SUBTYPE_ARM64; + } else if (tb_strcmp(arch, "arm") == 0) { + return XM_MACHO_CPU_SUBTYPE_ARM; + } else if (tb_strcmp(arch, "x86") == 0 || tb_strcmp(arch, "i386") == 0) { + return XM_MACHO_CPU_SUBTYPE_X86; + } + return XM_MACHO_CPU_SUBTYPE_X86_64; +} + +static tb_bool_t xm_binutils_bin2macho_is_64bit(tb_char_t const *arch) { + if (!arch) { + return tb_true; + } + if (tb_strcmp(arch, "x86_64") == 0 || tb_strcmp(arch, "x64") == 0) { + return tb_true; + } else if (tb_strcmp(arch, "arm64") == 0 || tb_strcmp(arch, "aarch64") == 0) { + return tb_true; + } else if (tb_strcmp(arch, "arm") == 0) { + return tb_false; + } else if (tb_strcmp(arch, "x86") == 0 || tb_strcmp(arch, "i386") == 0) { + return tb_false; + } + return tb_true; +} + +static tb_uint32_t xm_binutils_bin2macho_align(tb_uint32_t value, tb_uint32_t align) { + return ((value + align - 1) & ~(align - 1)); +} + +static tb_uint32_t xm_binutils_bin2macho_get_platform(tb_char_t const *platform) { + if (!platform) { + return XM_MACHO_PLATFORM_MACOS; + } + if (tb_strcmp(platform, "macosx") == 0 || tb_strcmp(platform, "macos") == 0) { + return XM_MACHO_PLATFORM_MACOS; + } else if (tb_strcmp(platform, "iphoneos") == 0 || tb_strcmp(platform, "ios") == 0) { + return XM_MACHO_PLATFORM_IOS; + } else if (tb_strcmp(platform, "appletvos") == 0 || tb_strcmp(platform, "tvos") == 0) { + return XM_MACHO_PLATFORM_TVOS; + } else if (tb_strcmp(platform, "watchos") == 0) { + return XM_MACHO_PLATFORM_WATCHOS; + } + return XM_MACHO_PLATFORM_MACOS; +} + +// parse version string (e.g., "10.0" or "18.2") to Mach-O format (0x000a0000) +// format: (major << 16) | (minor << 8) | patch +static tb_uint32_t xm_binutils_bin2macho_parse_version(tb_char_t const *version_str) { + if (!version_str || !version_str[0]) { + return 0x000a0000; // default: 10.0.0 + } + tb_uint32_t major = 0; + tb_uint32_t minor = 0; + tb_uint32_t patch = 0; + tb_char_t const *p = version_str; + // parse major + while (*p && tb_isdigit(*p)) { + major = major * 10 + (*p - '0'); + p++; + } + if (*p == '.') { + p++; + // parse minor + while (*p && tb_isdigit(*p)) { + minor = minor * 10 + (*p - '0'); + p++; + } + if (*p == '.') { + p++; + // parse patch + while (*p && tb_isdigit(*p)) { + patch = patch * 10 + (*p - '0'); + p++; + } + } + } + return (major << 16) | (minor << 8) | patch; +} + +static tb_bool_t xm_binutils_bin2macho_dump_64(tb_stream_ref_t istream, + tb_stream_ref_t ostream, + tb_char_t const *symbol_prefix, + tb_char_t const *plat, + tb_char_t const *arch, + tb_char_t const *basename, + tb_uint32_t minos, + tb_uint32_t sdk, + tb_bool_t zeroend) { + tb_assert_and_check_return_val(istream && ostream, tb_false); + + // get file size + tb_hong_t filesize = tb_stream_size(istream); + if (filesize < 0 || filesize > 0xffffffffU) { + return tb_false; + } + tb_uint32_t datasize = (tb_uint32_t)filesize; + // add null terminator if zeroend is true + if (zeroend) { + if (datasize >= 0xffffffffU) { + return tb_false; // would overflow + } + datasize++; + } + + // generate symbol names from filename + tb_char_t symbol_name[256] = {0}; + tb_char_t symbol_start[256] = {0}; + tb_char_t symbol_end[256] = {0}; + + // use basename or default to "data" + if (!basename || !basename[0]) { + basename = "data"; + } + + // build symbol name + // On macOS, C compiler adds an underscore prefix, so we generate symbols with two underscores + // (C code declares _binary_xxx, compiler generates __binary_xxx in object file, so we define __binary_xxx) + if (symbol_prefix) { + tb_snprintf(symbol_name, sizeof(symbol_name), "_%s%s", symbol_prefix, basename); + } else { + tb_snprintf(symbol_name, sizeof(symbol_name), "__binary_%s", basename); + } + + // replace non-alphanumeric with underscore + for (tb_size_t i = 0; symbol_name[i]; i++) { + if (!tb_isalpha(symbol_name[i]) && !tb_isdigit(symbol_name[i]) && symbol_name[i] != '_') { + symbol_name[i] = '_'; + } + } + + tb_snprintf(symbol_start, sizeof(symbol_start), "%s_start", symbol_name); + tb_snprintf(symbol_end, sizeof(symbol_end), "%s_end", symbol_name); + + // calculate offsets + tb_uint32_t header_size = sizeof(xm_macho_header_64_t); + tb_uint32_t segment_cmd_size = sizeof(xm_macho_segment_command_64_t); + tb_uint32_t section_size = sizeof(xm_macho_section_64_t); + tb_uint32_t symtab_cmd_size = sizeof(xm_macho_symtab_command_t); + tb_uint32_t build_version_cmd_size = sizeof(xm_macho_build_version_command_t); + tb_uint32_t segment_cmd_total_size = segment_cmd_size + section_size; + tb_uint32_t data_offset = xm_binutils_bin2macho_align(header_size + segment_cmd_total_size + symtab_cmd_size + build_version_cmd_size, 8); + tb_uint32_t data_size = datasize; + tb_uint32_t data_end_offset = data_offset + data_size; + tb_uint32_t symtab_offset = xm_binutils_bin2macho_align(data_end_offset, 8); + tb_uint32_t nlist_size = sizeof(xm_macho_nlist_64_t); + tb_uint32_t nlist_count = 2; // start, end + tb_uint32_t strtab_offset = symtab_offset + nlist_size * nlist_count; + tb_uint32_t strtab_size = 4; // initial 4-byte size field + tb_size_t start_len = tb_strlen(symbol_start); + tb_size_t end_len = tb_strlen(symbol_end); + strtab_size += (tb_uint32_t)(start_len + 1); + strtab_size += (tb_uint32_t)(end_len + 1); + strtab_size = xm_binutils_bin2macho_align(strtab_size, 8); + + // write Mach-O header + xm_macho_header_64_t header; + tb_memset(&header, 0, sizeof(header)); + header.magic = XM_MACHO_MAGIC_64; + header.cputype = xm_binutils_bin2macho_get_cputype(arch); + header.cpusubtype = xm_binutils_bin2macho_get_cpusubtype(arch); + header.filetype = XM_MACHO_FILE_TYPE_OBJECT; + header.ncmds = 3; // segment + symtab + build_version + header.sizeofcmds = segment_cmd_total_size + symtab_cmd_size + build_version_cmd_size; + header.flags = 0; + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)&header, sizeof(header))) { + return tb_false; + } + + // write segment command + xm_macho_segment_command_64_t segment; + tb_memset(&segment, 0, sizeof(segment)); + segment.cmd = XM_MACHO_LC_SEGMENT_64; + segment.cmdsize = segment_cmd_total_size; + tb_strncpy(segment.segname, "__TEXT", 16); + segment.vmaddr = 0; + segment.vmsize = data_size; + segment.fileoff = data_offset; + segment.filesize = data_size; + segment.maxprot = XM_MACHO_VM_PROT_READ; // VM_PROT_READ (read-only) + segment.initprot = XM_MACHO_VM_PROT_READ; // VM_PROT_READ (read-only) + segment.nsects = 1; + segment.flags = 0; + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)&segment, sizeof(segment))) { + return tb_false; + } + + // write section + xm_macho_section_64_t section; + tb_memset(§ion, 0, sizeof(section)); + tb_strncpy(section.sectname, "__const", 16); + tb_strncpy(section.segname, "__TEXT", 16); + section.addr = 0; + section.size = data_size; + section.offset = data_offset; + section.align = 3; // 2^3 = 8 bytes + section.reloff = 0; + section.nreloc = 0; + section.flags = XM_MACHO_SECT_TYPE_REGULAR | XM_MACHO_SECT_ATTR_SOME_INITS; + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)§ion, sizeof(section))) { + return tb_false; + } + + // write symtab command + xm_macho_symtab_command_t symtab; + tb_memset(&symtab, 0, sizeof(symtab)); + symtab.cmd = XM_MACHO_LC_SYMTAB; + symtab.cmdsize = symtab_cmd_size; + symtab.symoff = symtab_offset; + symtab.nsyms = nlist_count; + symtab.stroff = strtab_offset; + symtab.strsize = strtab_size; + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)&symtab, sizeof(symtab))) { + return tb_false; + } + + // write build version command + xm_macho_build_version_command_t build_version; + tb_memset(&build_version, 0, sizeof(build_version)); + build_version.cmd = XM_MACHO_LC_BUILD_VERSION; + build_version.cmdsize = build_version_cmd_size; + build_version.platform = xm_binutils_bin2macho_get_platform(plat); + build_version.minos = minos; + build_version.sdk = sdk; + build_version.ntools = 0; + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)&build_version, sizeof(build_version))) { + return tb_false; + } + + // align to 8 bytes + tb_uint32_t padding = data_offset - (header_size + segment_cmd_total_size + symtab_cmd_size + build_version_cmd_size); + if (padding > 0) { + tb_byte_t zero = 0; + while (padding-- > 0) { + if (!tb_stream_bwrit(ostream, &zero, 1)) { + return tb_false; + } + } + } + + // write section data + if (!xm_binutils_stream_copy(istream, ostream, filesize)) { + return tb_false; + } + // append null terminator if zeroend is true + if (zeroend) { + tb_byte_t zero = 0; + if (!tb_stream_bwrit(ostream, &zero, 1)) { + return tb_false; + } + } + + // align to 8 bytes + padding = symtab_offset - data_end_offset; + if (padding > 0) { + tb_byte_t zero = 0; + while (padding-- > 0) { + if (!tb_stream_bwrit(ostream, &zero, 1)) { + return tb_false; + } + } + } + + // write symbol table + // strx starts from 4 (after 4-byte size field) + tb_uint32_t strx = 4; + // symbol 0: _binary_xxx_start + xm_macho_nlist_64_t nlist_start; + tb_memset(&nlist_start, 0, sizeof(nlist_start)); + nlist_start.strx = strx; + nlist_start.type = XM_MACHO_N_TYPE_SECT | XM_MACHO_N_EXT; // N_SECT | N_EXT + nlist_start.sect = 1; + nlist_start.desc = 0; + nlist_start.value = 0; + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)&nlist_start, sizeof(nlist_start))) { + return tb_false; + } + strx += (tb_uint32_t)(start_len + 1); + + // symbol 1: _binary_xxx_end + xm_macho_nlist_64_t nlist_end; + tb_memset(&nlist_end, 0, sizeof(nlist_end)); + nlist_end.strx = strx; + nlist_end.type = XM_MACHO_N_TYPE_SECT | XM_MACHO_N_EXT; // N_SECT | N_EXT + nlist_end.sect = 1; + nlist_end.desc = 0; + nlist_end.value = data_size; + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)&nlist_end, sizeof(nlist_end))) { + return tb_false; + } + strx += (tb_uint32_t)(end_len + 1); + + // align to 8 bytes + padding = strtab_offset - (symtab_offset + nlist_size * nlist_count); + if (padding > 0) { + tb_byte_t zero = 0; + while (padding-- > 0) { + if (!tb_stream_bwrit(ostream, &zero, 1)) { + return tb_false; + } + } + } + + // write string table + tb_stream_bwrit(ostream, (tb_byte_t const *)&strtab_size, 4); + tb_stream_bwrit(ostream, (tb_byte_t const *)symbol_start, start_len); + tb_byte_t null = 0; + tb_stream_bwrit(ostream, &null, 1); + tb_stream_bwrit(ostream, (tb_byte_t const *)symbol_end, end_len); + tb_stream_bwrit(ostream, &null, 1); + + // align string table to 8 bytes + padding = strtab_size - (4 + (tb_uint32_t)start_len + 1 + (tb_uint32_t)end_len + 1); + if (padding > 0) { + tb_byte_t zero = 0; + while (padding-- > 0) { + if (!tb_stream_bwrit(ostream, &zero, 1)) { + return tb_false; + } + } + } + + return tb_true; +} + +static tb_bool_t xm_binutils_bin2macho_dump_32(tb_stream_ref_t istream, + tb_stream_ref_t ostream, + tb_char_t const *symbol_prefix, + tb_char_t const *plat, + tb_char_t const *arch, + tb_char_t const *basename, + tb_uint32_t minos, + tb_uint32_t sdk, + tb_bool_t zeroend) { + tb_assert_and_check_return_val(istream && ostream, tb_false); + + // get file size + tb_hong_t filesize = tb_stream_size(istream); + if (filesize < 0 || filesize > 0xffffffffU) { + return tb_false; + } + tb_uint32_t datasize = (tb_uint32_t)filesize; + // add null terminator if zeroend is true + if (zeroend) { + if (datasize >= 0xffffffffU) { + return tb_false; // would overflow + } + datasize++; + } + + // generate symbol names from filename + tb_char_t symbol_name[256] = {0}; + tb_char_t symbol_start[256] = {0}; + tb_char_t symbol_end[256] = {0}; + + // use basename or default to "data" + if (!basename || !basename[0]) { + basename = "data"; + } + + // build symbol name + // On macOS, C compiler adds an underscore prefix, so we generate symbols with two underscores + // (C code declares _binary_xxx, compiler generates __binary_xxx in object file, so we define __binary_xxx) + if (symbol_prefix) { + tb_snprintf(symbol_name, sizeof(symbol_name), "_%s%s", symbol_prefix, basename); + } else { + tb_snprintf(symbol_name, sizeof(symbol_name), "__binary_%s", basename); + } + + // replace non-alphanumeric with underscore + for (tb_size_t i = 0; symbol_name[i]; i++) { + if (!tb_isalpha(symbol_name[i]) && !tb_isdigit(symbol_name[i]) && symbol_name[i] != '_') { + symbol_name[i] = '_'; + } + } + + tb_snprintf(symbol_start, sizeof(symbol_start), "%s_start", symbol_name); + tb_snprintf(symbol_end, sizeof(symbol_end), "%s_end", symbol_name); + + // calculate offsets + tb_uint32_t header_size = sizeof(xm_macho_header_t); + tb_uint32_t segment_cmd_size = sizeof(xm_macho_segment_command_t); + tb_uint32_t section_size = sizeof(xm_macho_section_t); + tb_uint32_t symtab_cmd_size = sizeof(xm_macho_symtab_command_t); + tb_uint32_t build_version_cmd_size = sizeof(xm_macho_build_version_command_t); + tb_uint32_t segment_cmd_total_size = segment_cmd_size + section_size; + tb_uint32_t data_offset = xm_binutils_bin2macho_align(header_size + segment_cmd_total_size + symtab_cmd_size + build_version_cmd_size, 4); + tb_uint32_t data_size = datasize; + tb_uint32_t data_end_offset = data_offset + data_size; + tb_uint32_t symtab_offset = xm_binutils_bin2macho_align(data_end_offset, 4); + tb_uint32_t nlist_size = sizeof(xm_macho_nlist_t); + tb_uint32_t nlist_count = 2; // start, end + tb_uint32_t strtab_offset = symtab_offset + nlist_size * nlist_count; + tb_uint32_t strtab_size = 4; // initial 4-byte size field + tb_size_t start_len = tb_strlen(symbol_start); + tb_size_t end_len = tb_strlen(symbol_end); + strtab_size += (tb_uint32_t)(start_len + 1); + strtab_size += (tb_uint32_t)(end_len + 1); + strtab_size = xm_binutils_bin2macho_align(strtab_size, 4); + + // write Mach-O header + xm_macho_header_t header; + tb_memset(&header, 0, sizeof(header)); + header.magic = XM_MACHO_MAGIC_32; + header.cputype = xm_binutils_bin2macho_get_cputype(arch); + header.cpusubtype = xm_binutils_bin2macho_get_cpusubtype(arch); + header.filetype = XM_MACHO_FILE_TYPE_OBJECT; + header.ncmds = 3; // segment + symtab + build_version + header.sizeofcmds = segment_cmd_total_size + symtab_cmd_size + build_version_cmd_size; + header.flags = 0; + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)&header, sizeof(header))) { + return tb_false; + } + + // write segment command + xm_macho_segment_command_t segment; + tb_memset(&segment, 0, sizeof(segment)); + segment.cmd = XM_MACHO_LC_SEGMENT; + segment.cmdsize = segment_cmd_total_size; + tb_strncpy(segment.segname, "__TEXT", 16); + segment.vmaddr = 0; + segment.vmsize = data_size; + segment.fileoff = data_offset; + segment.filesize = data_size; + segment.maxprot = XM_MACHO_VM_PROT_READ; // VM_PROT_READ (read-only) + segment.initprot = XM_MACHO_VM_PROT_READ; // VM_PROT_READ (read-only) + segment.nsects = 1; + segment.flags = 0; + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)&segment, sizeof(segment))) { + return tb_false; + } + + // write section + xm_macho_section_t section; + tb_memset(§ion, 0, sizeof(section)); + tb_strncpy(section.sectname, "__const", 16); + tb_strncpy(section.segname, "__TEXT", 16); + section.addr = 0; + section.size = data_size; + section.offset = data_offset; + section.align = 2; // 2^2 = 4 bytes + section.reloff = 0; + section.nreloc = 0; + section.flags = XM_MACHO_SECT_TYPE_REGULAR | XM_MACHO_SECT_ATTR_SOME_INITS; + section.reserved1 = 0; + section.reserved2 = 0; + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)§ion, sizeof(section))) { + return tb_false; + } + + // write symtab command + xm_macho_symtab_command_t symtab; + tb_memset(&symtab, 0, sizeof(symtab)); + symtab.cmd = XM_MACHO_LC_SYMTAB; + symtab.cmdsize = symtab_cmd_size; + symtab.symoff = symtab_offset; + symtab.nsyms = nlist_count; + symtab.stroff = strtab_offset; + symtab.strsize = strtab_size; + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)&symtab, sizeof(symtab))) { + return tb_false; + } + + // write build version command + xm_macho_build_version_command_t build_version; + tb_memset(&build_version, 0, sizeof(build_version)); + build_version.cmd = XM_MACHO_LC_BUILD_VERSION; + build_version.cmdsize = build_version_cmd_size; + build_version.platform = xm_binutils_bin2macho_get_platform(plat); + build_version.minos = minos; + build_version.sdk = sdk; + build_version.ntools = 0; + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)&build_version, sizeof(build_version))) { + return tb_false; + } + + // align to 4 bytes + tb_uint32_t padding = data_offset - (header_size + segment_cmd_total_size + symtab_cmd_size + build_version_cmd_size); + if (padding > 0) { + tb_byte_t zero = 0; + while (padding-- > 0) { + if (!tb_stream_bwrit(ostream, &zero, 1)) { + return tb_false; + } + } + } + + // write section data + if (!xm_binutils_stream_copy(istream, ostream, filesize)) { + return tb_false; + } + // append null terminator if zeroend is true + if (zeroend) { + tb_byte_t zero = 0; + if (!tb_stream_bwrit(ostream, &zero, 1)) { + return tb_false; + } + } + + // align to 4 bytes + padding = symtab_offset - data_end_offset; + if (padding > 0) { + tb_byte_t zero = 0; + while (padding-- > 0) { + if (!tb_stream_bwrit(ostream, &zero, 1)) { + return tb_false; + } + } + } + + // write symbol table + // strx starts from 4 (after 4-byte size field) + tb_uint32_t strx = 4; + // symbol 0: _binary_xxx_start + xm_macho_nlist_t nlist_start; + tb_memset(&nlist_start, 0, sizeof(nlist_start)); + nlist_start.strx = strx; + nlist_start.type = XM_MACHO_N_TYPE_SECT | XM_MACHO_N_EXT; // N_SECT | N_EXT + nlist_start.sect = 1; + nlist_start.desc = 0; + nlist_start.value = 0; + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)&nlist_start, sizeof(nlist_start))) { + return tb_false; + } + strx += (tb_uint32_t)(start_len + 1); + + // symbol 1: _binary_xxx_end + xm_macho_nlist_t nlist_end; + tb_memset(&nlist_end, 0, sizeof(nlist_end)); + nlist_end.strx = strx; + nlist_end.type = XM_MACHO_N_TYPE_SECT | XM_MACHO_N_EXT; // N_SECT | N_EXT + nlist_end.sect = 1; + nlist_end.desc = 0; + nlist_end.value = data_size; + if (!tb_stream_bwrit(ostream, (tb_byte_t const *)&nlist_end, sizeof(nlist_end))) { + return tb_false; + } + strx += (tb_uint32_t)(end_len + 1); + + // align to 4 bytes + padding = strtab_offset - (symtab_offset + nlist_size * nlist_count); + if (padding > 0) { + tb_byte_t zero = 0; + while (padding-- > 0) { + if (!tb_stream_bwrit(ostream, &zero, 1)) { + return tb_false; + } + } + } + + // write string table + tb_stream_bwrit(ostream, (tb_byte_t const *)&strtab_size, 4); + tb_stream_bwrit(ostream, (tb_byte_t const *)symbol_start, start_len); + tb_byte_t null = 0; + tb_stream_bwrit(ostream, &null, 1); + tb_stream_bwrit(ostream, (tb_byte_t const *)symbol_end, end_len); + tb_stream_bwrit(ostream, &null, 1); + + // align string table to 4 bytes + padding = strtab_size - (4 + (tb_uint32_t)start_len + 1 + (tb_uint32_t)end_len + 1); + if (padding > 0) { + tb_byte_t zero = 0; + while (padding-- > 0) { + if (!tb_stream_bwrit(ostream, &zero, 1)) { + return tb_false; + } + } + } + + return tb_true; +} + +static tb_bool_t xm_binutils_bin2macho_dump(tb_stream_ref_t istream, + tb_stream_ref_t ostream, + tb_char_t const *symbol_prefix, + tb_char_t const *plat, + tb_char_t const *arch, + tb_char_t const *basename, + tb_uint32_t minos, + tb_uint32_t sdk, + tb_bool_t zeroend) { + if (xm_binutils_bin2macho_is_64bit(arch)) { + return xm_binutils_bin2macho_dump_64(istream, ostream, symbol_prefix, plat, arch, basename, minos, sdk, zeroend); + } else { + return xm_binutils_bin2macho_dump_32(istream, ostream, symbol_prefix, plat, arch, basename, minos, sdk, zeroend); + } +} + +/* ////////////////////////////////////////////////////////////////////////////////////// + * implementation + */ + +/* generate Mach-O object file from binary file + * + * local ok, errors = binutils.bin2macho(binaryfile, outputfile, symbol_prefix, plat, arch, basename) + */ +tb_int_t xm_binutils_bin2macho(lua_State *lua) { + tb_assert_and_check_return_val(lua, 0); + + // get the binaryfile + tb_char_t const *binaryfile = luaL_checkstring(lua, 1); + tb_check_return_val(binaryfile, 0); + + // get the outputfile + tb_char_t const *outputfile = luaL_checkstring(lua, 2); + tb_check_return_val(outputfile, 0); + + // get symbol prefix (optional) + tb_char_t const *symbol_prefix = lua_isstring(lua, 3) ? lua_tostring(lua, 3) : tb_null; + + // get plat (optional) + tb_char_t const *plat = lua_isstring(lua, 4) ? lua_tostring(lua, 4) : tb_null; + + // get arch (optional) + tb_char_t const *arch = lua_isstring(lua, 5) ? lua_tostring(lua, 5) : tb_null; + + // get basename (optional) + tb_char_t const *basename = lua_isstring(lua, 6) ? lua_tostring(lua, 6) : tb_null; + + // get minos version string (optional) + tb_char_t const *minos_str = lua_isstring(lua, 7) ? lua_tostring(lua, 7) : tb_null; + tb_uint32_t minos = xm_binutils_bin2macho_parse_version(minos_str); + + // get sdk version string (optional) + tb_char_t const *sdk_str = lua_isstring(lua, 8) ? lua_tostring(lua, 8) : tb_null; + tb_uint32_t sdk = xm_binutils_bin2macho_parse_version(sdk_str); + + // get zeroend (optional, default: false) + tb_bool_t zeroend = lua_toboolean(lua, 9); + + // do dump + tb_bool_t ok = tb_false; + tb_stream_ref_t istream = tb_stream_init_from_file(binaryfile, TB_FILE_MODE_RO); + tb_stream_ref_t ostream = tb_stream_init_from_file(outputfile, + TB_FILE_MODE_RW | TB_FILE_MODE_CREAT | TB_FILE_MODE_TRUNC); + do { + if (!tb_stream_open(istream)) { + lua_pushboolean(lua, tb_false); + lua_pushfstring(lua, "bin2macho: open %s failed", binaryfile); + break; + } + + if (!tb_stream_open(ostream)) { + lua_pushboolean(lua, tb_false); + lua_pushfstring(lua, "bin2macho: open %s failed", outputfile); + break; + } + + if (!xm_binutils_bin2macho_dump(istream, ostream, symbol_prefix, plat, arch, basename, minos, sdk, zeroend)) { + lua_pushboolean(lua, tb_false); + lua_pushfstring(lua, "bin2macho: dump data failed"); + break; + } + + ok = tb_true; + lua_pushboolean(lua, ok); + + } while (0); + + if (istream) { + tb_stream_clos(istream); + } + istream = tb_null; + + if (ostream) { + tb_stream_clos(ostream); + } + ostream = tb_null; + + return ok ? 1 : 2; +} + diff --git a/core/src/xmake/binutils/prefix.h b/core/src/xmake/binutils/prefix.h new file mode 100644 index 000000000..739e220f7 --- /dev/null +++ b/core/src/xmake/binutils/prefix.h @@ -0,0 +1,70 @@ +/*!A cross-platform build utility based on Lua + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright (C) 2015-present, Xmake Open Source Community. + * + * @author ruki + * @file prefix.h + * + */ +#ifndef XM_BINUTILS_PREFIX_H +#define XM_BINUTILS_PREFIX_H + +/* ////////////////////////////////////////////////////////////////////////////////////// + * includes + */ +#include "../prefix.h" + +/* ////////////////////////////////////////////////////////////////////////////////////// + * inline implementation + */ + +/* copy data from input stream to output stream + * + * @param istream the input stream + * @param ostream the output stream + * @param size the size to copy + * + * @return tb_true on success, tb_false on failure + */ +static __tb_inline__ tb_bool_t xm_binutils_stream_copy(tb_stream_ref_t istream, tb_stream_ref_t ostream, tb_hize_t size) { + tb_assert_and_check_return_val(istream && ostream && size > 0, tb_false); + + tb_byte_t data[TB_STREAM_BLOCK_MAXN]; + tb_hize_t writ = 0; + do { + tb_size_t need = (tb_size_t)tb_min(size - writ, (tb_hize_t)TB_STREAM_BLOCK_MAXN); + tb_check_break(need); + + tb_long_t real = tb_stream_read(istream, data, need); + if (real > 0) { + if (!tb_stream_bwrit(ostream, data, (tb_size_t)real)) { + return tb_false; + } + writ += real; + } else if (!real) { + tb_long_t wait = tb_stream_wait(istream, TB_STREAM_WAIT_READ, tb_stream_timeout(istream)); + tb_check_break(wait > 0 && (wait & TB_STREAM_WAIT_READ)); + } else { + return tb_false; + } + + tb_check_break(writ < size); + } while (1); + + return tb_true; +} + +#endif + |
