On 04/22/2010 07:08 PM, luozhiyuan wrote:
> 于 2010-4-23 0:12, John Reiser 写道:
>>> char* p =(char*)
>>> mmap(&start,PAGE_SIZE,PROT_READ|PROT_WRITE,MAP_PRIVATE|MAP_ANONYMOUS,-1,0);
>>>
>>> *p = 1;
>> This code is bad because it does not check for failure of the system
>> call.
>>
> It's OK to just run the program,

The program succeeds "by accident".  The kernel is allowed to return MAP_FAILED
(with EINVAL) for such an mmap, and sometimes it does!  Read the manual page
that is displayed by running the shell command "man mmap":

        EINVAL We don’t like addr, length, or offset (e.g., they are too large,
               or not aligned on a page boundary).

> But it will fail to run with valgrind.
> Why?

memcheck has done you a favor by pointing out that the code is wrong.
In fact there are *TWO* bugs: the code does not check for MAP_FAILED,
and the code does not align the address with the offset.

> You can try the code.
> I trace the syscalls when use valgrind,sys_mmap2 seems to fail:
>    [[snip]]
> SYSCALL[22210,1](192) sys_mmap2 ( 0xBECDE76C, 4096, 3, 34, -1, 0 ) --> 
> [pre-fail] Failure(0x16)

Notice the "[pre-fail]".  That means that memcheck never asked the kernel
to try the mmap.  Instead, memcheck noticed that (0 != (0xfff & (addr ^ 
offset)))
which is a legitimate reason for mmap to fail with EINVAL, and therefore
memcheck returned MAP_FAILED "early".  You may argue that it doesn't matter
because of MAP_ANONYMOUS, but it is perfectly legal for memcheck to complain,
because the kernel is not required to check MAP_ANONYMOUS before checking
the address against the offset.  The code is incorrect, in two ways.
Fix both of them.

> ==22210== Invalid write of size 1
> ==22210== at 0x8048475: main (valgrind_test.cpp:13)
> ==22210== Address 0xffffffff is not stack'd, malloc'd or (recently) free'd

0xffffffff==MAP_FAILED on a 32-bit machine.

-- 

------------------------------------------------------------------------------
_______________________________________________
Valgrind-users mailing list
Valgrind-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/valgrind-users

Reply via email to