linuxgdblinux-device-driver

how to prevent some values from being optimized out in linux kernel debugging?


This is a code in linux (5.4.21)
When I use a virtual machine and connect gdb to the linux process, I can use break points and follow code. For example, I set breakpoint on a function arm_smmu_device_probe. When I follow with 'next' command, I see some values, for example, 'smmu' or 'dev' below are shown to have been optimized out. How can I make them not optimized out so that I can see them in gdb?

static int arm_smmu_device_probe(struct platform_device *pdev)
{
    int irq, ret;
    struct resource *res;
    resource_size_t ioaddr;
    struct arm_smmu_device *smmu;
    struct device *dev = &pdev->dev;
    bool bypass;

    smmu = devm_kzalloc(dev, sizeof(*smmu), GFP_KERNEL);
    if (!smmu) {
        dev_err(dev, "failed to allocate arm_smmu_device\n");
        return -ENOMEM;
    }
    smmu->dev = dev;

    if (dev->of_node) {
        ret = arm_smmu_device_dt_probe(pdev, smmu);
    } else {
        ret = arm_smmu_device_acpi_probe(pdev, smmu);
        if (ret == -ENODEV)
            return ret;
    }

I tried chaning -O2 to -Og in the top Makefile but the kernel build fails then.


Solution

  • Recently I found how to do this. (from Is there a way to tell GCC not to optimise a particular piece of code?, flolo's answer)
    If you want a function aaa(...) not to be optimzed, you can do it like this.

    #pragma GCC push_options
    #pragma GCC optimize ("O0")
    aaa ( ... ) 
    {
      function body
    }
    #pragma GCC pop_options
    

    In some cases, this putting #pragma causes some discrepancy between the #include header file and the function source. So in this case (not often) you need to add this #praga around the corresponding #include statement. If linux/bbb.h causes this kind of problem, do this.

    #pragma GCC push_options
    #pragma GCC optimize ("O0")
    #include <linux/bbb.h>
    #pragma GCC pop_options
    

    This works sure and I'm enjoying(?) debug/analysis this way.