代码之家  ›  专栏  ›  技术社区  ›  Felipe

在尝试加载内核模块时,如何修复C++中的MalCube()错误?

  •  0
  • Felipe  · 技术社区  · 6 年前

    我明白了 malloc(): memory corruption 当我在C++中执行这个代码时。基本上,我打开一个内核文件,使用malloc struct stat st . 我想这是问题的根源。

    代码加载一个内核模块(I2C),它实际上正在加载。但我想我不是在用 malloc() 应该使用的。谢谢。

    #define _GNU_SOURCE
    #include <fcntl.h>
    #include <stdio.h>
    #include <sys/stat.h>
    #include <sys/syscall.h>
    #include <sys/types.h>
    #include <unistd.h>
    #include <stdlib.h>
    
    #include <gtest/gtest.h>
    #include <gmock/gmock.h>
    
    #define init_module(mod, len, opts) syscall(__NR_init_module, mod, len, opts)
    #define delete_module(name, flags) syscall(__NR_delete_module, name, flags)
    class I2CKernelModule : public testing::Test {
    public:
        I2CKernelModule() {
        }
    };
    TEST_F(I2CKernelModule, TestAddAndRemoveKernelModule) {
        char *params;
        int fd;
        size_t image_size;
        struct stat st;
        void *image;
    
        // command: sudo insmod /root/i2c-tests/i2c-stub.ko chip_addr=0x20
        params = "chip_addr=0x20";
        fd = open("/root/i2c-tests/i2c-stub.ko", O_RDONLY);
        fstat(fd, &st);
        image_size = st.st_size;
        image = malloc(image_size);
        read(fd, image, image_size);
        close(fd);
        if (init_module(image, image_size, params) != 0) {
            perror("init_module");
            GTEST_FAIL();
        }
        free(image);
        GTEST_SUCCESS_("Kernel module loaded.");
    
        /*
        // sudo rmmod i2c_stub
        if (delete_module("i2c_stub", O_NONBLOCK) != 0) {
            perror("delete_module");
            GTEST_FAIL();
        }
        GTEST_SUCCESS_("Kernel module unloaded.");
        */
    }
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Zan Lynx    6 年前

    检查所有函数的返回值是否有错误。如果文件未打开、stat失败或malloc失败,则列出的代码将失败。检查read返回的字节数也是一个好主意。