复制与修补:复制与修补教程
Copy-and-Patch: A Copy-and-Patch Tutorial

原始链接: https://transactional.blog/copy-and-patch/tutorial

这段代码定义了一组函数,用于创建和修补小型代码模板,可能用于即时编译(JIT)或动态代码修改。它专注于简单的整数运算。 代码提供了预定义的字节序列(`cnp_stencil_..._code`),代表x86-64指令:将整数加载到寄存器(r12d, r13d),将两个寄存器的内容相加,以及在eax中返回值。 像`cnp_copy_...`这样的函数将这些预定义的指令序列复制到提供的内存缓冲区(`stencil_start`)中。`cnp_patch_...`函数允许通过在指令序列的特定偏移量处插入整数值来修改这些模板。值得注意的是,加法和返回模板不需要修补,因为它们是完整的指令。这种方法能够动态生成具有可定制整数值的代码片段。

Hacker News新 | 过去 | 评论 | 提问 | 展示 | 招聘 | 提交登录 复制和补丁:一个复制和补丁教程 (transactional.blog) 10 分,by todsacerdoti 45 分钟前 | 隐藏 | 过去 | 收藏 | 1 评论 shoo 5 分钟前 [–] 配套文章“工作原理”值得与本教程一起阅读https://transactional.blog/copy-and-patch/ (关键词:滥用:4,强制:3,技巧:1,机会:1)回复 考虑申请YC冬季2026批次!申请截止至11月10日 指南 | 常见问题 | 列表 | API | 安全 | 法律 | 申请YC | 联系 搜索:
相关文章

原文
#include <stdint.h>

uint8_t cnp_stencil_load_int_reg1_code[] = {
   0x41, 0xbc, 0x00, 0x00, 0x00, 0x00, // mov r12d,0x0
};
uint8_t* cnp_copy_load_int_reg1(uint8_t* stencil_start) {
  const size_t stencil_size = sizeof(cnp_stencil_load_int_reg1_code);
  memcpy(stencil_start, cnp_stencil_load_int_reg1_code, stencil_size);
  return stencil_start + stencil_size;
}
void cnp_patch_load_int_reg1(uint8_t* stencil_start, int value) {
  // 2: R_X86_64_32 cnp_value_hole  ->  0x02 offset
  memcpy(stencil_start + 0x2, &value, sizeof(value));
}

uint8_t cnp_stencil_load_int_reg2_code[] = {
   0x41, 0xbd, 0x00, 0x00, 0x00, 0x00, // mov r13d,0x0
};
uint8_t* cnp_copy_load_int_reg2(uint8_t* stencil_start) {
  const size_t stencil_size = sizeof(cnp_stencil_load_int_reg2_code);
  memcpy(stencil_start, cnp_stencil_load_int_reg2_code, stencil_size);
  return stencil_start + stencil_size;
}
void cnp_patch_load_int_reg2(uint8_t* stencil_start, int value) {
  // 12: R_X86_64_32 cnp_value_hole  ->  0x12 - 0x10 base = 0x2
  memcpy(stencil_start + 0x2, &value, sizeof(value));
}

uint8_t cnp_stencil_add_int1_int2_code[] = {
  0x45, 0x01, 0xec, // add r12d,r13d
};
uint8_t* cnp_copy_add_int1_int2(uint8_t* stencil_start) {
  const size_t stencil_size = sizeof(cnp_stencil_add_int1_int2_code);
  memcpy(stencil_start, cnp_stencil_add_int1_int2_code, stencil_size);
  return stencil_start + stencil_size;
}
// No patching needed

uint8_t cnp_stencil_return_int1_code[] = {
  0x44, 0x89, 0xe0, // mov eax,r12d
  0xc3,             // ret
};
uint8_t* cnp_copy_return_int1(uint8_t* stencil_start) {
  const size_t stencil_size = sizeof(cnp_stencil_return_int1_code);
  memcpy(stencil_start, cnp_stencil_return_int1_code, stencil_size);
  return stencil_start + stencil_size;
}
// No patching needed
联系我们 contact @ memedata.com