简体   繁体   English

capset失败,指向结构的指针

[英]capset fails with pointer to struct

I have two code samples: 我有两个代码示例:
First, runs correctly: 首先,正确运行:

#include <sys/capability.h>
#include <unistd.h>
#include <cstdio>

int main()
{
    __user_cap_header_struct *hdr = new __user_cap_header_struct;
    __user_cap_data_struct *data = new __user_cap_data_struct;
    hdr->pid = getpid();
    hdr->version = _LINUX_CAPABILITY_VERSION;
    data->effective &= ~CAP_TO_MASK(CAP_IPC_LOCK);
    data->permitted &= ~CAP_TO_MASK(CAP_IPC_LOCK);
    data->inheritable = 0;
    if (capset(hdr, data) < 0)
        printf("capset failed: %m");

    return 0
}

Second, fail: Operation not permitted : 二, fail: Operation not permitted

#include <sys/capability.h>
#include <unistd.h>
#include <cstdio>

int main()
{
    struct __user_cap_header_struct hdr;
    hdr.pid = getpid();
    hdr.version = _LINUX_CAPABILITY_VERSION;
    struct __user_cap_data_struct data;   
    data.effective &= ~CAP_TO_MASK(CAP_IPC_LOCK);    
    data.permitted &= ~CAP_TO_MASK(CAP_IPC_LOCK);   
    if(capset(&hdr, &data))   
        printf("capset failed: %m");   

    return 0;
}

I think both code samples are the same. 我认为两个代码示例是相同的。
When I run the first one it executes correctly (uses pointer to struct). 当我运行第一个时,它可以正确执行(使用指向struct的指针)。
But the second fails (uses instance of struct). 但是第二个失败(使用struct实例)。
I don't know why. 我不知道为什么 Can you help me? 你能帮助我吗?

Most likely because how the structures are initialized. 最有可能是因为如何初始化结构。 When declaring a local variable, its value is indeterminate , using that value then leads to undefined behavior . 声明局部变量时,其值是不确定的 ,使用该值会导致未定义的行为

The same goes for local structure variables. 局部结构变量也是如此。 The member field values are simply undefined, so when you do eg data.effective &= ~CAP_TO_MASK(CAP_IPC_LOCK); 成员字段的值只是未定义的,所以当您执行例如data.effective &= ~CAP_TO_MASK(CAP_IPC_LOCK); you use an indeterminate (and seemingly random) value for the operation. 您对操作使用不确定的(看似随机的)值。

You need to initialize the structure to a well know value before using it. 您需要在使用结构之前将其初始化为众所周知的值。 Like 喜欢

struct __user_cap_header_struct hdr = { 0 };

The above will set all fields in the structure to zero. 上面的代码将结构中的所有字段设置为零。

When you allocate with new (which is C++ and not C!) then for structures (or classes) without default constructors all member fields are default constructed , and for integer fields this means they are zeroed. 当使用new (是C ++而不是C!)进行分配时,对于没有默认构造函数的结构(或类),所有成员字段都是默认构造的 ,对于整数字段,这意味着它们将被清零。 If you allocated the structures in the first example using malloc (as that's the C way of allocating memory) then you would have the same result as the second example, as then the allocated memory would not be initialized at all. 如果您在第一个示例中使用malloc分配了结构(因为这是分配内存的C方法),那么您将获得与第二个示例相同的结果,因为分配的内存根本不会初始化。

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

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