Skip to content

Memset and Memcpy are not safe on uint8 if unaligned bytes. #2488

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
tbandtg opened this issue May 27, 2025 · 4 comments
Open

Memset and Memcpy are not safe on uint8 if unaligned bytes. #2488

tbandtg opened this issue May 27, 2025 · 4 comments

Comments

@tbandtg
Copy link

tbandtg commented May 27, 2025

I’ve encountered an issue with the current implementation of memset and memcpy in the standard library on the pico. When the SCB_CCR_UNALIGN_TRP flag is enabled to trap unaligned accesses, both functions may internally perform word-sized operations on unaligned addresses—even when operating on uint8_t arrays. This results in a UsageFault exception on CPUs that do not support unaligned accesses. While this is allowed by the C standard, it is problematic for platforms enforcing strict alignment. To ensure compatibility with systems that enable UNALIGN_TRP, these functions need to handle unaligned pointers correctly, for example, by using byte-wise operations when the pointer is not word-aligned.

example code.

SCB->CCR |= ( SCB_CCR_DIV_0_TRP_Msk | SCB_CCR_UNALIGN_TRP_Msk | SCB_CCR_BFHFNMIGN_Msk);
uint8_t buffer[10];
memset(&buffer[1], 0, 4);
memset(&buffer[2], 0, 4);
DEBUG_PRINT("%d , buffer1 %d, buffer2 %d\n", buffer, &buffer[1], &buffer[2]);
@tbandtg
Copy link
Author

tbandtg commented May 27, 2025

add_compile_options(-mno-unaligned-access)

Added to cmake did not fix the issue.

@lurch
Copy link
Contributor

lurch commented May 27, 2025

I guess this must be on RP2350? Looking at the RP2350 datasheet says that CCR.UNALIGN_TRP is RW, but the RP2040 datasheet says that CCR.UNALIGN_TRP is RO and hardwired to 1. (With the latter being one of the unfortunate examples of where the Reset column in the auto-generated register tables doesn't know what the real reset value is. See also raspberrypi/pico-feedback#241 )

@tbandtg
Copy link
Author

tbandtg commented May 27, 2025

IT is but if it is hardwired to 1 on the 2040 wouldnt this have caused alot of problems?
I found this in btstack first and then ran the above test.

@tbandtg
Copy link
Author

tbandtg commented May 27, 2025

At the end of the day memset and memcpy should be safe to do on uint8 arrays even with the trap enabled.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants