How to write() data more than 2G in a time - c

I have already defined _LARGEFILE64_SOURCE and _FILE_OFFSET_BITS 64
to support open() file that more than 2G. That seems to be all right.
But if I try to write() data more than 2G at a time ( such as 64G ), write() will return a value much smaller than 64G (Exactly 2147479552). I guess that write() only can write data smaller than 2G in a time.
Here is my code:
#define _GNU_SOURCE
#define _LARGEFILE_SOURCE
#define _LARGEFILE64_SOURCE
#define _FILE_OFFSET_BITS 64
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <errno.h>
#include <unistd.h>
#include <mmap.h>
#define SPACE_SIZE 68719476736
int main()
{
ssize_t err;
void* zeros;
int fd = open64("./test", O_CREAT|O_RDWR|O_LARGEFILE, 0644);
assert(fd != -1);
int zero_fd = open("/dev/zero", O_RDWR);
assert(zero_fd != -1);
zeros = mmap(NULL, SPACE_SIZE, PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS, zero_fd, 0);
assert(zeros != (void *)-1);
err = write(fd, zeros, SPACE_SIZE);
assert(err == SPACE_SIZE); // Received SIGABRT, err = 2147479552
munmap(zeros, SPACE_SIZE);
}
How to write() data more than 2G in a time?
Supplementary info:
The result of readelf -h ./a.out. a.out is my program's name
ELF Header:
Magic: 7f 45 4c 46 02 01 01 00 00 00 00 00 00 00 00 00
Class: ELF64
Data: 2's complement, little endian
Version: 1 (current)
OS/ABI: UNIX - System V
ABI Version: 0
Type: DYN (Shared object file)
Machine: Advanced Micro Devices X86-64
Version: 0x1
Entry point address: 0x660
Start of program headers: 64 (bytes into file)
Start of section headers: 6672 (bytes into file)
Flags: 0x0
Size of this header: 64 (bytes)
Size of program headers: 56 (bytes)
Number of program headers: 9
Size of section headers: 64 (bytes)
Number of section headers: 29
Section header string table index: 28

