Skip to content

__strcpy_sse2_unaligned

Example code

在运行owasp的Doubly freeing memory文章中给出的代码时,发现的这个错误:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

#define BUFSIZE1    512
#define BUFSIZE2    ((BUFSIZE1/2) - 8)

int main(int argc, char **argv) {
  char *buf1R1;
  char *buf2R1;
  char *buf1R2;

  buf1R1 = (char *) malloc(BUFSIZE2);
  buf2R1 = (char *) malloc(BUFSIZE2);

  free(buf1R1);
  free(buf2R1);

  buf1R2 = (char *) malloc(BUFSIZE1);
  strncpy(buf1R2, argv[1], BUFSIZE1-1);

  free(buf2R1); // double free
  free(buf1R2); 
}

编译后,我直接这样运行,没有传入一个argument:

./a.out

进程直接core了

(base) [github@VM_0_10_centos drdobbs]$ ./a.out
Segmentation fault (core dumped)
(base) [github@VM_0_10_centos drdobbs]$ gdb a.out core.23001
GNU gdb (GDB) Red Hat Enterprise Linux 7.6.1-110.el7
Copyright (C) 2013 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-redhat-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /home/github/repository/programming-language/docs/C++/Language/Idiom/The-rule-of-three-five-zero/Code/drdobbs/a.out...(no debugging symbols found)...done.
[New LWP 23001]
Core was generated by `./a.out'.
Program terminated with signal 11, Segmentation fault.
#0  0x00007f2a81b1057f in __strncpy_sse2_unaligned () from /lib64/libc.so.6
Missing separate debuginfos, use: debuginfo-install glibc-2.17-260.el7.x86_64
(gdb) where
#0  0x00007f2a81b1057f in __strncpy_sse2_unaligned () from /lib64/libc.so.6
#1  0x000000000040062d in main ()

分析

stackoverflow strcpy misalignment __strcpy_sse2_unaligned()

The compiler is unable to determine whether your source and destination char* are aligned (usually word or even quad-word aligned) and therefore is backing up to the unaligned yet possibly optimized strcpy routine. You'd need to explicitly hint about the missed guess it is doing; otherwise, it'll just give up: unaligned access is often disallowed for SSE or still very slow.

But, if you're getting a segfault it is very unlikely it's a library issue (it's a largely used function) and it just cannot be due to misalignment. It's much likely your code exhibits undefined behavior somewhere, due to buffer overrun, for example. Check your pointers with valgrind or -fsanitize=address.

TODO

这个问题和之前碰到过的收录在有道云笔记programming language/c family language/alignment/memory access and alignment中的密切相关。

另外参见:

http://forums.codeguru.com/showthread.php?559555-segmentation-fault-__strcpy_sse2_unaligned-(c-code)