newlib-nano printf("%.*s",moo) walks off the end of string

Bug #1385829 reported by Clem Taylor on 2014-10-26
This bug affects 1 person
Affects Status Importance Assigned to Milestone
GNU Arm Embedded Toolchain
Terry Guo

Bug Description

I have always used:
      char moo[16];
      printf("%.*s", sizeof(moo), moo);

To print potentially non-terminated strings.

With the assumption that printf() will *not* attempt to read moo[16].

However, it seems that the newlib-nano implementation calls
strlen() instead of something like strnlen() and happily walks off the end of memory.

In the case that caught the bug, the string was near the end of flash and the rest of the data was 0xFF, so it walked off the end of flash until it took a hard fault. I doubt I would have caught it otherwise.

I'm using gcc-arm-none-eabi-4_8-2014q3 with nano.specs on a cortex-m0.

Zhenqiang Chen (zhenqiang-chen) wrote :

Thank you for the report. But I can not reproduce it with the following case:

#include <stdio.h>
int main ()
  char moo[16] = {'c','c','c','c',

  printf("%.*s\n", 10, moo);
  printf("%.*s\n", 16, moo);
  return 0;

arm-none-eabi-gcc -mcpu=cortex-m0 -mthumb -O2 printf.c --specs=nano.specs -specs=rdimon.specs

The output are correct.

Can you show us more detail about your case?

Terry Guo (terry.guo) wrote :

I took a closer look to nano code and found that we have code strlen(cp) where cp may not be null-terminated. So this issue is confirmed. I am working on a patch by using Newlib approach here for Nano to fix this issue.

Changed in gcc-arm-embedded:
assignee: nobody → Terry Guo (terry.guo)
status: New → Confirmed
Terry Guo (terry.guo) wrote :

Hi Clem,

Do you still have environment to reproduce this issue? The fix to this issue is just committed to Newlib. I am wondering that whether you can help us to verify the fix. If you are OK, please drop me an email <email address hidden> and I will send you the updated newlib-nano. Thanks in advance.

Changed in gcc-arm-embedded:
status: Confirmed → In Progress
milestone: none → 4.9-2014-q4-major
Terry Guo (terry.guo) on 2014-11-11
Changed in gcc-arm-embedded:
status: In Progress → Fix Committed
Terry Guo (terry.guo) on 2014-12-10
Changed in gcc-arm-embedded:
status: Fix Committed → Fix Released
To post a comment you must log in.
This report contains Public information  Edit
Everyone can see this information.

Other bug subscribers