Bus error working with GPIOs


#1

Hi!

I’m working on my program to interface with an I2C device. I need to read a device’s pin, so I use the GPIOs in the same way is explained in the LinuxUserGuide_Dragonboard, but when I run the program, “Bus error” is displayed.

Checking my code, I use the GPIOs in the same way as they are used in the document. So, I tried to run the code TogglyGPIO (page 22 of the document) and the same error is showed. Days ago, when I executed the same code this error wasn’t showed. I copied the code. Also I have checked it.

Anyone has the same problem or know the cause? As I can read in Internet, Bus error happens when processor can’t access to the memory address requested, but in the code i don’t see any that can cause this.

Here is a screen shot:


#2

Actually, I meet the same issue on my side.

I’m pretty sure this is due to memory corruption.
There is an obvious buffer overflow in Write_GPIO and Read_GPIO.
If you look inside these functions you can see:
char buf[MAX_BUF];
sprintf(buf, “/sys/class/gpio/gpio%d/direction”, gpio);

However, MAX_BUF is 10, so the memory is corrupted, leading to instability.

I suggest you to fix this by defining MAX_BUF to 100.


#3

I would suggest you look at using the mraa library for accessing GPIO especially if you are looking are interfacing with I2C devices.

More details at:
https://www.96boards.org/documentation/ConsumerEdition/guides/mraa.md

and:


#4

… valgrind is available on arm if you wanted to try and prove it :wink: (however the bug is so crass I think we can be totally sure it needs fixing whether valgrind picks it up or not).


#5

Hi @loic, I noticed that the first time I saw the code, but I supposed that the kernel would manage this issue (reserving the memory needed to allocate the string or something like that)
With a MAX_BUF definition of 100 it works fine! Thank you.

Thank you @barryb for your response, I will take a look!


#6

C is powerful but extremely permissive, you can do what you want with memory and be able to build.
Kernel does not complain as long as you play with your own process memory.

Here process writes out of the buffer memory but still in the process stack memory, probably overwriting
a return address. This is why the error comes later when process tries to access or execute the previously corrupted address. Process is then killed by the kernel via a signal (Bus error, segfault, etc…).

Yes that would be an instinctive practice :slight_smile:
In my defence valgrind is not very good for bound checking on stack arrays.
Best solution is static code analysis or compiling with a stack guard.

Compiling with -fstack-protector reports the error:
Writing GPIO_36: value=1
*** stack smashing detected ***: /home/root/toggly terminated

May I also suggest to also have a look at the 96BoardsGPIO lib .

Documentation issue has been reported.