Indeed, and this fact is well documented in man write:
On Linux, write() (and similar system calls) will transfer at most 0x7ffff000 (2,147,479,552) bytes, returning the number of bytes actually transferred. (This is true on both 32-bit and 64-bit systems.)
So if you're using Linux, there is no way to write 64GB in a single call to write().
You can, however, create a file which appears to contain 64GB of NUL bytes by seeking to offset 64GB-1 and writing a single NUL byte. (Or, as #o11c points out in a comment, you could use ftruncate(fd, SPACE_SIZE);.) Either of those will create a sparse file which will not actually occupy much disk space, but it will act as though it were 64GB of NULs.

Related

Why is int32_t aliased to int in stdint.h?

In my Linux VM, even iwth int32_t, if I assign it different values, it gives different size. For example:
#include <stdint.h>
int32_t i = 0x123456;
int main(int argc, char *argv[])
{
return 0;
}
objdump reports i only takes 3 bytes:
Disassembly of section .data:
0804a010 <__data_start>:
804a010: 00 00 add %al,(%eax)
...
0804a014 <__dso_handle>:
804a014: 00 00 add %al,(%eax)
...
0804a018 <i>:
804a018: 56 push %esi
804a019: 34 12 xor $0x12,%al
...
Looking at stdint.h, I found out that int32_t is just a typedef to int:
typedef int int32_t;
I though that C99 standard enforces that int32_t is guaranteed to be exactly 4 bytes?
C (like C++) has something called the "as-if" rule. From the language perspective, things just have to appear as if they obey the C rules, even if the actual binary does not.
In particular, sizeof(int32_t) is most important for things like malloc(100*sizeof(int32_t)), where you'd definitely want 400 bytes. (Or 200 bytes, when bytes are 16 bits).
In this simple case however, you can't detect the "missing" byte by any standard method, so this is legal.

how to make holes in file to erase data by c in linux

Updated: This FALLOC_FL_PUNCH_HOLE is not originally supported by 3.0.0-17, I think I need to patch it.
I know linux have this hole feature, and I am wondering if I could make a hole in a existing file.
For specific, I have created a file named hole_test by these codes:
18 #include <stdlib.h>
19 #include <sys/types.h>
20 #include <sys/stat.h>
21 #include <fcntl.h>
22 #include <unistd.h>
23 #include <errno.h>
24
25 int main(int argc, char **argv)
26 {
27 int fd;
28 char a[7]="happy!";
30 fd = open("hole_test", O_CREAT|O_RDWR, 0666);
31 if(fd == -1)
32 printf("error, %s\n", (char *)strerror(errno));
35 // fallocate(fd, 0x02, 0,0);
36 // pwrite(fd, a, sizeof(a), 0);
37 // pwrite(fd, a, sizeof(b), 65536);
38 close(fd);
39 return 0;
40 }
firstly, I user L36 L37 to create a file. the stat hole_test shows that:
File: `hole_test'
Size: 65540 Blocks: 16 IO Block: 4096 regular file
Device: 801h/2049d Inode: 1052101 Links: 1
Access: (0664/-rw-rw-r--) Uid: ( 1000/ bxshi) Gid: ( 1000/ bxshi)
Access: 2012-04-03 23:02:35.227664608 +0800
Modify: 2012-04-03 23:02:35.227664608 +0800
Change: 2012-04-03 23:02:35.227664608 +0800
Then I use L35 and comment L36 L37 to make a hole in my file.(0x02 equals to FALLOC_FL_PUNCH_HOLE, I did not find where it is defined so just use its value)
and then, by stat hole_test, the Blocks is still 16.
File: `hole_test'
Size: 65540 Blocks: 16 IO Block: 4096 regular file
Device: 801h/2049d Inode: 1052101 Links: 1
Access: (0664/-rw-rw-r--) Uid: ( 1000/ bxshi) Gid: ( 1000/ bxshi)
Access: 2012-04-03 23:02:35.227664608 +0800
Modify: 2012-04-03 23:02:35.227664608 +0800
Change: 2012-04-03 23:02:35.227664608 +0800
I want to know if I could make new holes in this hole_test file to erase existing data?
How could I make a hole in hole_test at offset 0 to 7, in that way I think the Blocks could become 8 and the string I wrote would disappear.
Hope you guys could know what I said and give me some advice.
You use fallocate(fd, FALLOC_FL_PUNCH_HOLE, offset, len). (Supported since Linux 2.6.38) See https://lwn.net/Articles/415889/ for behind-the-scenes details and accompanying patches.
According to the man page for fallocate(2):
The FALLOC_FL_PUNCH_HOLE flag must be ORed with FALLOC_FL_KEEP_SIZE
in mode; in other words, even when punching off the end of the file,
the file size (as reported by stat(2)) does not change.
At least on ext4, if you just pass FALLOC_FL_PUNCH_HOLE, fallocate() will return Operation not supported.
Also note that:
The FALLOC_FL_* flags are
defined in glibc headers only since version 2.18.
So you may need to manually define them if you're using a supported kernel with an earlier version of libc:
// Constants are defined in glibc >= 2.18
#define FALLOC_FL_KEEP_SIZE 0x1
#define FALLOC_FL_PUNCH_HOLE 0x2

How to convert from binary to relocatable object file and back?

I wish to inject an object file into an existing binary. The method I am attempting is:
Convert a compiled binary into a relocatable object file.
Use gcc/ld to link the relocatable object file with the object file to be embedded.
Given the source:
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
puts("main");
return EXIT_SUCCESS;
}
I compile this to host with the following:
gcc -Wall host.c -o host
I do the conversion to relocatable object file with:
objcopy -B i386 -I binary -O elf64-x86-64 host host.o
I then attempt a link with:
gcc host.o -o host
Ideally, this would relink the relocatable object file back to a binary. This would also give a chance to link in any extra object files. Unfortunately the command gives the following error:
/usr/lib/gcc/x86_64-linux-gnu/4.6.1/../../../x86_64-linux-gnu/crt1.o: In function `_start':
(.text+0x20): undefined reference to `main'
collect2: ld returned 1 exit status
My question is why is this error appearing and how would I go about properly relinking?
Something I tried was to link in another object file at this point which contained a dummy main (because I figured I could manually patch up the entry point later anyway), but what happened was that the new binary seemed to relocate the old code in a weird way with the symbol table completely messed up.
Extra Information
readelf on the binary yields the following:
mike#mike-ubuntu:~/Desktop/inject-obj$ readelf -h host
ELF Header:
Magic: 7f 45 4c 46 02 01 01 00 00 00 00 00 00 00 00 00
Class: ELF64
Data: 2's complement, little endian
Version: 1 (current)
OS/ABI: UNIX - System V
ABI Version: 0
Type: EXEC (Executable file)
Machine: Advanced Micro Devices X86-64
Version: 0x1
Entry point address: 0x400410
Start of program headers: 64 (bytes into file)
Start of section headers: 4424 (bytes into file)
Flags: 0x0
Size of this header: 64 (bytes)
Size of program headers: 56 (bytes)
Number of program headers: 9
Size of section headers: 64 (bytes)
Number of section headers: 30
Section header string table index: 27
And on the relocatable object file:
mike#mike-ubuntu:~/Desktop/inject-obj$ readelf -h host.o
ELF Header:
Magic: 7f 45 4c 46 02 01 01 00 00 00 00 00 00 00 00 00
Class: ELF64
Data: 2's complement, little endian
Version: 1 (current)
OS/ABI: UNIX - System V
ABI Version: 0
Type: REL (Relocatable file)
Machine: Advanced Micro Devices X86-64
Version: 0x1
Entry point address: 0x0
Start of program headers: 0 (bytes into file)
Start of section headers: 8480 (bytes into file)
Flags: 0x0
Size of this header: 64 (bytes)
Size of program headers: 0 (bytes)
Number of program headers: 0
Size of section headers: 64 (bytes)
Number of section headers: 5
Section header string table index: 2
Rationale
For those interested, the rationale can be found here.
An executable file that is not PIE is impossible to make relocatable. Relocations have already been performed and the record of those relocations was thrown away. That is, relocating it would require finding all addresses of objects or functions inside the code and data of the binary, but it's impossible to determine whether a sequence of bytes is an address or some other sort of data or code.
There should be a way to do what you originally wanted to do (adding in new code), but the approach you're taking is doomed to failure.

