Uncategorized

Getting SIGSEGV fault when doing integer operations when a C lib is used in Python


I’m currently trying to run some C code in Python 3.10.12 to be able to test some algorithms/visual effects without the need for real hardware. To do this I made a separate compilation that compiles the relevant code to a library which can then be imported into python using ctypes. After a lot of fighting with ctypes I got my lib integrated with the Python code.

I have now ran into a super weird issue that I’m getting a SIGSEGV on one of the effects.

So I did the reasonable thing and set up a GDB session to debug the code, and GDB indicates that the SIGSEGV is happening with the following message:

Thread 1 "python" received signal SIGSEGV, Segmentation fault.
0x00007ffff7192870 in colour_random_offset_hue_gen_frame (buffer=0x7ffff719ad60 <led_buffer> "") at /home/jaxc/work/LED_glasses/effects/colours/random_hue.c:21
21          random = (random * 196314165) + 907633515;

The buffer originates from led_buffer which is defined as follows:

uint8_t led_buffer[FRAME_SIZE];

This seems super weird to be as this line does not affect the buffer (until a few lines later when I assign the value). The full function looks like this:

void colour_random_offset_hue_gen_frame(uint8_t buffer[FRAME_SIZE]) {

    uint16_t current_led = 0;
    for (uint16_t i = 0; i < FRAME_SIZE; i += 3) {
        struct colours pixel_hue;
        uint32_t random_hue = random % 1024;
        random = (random * 196314165) + 907633515;
        get_colour(&pixel_hue, random_hue, 0xff);

        buffer[i] = pixel_hue.green; /* Green value */
        buffer[i+1] = pixel_hue.red; /* Red value */
        buffer[i+2] = pixel_hue.blue; /* Blue value */

        current_led++;
    }
}

Compiling the code with -O0 flags gives the following assembly for the troubled row:

21          random = (random * 196314165) + 907633515;
   0x00007ffff7194a6f <+43>:    mov    0x5472(%rip),%rax        # 0x7ffff7199ee8
   0x00007ffff7194a76 <+50>:    mov    (%rax),%eax
   0x00007ffff7194a78 <+52>:    imul   $0xbb38435,%eax,%eax
   0x00007ffff7194a7e <+58>:    lea    0x3619636b(%rax),%edx
   0x00007ffff7194a84 <+64>:    mov    0x545d(%rip),%rax        # 0x7ffff7199ee8
=> 0x00007ffff7194a8b <+71>:    mov    %edx,(%rax)

And the fault happens at the last row (mov %edx,(%rax)). Even commenting out the rest of the code of the function results in the same assembly for that line of code.

I tried to isolate the issue by making a main that just has this code, but it works without segfaults, so I suspect the python integration somehow does something. I also tested this online:
https://onlinegdb.com/D0j3azZ98

I have also tested the code quickly using a c main function, calling the same function as I do in Python without getting any segmentation fault.

Thanks in advance!



Source link

Leave a Reply

Your email address will not be published. Required fields are marked *