一、错误现象
对实际业务没有影响,报错打印如下内容:
[ 615.211252] Alignment trap: app(1598) PC=0xb6e27de0 Instr=0x20d130b2 Address=0xb52afbed FSR 0x011
二、分析处理
1.获取maps
cat /proc/1598/maps
......
b6dac000-b6ed2000 r-xp 00000000 00:02 2128 /lib/libc-2.26.so
b6ed2000-b6ee2000 ---p 00126000 00:02 2128 /lib/libc-2.26.so
b6ee2000-b6ee4000 r--p 00126000 00:02 2128 /lib/libc-2.26.so
b6ee4000-b6ee5000 rw-p 00128000 00:02 2128 /lib/libc-2.26.so
b6ee5000-b6ee8000 rw-p 00000000 00:00 0
......
2.分析
(1)进程信息:app (1598) — 表示进程名为app-save,进程ID(PID)为1598。
(2)程序计数器(PC):0xb6e27de0 — 发生错误时的指令地址。
(3)指令机器码:0x20d130b2 — 导6致错误的指令的编码。
(4)访问地址:0xb52afbed — 可能未对齐的内存地址。
(5)FSR值:0x011 — Fault Status Register的值,通常表示对齐错误。
(6)PC 地址 0xb6e27de0 不在应用程序的代码段范围内(00010000-00019000),而是落在了 libc 库的代码段中(b6dac000-b6ed2000)。这表明错误实际上发生在 C 库函数内部,而不是应用程序代码中。
3.结论
应用程序传递了一个未对齐的指针给某个 C 库函数(如 memcpy、strcpy、printf 等),然后该库函数尝试访问这个未对齐的地址时触发了对齐错误。
四、解决方法
1.原始代码
static int file_write_data(FILE *file, void *data, size_t len)
{
if(file == NULL)
{
printf("[save] : file is NULL\n");
return -1;
}
size_t w_len = fwrite(data, 1, len, file);
if (w_len != len)
{
perror("Failed to write file data");
return -2;
}
return 0;
}
2.修改函数,手动对齐64KiB
#define BLOCK_SIZE (64 * 1024) // 64KiB
static uint8_t aligned_buf[BLOCK_SIZE] __attribute__((aligned(8)));
static int file_write_data(FILE *file, void *data, size_t len)
{
if (file == NULL)
{
printf("[save] : file is NULL\n");
return -1;
}
size_t remaining = len;
uint8_t *src = (uint8_t *)data;
while (remaining > 0)
{
size_t to_copy = (remaining < BLOCK_SIZE) ? remaining : BLOCK_SIZE;
memcpy(aligned_buf, src, to_copy);
size_t w_len = fwrite(aligned_buf, 1, to_copy, file);
if (w_len != to_copy)
{
perror("Failed to write file data");
return -2;
}
remaining -= to_copy;
src += to_copy;
}
return 0;
}
修改后问题得到解决


被折叠的 条评论
为什么被折叠?