Segfault occurs due to one line of code in C file and entire program does not run

I've created a C program to write to a serial port (/dev/ttyS0) on an embedded ARM system. The kernel running on the embedded ARM system is Linux version 3.0.4, built with the same cross-compiler as the one listed below.
My cross-compiler is arm-linux-gcc (Buildroot 2011.08) 4.3.6, running on an Ubuntu x86_64 host (3.0.0-14-generic #23-Ubuntu SMP). I have used the stty utility to set up the serial port from the command line.
Mysteriously, it seems that the program will refuse to run on the embedded ARM system if a single line of code is present. If the line is removed, the program will run.
Here is a full code listing replicating the problem:
EDIT: I now close the file on error, as suggested in the comments below.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdint.h>
#include <string.h>
#include <errno.h>
#include <termios.h>
int test();
void run_experiment();
int main()
{
run_experiment();
return 0;
}
void run_experiment()
{
printf("Starting program\n");
test();
}
int test()
{
int fd;
int ret;
fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY);
printf("fd = %u\n", fd);
if (fd < 0)
{
close(fd);
return 0;
}
fcntl(fd, F_SETFL, 0);
printf("Now writing to serial port\n");
//TODO:
// segfault occurs due to line of code here
// removing this line causes the program to run properly
ret = write( fd, "test\r\n", sizeof("test\r\n") );
if (ret < 0)
{
close(fd);
return 0;
}
close(fd);
return 1;
}
The output of this program on the ARM system is the following:
Segmentation fault
However, if I remove the line listed above and recompile the program, the problem goes away, and the output is the following:
Starting program
fd = 3
Now writing to serial port
What could be going wrong here, and how do I debug the problem? Would this be an issue with the code, with the cross-compiler compiler, or with a version of the OS?
I have also tried various combinations of O_WRONLY and O_RDWR without O_NOCTTY when opening the file, but the problem still persists.
As suggested by #wildplasser in the comments below, I have replaced the test function with the following code, heavily based on the code at another site (http://www.warpspeed.com.au/cgi-bin/inf2html.cmd?..\html\book\Toolkt40\XPG4REF.INF+112).
However, the program still doesn't run, and I receive the mysterious Segmentation Fault again.
Here is the code:
int test()
{
int fh;
FILE *fp;
char *cp;
if (-1 == (fh = open("/dev/ttyS0", O_RDWR)))
{
perror("Unable to open");
return EXIT_FAILURE;
}
if (NULL == (fp = fdopen(fh, "w")))
{
perror("fdopen failed");
close(fh);
return EXIT_FAILURE;
}
for (cp = "hello world\r\n"; *cp; cp++)
fputc( *cp, fp);
fclose(fp);
return 0;
}
This is very mysterious, since using other programs that I have written, I can use the write() function in a similar fashion to write to sysfs files, without any problem.
HOWEVER, if the program is exactly in the same structure, then I cannot write to /dev/null.
BUT I can successfully write to a sysfs file using exactly the same program!
If the segfault occurred at a particular line in the function, then I would assume that the function call would be causing the segfault. However, the full program does not run!
UPDATE: To provide more information, here is the cross-compiler information used to build on ARM system:
$ arm-linux-gcc --v
Using built-in specs.
Target: arm-unknown-linux-uclibcgnueabi
Configured with: /media/RESEARCH/SAS2-version2/device-system/buildroot/buildroot-2011.08/output/toolchain/gcc-4.3.6/configure --prefix=/media/RESEARCH/SAS2-version2/device-system/buildroot/buildroot-2011.08/output/host/usr --build=x86_64-unknown-linux-gnu --host=x86_64-unknown-linux-gnu --target=arm-unknown-linux-uclibcgnueabi --enable-languages=c,c++ --with-sysroot=/media/RESEARCH/SAS2-version2/device-system/buildroot/buildroot-2011.08/output/host/usr/arm-unknown-linux-uclibcgnueabi/sysroot --with-build-time-tools=/media/RESEARCH/SAS2-version2/device-system/buildroot/buildroot-2011.08/output/host/usr/arm-unknown-linux-uclibcgnueabi/bin --disable-__cxa_atexit --enable-target-optspace --disable-libgomp --with-gnu-ld --disable-libssp --disable-multilib --enable-tls --enable-shared --with-gmp=/media/RESEARCH/SAS2-version2/device-system/buildroot/buildroot-2011.08/output/host/usr --with-mpfr=/media/RESEARCH/SAS2-version2/device-system/buildroot/buildroot-2011.08/output/host/usr --disable-nls --enable-threads --disable-decimal-float --with-float=soft --with-abi=aapcs-linux --with-arch=armv5te --with-tune=arm926ej-s --disable-largefile --with-pkgversion='Buildroot 2011.08' --with-bugurl=http://bugs.buildroot.net/
Thread model: posix
gcc version 4.3.6 (Buildroot 2011.08)
Here is the makefile that I am using to compile my code:
CC=arm-linux-gcc
CFLAGS=-Wall
datacollector: datacollector.o
clean:
rm -f datacollector datacollector.o
UPDATE: Using the debugging suggestions given in the comments and answers below, I found that the segfault was caused by including the \r escape sequence in the string. For some strange reason, the compiler doesn't like the \r escape sequence, and will cause a segfault without running the code.
If the \r escape sequence is removed, then the code runs as expected.
Thus, the offending line of code should be the following:
ret = write( fd, "test\n", sizeof("test\n") );
So for the record, a full test program that actually runs is the following (could someone comment?):
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdint.h>
#include <string.h>
#include <errno.h>
#include <termios.h>
int test();
void run_experiment();
int main()
{
run_experiment();
return 0;
}
void run_experiment()
{
printf("Starting program\n");
fflush(stdout);
test();
}
int test()
{
int fd;
int ret;
char *msg = "test\n";
// NOTE: This does not work and will cause a segfault!
// even if the fflush is called after each printf,
// the program will still refuse to run
//char *msg = "test\r\n";
fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY);
printf("fd = %u\n", fd);
fflush(stdout);
if (fd < 0)
{
close(fd);
return 0;
}
fcntl(fd, F_SETFL, 0);
printf("Now writing to serial port\n");
fflush(stdout);
ret = write( fd, msg, strlen(msg) );
if (ret < 0)
{
close(fd);
return 0;
}
close(fd);
return 1;
}
EDIT: As an aside to all of this, is it better to use:
ret = write( fd, msg, sizeof(msg) );
or is it better to use:
ret = write( fd, msg, strlen(msg) );
Which is better? Is it better to use sizeof() or strlen()? It appears that some of the data in the string is truncated and not written to the serial port using the sizeof() function.
As I understand from Pavel's comment below, it is better to use strlen() if msg is declared as char*.
Moreover, it appears that gcc is not creating a proper binary when the escape sequence \r is being used to write to a tty.
Referring to the last test program given in my post above, the following line of code causes a segfault without the program running:
char *msg = "test\r\n";
As suggested by Igor in the comments, I have run the gdb debugger on the binary with the offending line of code. I had to compile the program with the -g switch.
The gdb debugger is being run natively on the ARM system, and all binaries are being built for the ARM architecture on the host using the same Makefile. All binaries are being built using the arm-linux-gcc cross-compiler.
The output of gdb (running natively on the ARM system) is as follows:
GNU gdb 6.8
Copyright (C) 2008 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 "arm-unknown-linux-uclibcgnueabi"...
"/programs/datacollector": not in executable format: File format not recognized
(gdb) run
Starting program:
No executable file specified.
Use the "file" or "exec-file" command.
(gdb) file datacollector
"/programs/datacollector": not in executable format: File format not recognized
(gdb)
However, if I change the single line of code to the following, the binary compiles and runs properly. Note that the \r escape sequence is missing:
char *msg = "test\n";
Here is the output of gdb after changing the single line of code:
GNU gdb 6.8
Copyright (C) 2008 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 "arm-unknown-linux-uclibcgnueabi"...
(gdb) run
Starting program: /programs/datacollector
Starting program
fd = 4
Now writing to serial port
test
Program exited normally.
(gdb)
UPDATE:
As suggested by Zack in an answer below, I have now ran a test program on the embedded
Linux system. Although Zack gives a detailed script to run on the embedded system, I was
unable to run the script due to the lack of development tools (compiler and headers) installed in the root file system.
In lieu of installing these tools, I simply compiled the nice test program that Zack provided in the script and
used the strace utility. The strace utility was run on the embedded system.
At last, I think that I understand what is happening.
The bad binary was transferred to the embedded system over FTP, using an SPI-to-Ethernet bridge (KSZ8851SNL).
There is a driver for the KSZ8851SNL in the Linux kernel.
It appears that either the Linux kernel driver, the proftpd server software running on the embedded system, or the actual hardware itself (KSZ8851SNL)
was somehow corrupting the binary. The binary runs well on the embedded system.
Here is the output of strace on the testz binary transferred to the embedded Linux system over the Ethernet serial link:
Bad binary tests:
# strace ./testz /dev/null
execve("./testz", ["./testz", "/dev/null"], [/* 17 vars */]) = 0
mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|0x4000000, -1, 0) = 0x40089000
--- SIGSEGV (Segmentation fault) # 0 (0) ---
+++ killed by SIGSEGV +++
Segmentation fault
# strace ./testz /dev/ttyS0
execve("./testz", ["./testz", "/dev/ttyS0"], [/* 17 vars */]) = 0
mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|0x4000000, -1, 0) = 0x400ca000
--- SIGSEGV (Segmentation fault) # 0 (0) ---
+++ killed by SIGSEGV +++
Segmentation fault
#
Here is the output of strace on the testz binary transferred on SD card to the embedded Linux system:
Good binary tests:
# strace ./testz /dev/null
execve("./testz", ["./testz", "/dev/null"], [/* 17 vars */]) = 0
mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|0x4000000, -1, 0) = 0x40058000
open("/lib/libc.so.0", O_RDONLY) = 3
fstat(3, {st_mode=S_IFREG|0755, st_size=298016, ...}) = 0
mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|0x4000000, -1, 0) = 0x400b8000
read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0(\0\1\0\0\0\240\230\0\0004\0\0\0"..., 4096) = 4096
mmap2(NULL, 348160, PROT_NONE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x40147000
mmap2(0x40147000, 290576, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_FIXED, 3, 0) = 0x40147000
mmap2(0x40196000, 4832, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED, 3, 0x47) = 0x40196000
mmap2(0x40198000, 14160, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x40198000
close(3) = 0
munmap(0x400b8000, 4096) = 0
stat("/lib/ld-uClibc.so.0", {st_mode=S_IFREG|0755, st_size=25296, ...}) = 0
mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|0x4000000, -1, 0) = 0x400c4000
set_tls(0x400c4470, 0x400c4470, 0x4007b088, 0x400c4b18, 0x40) = 0
mprotect(0x40196000, 4096, PROT_READ) = 0
mprotect(0x4007a000, 4096, PROT_READ) = 0
ioctl(0, SNDCTL_TMR_TIMEBASE or TCGETS, {B115200 opost isig icanon echo ...}) = 0
ioctl(1, SNDCTL_TMR_TIMEBASE or TCGETS, {B115200 opost isig icanon echo ...}) = 0
open("/dev/null", O_RDWR|O_NOCTTY|O_NONBLOCK) = 3
write(3, "1\n", 2) = 2
write(3, "12\n", 3) = 3
write(3, "123\n", 4) = 4
write(3, "1234\n", 5) = 5
write(3, "12345\n", 6) = 6
write(3, "1\r\n", 3) = 3
write(3, "12\r\n", 4) = 4
write(3, "123\r\n", 5) = 5
write(3, "1234\r\n", 6) = 6
close(3) = 0
exit_group(0) = ?
# strace ./testz /dev/ttyS0
execve("./testz", ["./testz", "/dev/ttyS0"], [/* 17 vars */]) = 0
mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|0x4000000, -1, 0) = 0x400ed000
open("/lib/libc.so.0", O_RDONLY) = 3
fstat(3, {st_mode=S_IFREG|0755, st_size=298016, ...}) = 0
mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|0x4000000, -1, 0) = 0x40176000
read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0(\0\1\0\0\0\240\230\0\0004\0\0\0"..., 4096) = 4096
mmap2(NULL, 348160, PROT_NONE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x40238000
mmap2(0x40238000, 290576, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_FIXED, 3, 0) = 0x40238000
mmap2(0x40287000, 4832, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED, 3, 0x47) = 0x40287000
mmap2(0x40289000, 14160, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x40289000
close(3) = 0
munmap(0x40176000, 4096) = 0
stat("/lib/ld-uClibc.so.0", {st_mode=S_IFREG|0755, st_size=25296, ...}) = 0
mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|0x4000000, -1, 0) = 0x400d1000
set_tls(0x400d1470, 0x400d1470, 0x40084088, 0x400d1b18, 0x40) = 0
mprotect(0x40287000, 4096, PROT_READ) = 0
mprotect(0x40083000, 4096, PROT_READ) = 0
ioctl(0, SNDCTL_TMR_TIMEBASE or TCGETS, {B115200 opost isig icanon echo ...}) = 0
ioctl(1, SNDCTL_TMR_TIMEBASE or TCGETS, {B115200 opost isig icanon echo ...}) = 0
open("/dev/ttyS0", O_RDWR|O_NOCTTY|O_NONBLOCK) = 3
write(3, "1\n", 21
) = 2
write(3, "12\n", 312
) = 3
write(3, "123\n", 4123
) = 4
write(3, "1234\n", 51234
) = 5
write(3, "12345\n", 612345
) = 6
write(3, "1\r\n", 31
) = 3
write(3, "12\r\n", 412
) = 4
write(3, "123\r\n", 5123
) = 5
write(3, "1234\r\n", 61234
) = 6
close(3) = 0
exit_group(0) = ?
EDIT: Read on for gory details, but the quick answer is, your FTP client is corrupting your program. This is an intentional feature of FTP, which can be turned off by typing binary at the FTP prompt before get whatever or put whatever. If you're using a graphical FTP client it should have a checkbox somewhere with the same effect. Or switch to scp, which does not have this inconvenient feature.
First off, there is no difference in the generated assembly code
between (one of the) working object files and the broken object file.
$ objdump -dr dc-good.o > dc-good.s
$ objdump -dr dc-bad.o > dc-bad.s
$ diff -u dc-good.s dc-bad.s
--- dc-good.s 2012-01-21 08:20:05.318518596 -0800
+++ dc-bad.s 2012-01-21 08:20:10.954566852 -0800
## -1,5 +1,5 ##
-dc-good.o: file format elf32-littlearm
+dc-bad.o: file format elf32-littlearm
Disassembly of section .text:
In fact, there are only two bytes that differ between the good and
bad object files. (You misunderstood what I was asking for with
"test\r\n" versus "testX\n": I wanted the two strings to be the
same length, so that everything would have the same offset in the
object files. Fortunately, your compiler padded the shorter string to
the same length as the longer string, so everything has the same
offset anyway.)
$ hd dc-good.o > dc-good.x
$ hd dc-bad.o > dc-bad.x
$ diff -u1 dc-good.x dc-bad.x
--- dc-good.x 2012-01-21 08:17:28.713174977 -0800
+++ dc-bad.x 2012-01-21 08:17:39.129264489 -0800
## -154,3 +154,3 ##
00000990 53 74 61 72 74 69 6e 67 20 70 72 6f 67 72 61 6d |Starting program|
-000009a0 00 00 00 00 74 65 73 74 58 0a 00 00 2f 64 65 76 |....testX.../dev|
+000009a0 00 00 00 00 74 65 73 74 58 0d 0a 00 2f 64 65 76 |....testX.../dev|
000009b0 2f 74 74 79 53 30 00 00 66 64 20 3d 20 25 75 0a |/ttyS0..fd = %u.|
## -223,3 +223,3 ##
00000de0 61 72 69 65 73 2f 64 61 74 61 63 6f 6c 6c 65 63 |aries/datacollec|
-00000df0 74 6f 72 2d 62 61 64 2d 62 69 6e 61 72 79 2d 32 |tor-bad-binary-2|
+00000df0 74 6f 72 2d 62 61 64 2d 62 69 6e 61 72 79 2d 31 |tor-bad-binary-1|
00000e00 00 46 49 4c 45 00 5f 5f 73 74 61 74 65 00 5f 5f |.FILE.__state.__|
The first difference is the difference that should be there: 74 65 73
74 58 0a 00 00 is the correct encoding of "test\n" (with one byte
of padding), 74 65 73 74 58 0d 0a 00 is the correct encoding of
"test\r\n". The other difference appears to be debugging
information: the name of the directory in which you compiled the
programs. This is harmless.
The object files are as they should be, so at this point we can rule
out a bug in the compiler or the assembler. Now let's look at the
executables.
$ hd dc-good > dc-good.xe
$ hd dc-bad > dc-bad.xe
$ diff -u1 dc-good.xe dc-bad.xe
--- dc-good.xe 2012-01-21 08:31:33.456437417 -0800
+++ dc-bad.xe 2012-01-21 08:31:38.388480238 -0800
## -120,3 +120,3 ##
00000770 f0 af 1b e9 53 74 61 72 74 69 6e 67 20 70 72 6f |....Starting pro|
-00000780 67 72 61 6d 00 00 00 00 74 65 73 74 58 0a 00 00 |gram....testX...|
+00000780 67 72 61 6d 00 00 00 00 74 65 73 74 58 0d 0a 00 |gram....testX...|
00000790 2f 64 65 76 2f 74 74 79 53 30 00 00 66 64 20 3d |/dev/ttyS0..fd =|
## -373,3 +373,3 ##
00001750 63 6f 6c 6c 65 63 74 6f 72 2d 62 61 64 2d 62 69 |collector-bad-bi|
-00001760 6e 61 72 79 2d 32 00 46 49 4c 45 00 5f 5f 73 74 |nary-2.FILE.__st|
+00001760 6e 61 72 79 2d 31 00 46 49 4c 45 00 5f 5f 73 74 |nary-1.FILE.__st|
00001770 61 74 65 00 5f 5f 67 63 73 00 73 74 64 6f 75 74 |ate.__gcs.stdout|
Same two differences, different offsets within the executable. This
is also as it should be. We can rule out a bug in the linker as well
(if it was screwing up the address of the string, it would have to be
screwing it up the same way in both executables and they both ought to
crash).
At this point I think we are looking at a bug in your C library or
kernel. To pin it down further, I would like you to try this test
script. Run it as sh testz.sh on the ARM board, and send us the
complete output.
#! /bin/sh
set -e
cat >testz.c <<\EOF
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#define W(f, s) write(f, s, sizeof s - 1)
int
main(int ac, char **av)
{
int f;
if (ac != 2) return 2;
f = open(av[1], O_RDWR|O_NOCTTY|O_NONBLOCK);
if (f == -1) return 1;
W(f, "1\n");
W(f, "12\n");
W(f, "123\n");
W(f, "1234\n");
W(f, "12345\n");
W(f, "1\r\n");
W(f, "12\r\n");
W(f, "123\r\n");
W(f, "1234\r\n");
close(f);
return 0;
}
EOF
arm-linux-gcc -Wall -g testz.c -o testz
set +e
strace ./testz /dev/null
echo ----
strace ./testz /dev/ttyS0
echo ----
exit 0
I've looked at the damaged binary you provided and now I know what's wrong.
$ ls -l testz*
-rwxr-x--- 1 zack zack 7528 Dec 31 1979 testz-bad
-rwxr-x--- 1 zack zack 7532 Jan 21 16:35 testz-good
Ignore the odd datestamp; see how the -bad version is four bytes smaller than the -good version? There were exactly four \r characters in the source code. Let's have a look at the differences in the hex dumps. I've pulled out the interesting bit of the diff and shuffled it around a little to make it easier to see what's going on.
00000620 00 00 00 00 31 32 33 34 0a 00 00 00 31 32 33 34 |....1234....1234|
-00000630 35 0a 00 00 31 0d 0a 00 31 32 0d 0a 00 00 00 00 |5...1...12......|
+00000630 35 0a 00 00 31 0a 00 31 32 0a 00 00 00 00 31 32 |5...1..12.....12|
-00000640 31 32 33 0d 0a 00 00 00 31 32 33 34 0d 0a 00 00 |123.....1234....|
+00000640 33 0a 00 00 00 31 32 33 34 0a 00 00 00 00 00 00 |3....1234.......|
-00000650 00 00 00 00 68 84 00 00 1c 84 00 00 00 00 00 00 |....h...........|
+00000650 68 84 00 00 1c 84 00 00 00 00 00 00 01 00 00 00 |h...............|
The file transfer is replacing 0d 0a (that is, \r\n) sequences with 0a (just \n). This causes everything after this point in the file to be displaced four bytes from where it's supposed to be. The code is before this point, and so are all the ELF headers that the kernel looks at, which is why you don't get
execve("./testz-bad", ["./testz-bad", "/dev/null"], [/* 36 vars */]) = -1 ENOEXEC (Exec format error)
from the test script; instead, you get a segfault inside the dynamic loader, because the DYNAMIC segment (which tells the dynamic loader what to do) is after the displacement starts.
$ readelf -d testz-bad 2> /dev/null
Dynamic section at offset 0x660 contains 13 entries:
Tag Type Name/Value
0x00000035 (<unknown>: 35) 0xc
0x0000832c (<unknown>: 832c) 0xd
0x00008604 (<unknown>: 8604) 0x19
0x00010654 (<unknown>: 10654) 0x1b
0x00000004 (HASH) 0x1a
0x00010658 (<unknown>: 10658) 0x1c
0x00000004 (HASH) 0x4
0x00008108 (<unknown>: 8108) 0x5
0x0000825c (<unknown>: 825c) 0x6
0x0000815c (<unknown>: 815c) 0xa
0x00000098 (<unknown>: 98) 0xb
0x00000010 (SYMBOLIC) 0x15
0x00000000 (NULL) 0x3
Contrast:
$ readelf -d testz-good
Dynamic section at offset 0x660 contains 18 entries:
Tag Type Name/Value
0x00000001 (NEEDED) Shared library: [libc.so.0]
0x0000000c (INIT) 0x832c
0x0000000d (FINI) 0x8604
0x00000019 (INIT_ARRAY) 0x10654
0x0000001b (INIT_ARRAYSZ) 4 (bytes)
0x0000001a (FINI_ARRAY) 0x10658
0x0000001c (FINI_ARRAYSZ) 4 (bytes)
0x00000004 (HASH) 0x8108
0x00000005 (STRTAB) 0x825c
0x00000006 (SYMTAB) 0x815c
0x0000000a (STRSZ) 152 (bytes)
0x0000000b (SYMENT) 16 (bytes)
0x00000015 (DEBUG) 0x0
0x00000003 (PLTGOT) 0x10718
0x00000002 (PLTRELSZ) 56 (bytes)
0x00000014 (PLTREL) REL
0x00000017 (JMPREL) 0x82f4
0x00000000 (NULL) 0x0
The debugging information is also after the displacement, which is why gdb didn't like the program.
So why this very particular corruption? It's not a bug in anything; it's an intentional feature of your FTP client, which defaults to transferring files in "text mode", which means (among other things) that it converts DOS-style line endings (\r\n) to Unix-style (\n). Because that would be what you wanted if this were 1991 and you were transferring text files off your IBM PC to your institutional file server. It is basically never what is wanted nowadays, even if you are moving text files around. Fortunately, you can turn it off: just type binary at the FTP prompt before the file transfer commands. *Un*fortunately, as far as I know there is no way to make that stick; you have to do that every time. I recommend switching to scp, which always transfers files verbatim and is also easier to operate from build automation.
First things first - the fact that you only see the seg fault is NOT indicative that the program failed to run at all. What happens is that the output from the printf calls is line buffered, and when the program seg faults, it's never written out.
If you add
fflush(stdout);
after every printf, you'll see your output prior to the segfault.
Now, in your original program, what's the point of the fcntl(fd, F_SETFL, 0); call? What are you trying to achieve with it? Are you trying to turn off non-blocking mode? What if you don't make that call?
As to your second test, I see that you are using perror, but again the lack of error messages doesn't tell you that the program isn't running - it just tells you that you didn't get any error messages, and you still aren't flushing stdout, so you'll never see the printf from run_experiment.
I also see that in your second test you're doing an fdopen with read mode, then trying to write to that FILE pointer. While that certainly shouldn't crash, it also certainly shouldn't work.
Now, outside of your program, are you sure the serial port works OK? Try doing 'cat > /dev/ttyS0' and see what happens, just to be sure it's not something wonky with the hardware.

Why doesn't ptrace SINGLESTEP work properly?

I am trying to trace a little program using ptrace API. I figured out that every time the tracer is run, it produces bad results. This is the disassembly of short program that I want to trace:
$ objdump -d -M intel inc_reg16
inc_reg16: file format elf32-i386
Disassembly of section .text:
08048060 <.text>:
8048060: b8 00 00 00 00 mov eax,0x0
8048065: 66 40 inc ax
8048067: 75 fc jne 0x8048065
8048069: 89 c3 mov ebx,eax
804806b: b8 01 00 00 00 mov eax,0x1
8048070: cd 80 int 0x80
and here is code of the tracer itself:
// ezptrace.c
#include <sys/user.h>
#include <sys/ptrace.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
int main() {
pid_t child;
child = fork();
if (child == 0) {
ptrace(PTRACE_TRACEME, 0, NULL, NULL);
execv("inc_reg16", NULL);
}
else {
int status;
wait(&status);
struct user_regs_struct regs;
while (1) {
ptrace(PTRACE_GETREGS, child, NULL, &regs);
printf("eip: %x\n", (unsigned int) regs.eip);
ptrace(PTRACE_SINGLESTEP, child, NULL, NULL);
waitpid(child, &status, 0);
if(WIFEXITED(status)) break;
}
printf("end\n");
}
return 0;
}
The tracer's job is to single step the inc_reg16 program and log address of each encountered processor instruction. When I run and check how many times the instruction 'inc ax' has been encountered, it occurs that the numbers are different each time the tracer is run:
$ gcc ezptrace.c -Wall -o ezptrace
$ ./ezptrace > inc_reg16.log
$ grep '8048065' inc_reg16.log | wc -l
65498
the second check:
$ ./ezptrace > inc_reg16.log
$ grep '8048065' inc_reg16.log | wc -l
65494
The problem is that above results should be both 65536, as the instruction 'inc ax' is executed exactly 65536 times. Now the question is: is there a mistake in my code or it's a matter of some bug in ptrace? Your help is greatly appreciated.
I tried the same program under both virtualbox and vmware, it seems that only vmware has the correct result, whereas virtualbox has the same problem as you. I used the virtualbox 4.2.1.
eip is the address to the "current instruction" in user space. You need a ptrace(...PEEKDATA, ...), i.e. following ptrace(...GETREGS, ...), to obtain the actual instruction. Also keep in mind that, with ptrace(...PEEKDATA, ...) you always obtain a machine word, actual opcodes usually only occupy the low 16/32 bits of it.

Resources