Friday, December 27, 2013

Linux跟Windows對記憶體保護機制的不同

一樣的程式,分別用GCC-4.4/Linux, GCC-4.5/Cygwin, VC 9.0/Windows 7

  1 #include
  2 #include
  3
  4 int main (void)
  5 {
  6
  7     char *a  = "abcd";
  8     char b[] = "ABCD";
  9
 10     a[0] = 'x';
 11     b[0] = 'x';
 12
 13     printf ("a:%s\n", a);
 14     printf ("b:%s\n", b);
 15
 16     return (0);
 17 }

Linux會將上述第7行的資料保護著,設為唯讀。

LungSWuBlog:~/temp$ gcc a.c -o a
LungSWuBlog:~/temp$ ./a
程式記憶體區段錯誤
LungSWuBlog:~/temp$ gcc -c a.c -o a.o
LungSWuBlog:~/temp$ objdump -s a.o

a.o:     file format elf64-x86-64

Contents of section .text:
 0000 554889e5 4883ec20 48c745e8 00000000  UH..H.. H.E.....
 0010 c745f041 424344c6 45f40048 8b45e8c6  .E.ABCD.E..H.E..
 0020 0078c645 f078b800 00000048 8b55e848  .x.E.x.....H.U.H
 0030 89d64889 c7b80000 0000e800 000000b8  ..H.............
 0040 00000000 488d55f0 4889d648 89c7b800  ....H.U.H..H....
 0050 000000e8 00000000 b8000000 00c9c3    ...............
Contents of section .rodata:
 0000 61626364 00613a25 730a0062 3a25730a  abcd.a:%s..b:%s.
 0010 00                                   .
Contents of section .comment:
 0000 00474343 3a202855 62756e74 7520342e  .GCC: (Ubuntu 4.
 0010 342e332d 34756275 6e747535 2e312920  4.3-4ubuntu5.1)
 0020 342e342e 3300                        4.4.3.
Contents of section .eh_frame:
 0000 14000000 00000000 017a5200 01781001  .........zR..x..
 0010 1b0c0708 90010000 1c000000 1c000000  ................
 0020 00000000 5f000000 00410e10 4386020d  ...._....A..C...
 0030 06000000 00000000                    ........
LungSWuBlog:~/temp$

Windows 7不會將上述第7行的資料保護著,還是可以寫入。

[VC 9.0]
D:\LungSWuBlog>cl a.c

/out:a.exe
a.obj

D:\LungSWuBlog>a
a:xbcd
b:xBCD

D:\LungSWuBlog>

[Cygwin]

LungSWuBlog ~/tmp
$ gcc a.c -o a

LungSWuBlog ~/tmp
$ ./a.exe
a:xbcd
b:xBCD

LungSWuBlog ~/tmp
$ gcc -c a.c -o a.o

LungSWuBlog ~/tmp
$ objdump.exe -s a.o

a.o:     file format pe-i386

Contents of section .text:
 0000 5589e583 e4f083ec 20e80000 0000c744  U....... ......D
 0010 241c0000 0000c744 24174142 4344c644  $......D$.ABCD.D
 0020 241b008b 44241cc6 0078c644 2417788b  $...D$...x.D$.x.
 0030 44241c89 442404c7 04240500 0000e800  D$..D$...$......
 0040 0000008d 44241789 442404c7 04240b00  ....D$..D$...$..
 0050 0000e800 000000b8 00000000 c9c39090  ................
Contents of section .rdata:
 0000 61626364 00613a25 730a0062 3a25730a  abcd.a:%s..b:%s.
 0010 00000000                             ....

LungSWuBlog ~/tmp
$

最後,跟program loader也可能有關

No comments:

Post a Comment