简体   繁体   English

C,写系统调用,写int

[英]C, write system call, writing int

I found this source in Jon Erickson's book, Hacking: The Art of Exploitation , 我在乔恩·埃里克森(Jon Erickson)的著作《 黑客:剥削的艺术》中找到了这个资源,

userid = getuid(); // get the real user ID
// Writing data
if(write(fd, &userid, 4) == -1)  // write user ID before note data
    fatal("in main() while writing userid to file");
write(fd, "\n", 1); // terminate line

I tried to compile this code, and found that on the file I write, userid (which is what I write in the code above) is not right; 我尝试编译此代码,发现在我写的文件上,userid(这是我在上面的代码中写的)不正确; they just wrote strange character (I think is not important to write it here). 他们只是写了奇怪的人物(我想在这里写它并不重要)。 So the problem is I am trying to pass an int to a function which required char * , because of that the result on file I want to write is false. 所以问题是我试图将int传递给需要char *的函数,因为我要写入的文件结果为false。

So this is a bug, right? 这是一个错误,对吗?

The write() function expects a void * for its buffer; write()函数的缓冲区期望为void * it writes arbitrary binary data. 它写入任意二进制数据。 If you need conversion to string, use printf() . 如果需要转换为字符串,请使用printf()

You don't show the declaration of userid , but the write() line should be written as: 您没有显示userid的声明,但是write()行应写为:

if (write(fd, &userid, sizeof(userid)) != sizeof(userid))

This will detect short writes (unlikely to be a problem for an integer type) and other problems, and works correctly regardless of the type of userid . 这将检测短写(不太可能是整数类型的问题)和其他问题,并且无论userid的类型如何都可以正常工作。 The original version of the line is arguably buggy, therefore. 因此,该系列的原始版本可以说是越野车。 Otherwise, the bug seems to be in your expectations rather than the code per se. 否则,该错误似乎在您的期望中,而不是代码本身。

No, it's not a bug, rather it's a misunderstanding on your part. 不,这不是错误,而是您的误解。 The write call will just write what's in memory, the binary representation. write调用将只写内存中的二进制表示形式。 You would need something like fprintf to get a readable version. 您需要像fprintf这样的东西才能获得可读的版本。

For example, the binary representation of 7 may be the four bytes 0, 0, 0 and 7, which are unlikely to look like the textual representation, a single byte 55 (assuming ASCII). 例如,7的二进制表示形式可以是四个字节0​​、0、0和7,它们看起来不太像文本表示形式,即单个字节55(假定ASCII)。

It's also a bad idea to hardcode type lengths like 4 for an integer since that's not portable. 硬编码类型长度为4的整数也是一个坏主意,因为它不可移植。 Better would be to use something like sizeof(userid) . 最好使用诸如sizeof(userid)类的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM