ARMmbed / ARMmbed/mbed-drivers
Excessive stack usage in retarget.cpp
- Dominant language
- C++
- Stars
- 39
- Forks
- 41
- PR merge metrics
- No merged PRs in 30d
Description
Hi,
I'm seeing some weird behavior in `_open()` (retarget.cpp:166) when running the example-mbedos-blinky example on EFM32 Happy Gecko. It looks to me like the `sscanf()` call on line 209 takes up several hundred bytes of stack space when trying to allocate a file handle for stdout. I assume some of this is buffers for the string, but it still seems excessive. I have not tested this on other platforms, so if someone were able to confirm this, that would be great.
Since EFM32 Happy Gecko only has 8 kB of RAM, it would be great if the stack usage could be reduced. Internally, sscanf calls `strtoul()` for actually storing the string value into the pointer, so by doing this directly, instead of going through sscanf, stack usage was reduced significantly in my tests. I have attached a patch below.
## Testing
All testing was performed with armgcc 4.9.3 20150529 on OSX, running yotta build in release mode. I filled the stack with `0xCD`, and looked at the maximum stack usage of example-mbedos-blinky. The stack runs from the base of RAM (`0x20000000`) to `0x20000800 in these tests.
### EFM32 Happy Gecko (target efm32hg-stk-gcc)
Lowest address touched originally: `0x2000028c`
Lowest address touched with patch: `0x20000500`
### EFM32 Giant Gecko (target efm32gg-stk-gcc)
Lowest address touched originally: `0x2000250`
Lowest address touched with patch: `0x20004b8`
I.e. approximately 600 bytes of stack space is saved for both these devices.
## Patch
```
diff --git a/source/retarget.cpp b/source/retarget.cpp
index c96c9ac..40ba73d 100644
--- a/source/retarget.cpp
+++ b/source/retarget.cpp
@@ -205,10 +205,7 @@ extern "C" FILEHANDLE PREFIX(_open)(const char* name, int openmode) {
/* FILENAME: ":0x12345678" describes a FileLike* */
if (name[0] == ':') {
- void *p;
- sscanf(name, ":%p", &p);
- res = (FileHandle*)p;
-
+ res = (FileHandle*)strtoul(&name[1], NULL, 0);
/* FILENAME: "/file_system/file_name" */
} else {
FilePath path(name);
```
Contributor guide
No contributing guide indexed for this repository
Research direction
Inspect source/retarget.cpp around _open() line 166 and the sscanf call near line 209; compare the supplied strtoul-based approach. Build example-mbedos-blinky with yotta in release mode for the EFM32 targets and measure stack usage as described. Done means the stdout file-handle path works and the reported stack use is reduced.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- cpp
- Domain
- embedded-iot, performance
- Issue type
- Bug
- Difficulty
- 2/5
- Estimated time
- 1-3 hours
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 38/100