android / android/ndk

[BUG] Bug in stpncpy implementation: Wrong pointer returned

Open
#2,240 3 comments 0 reactions 1 assignee Claimed by @Sharjeel-Khan View on GitHub
bug
Dominant language
No language data
Stars
2.3k
Forks
310
PR merge metrics
No merged PRs in 30d

Description

### Description

# Bug Description

When using NDK r29 stpncpy does not return the correct pointer in some cases.
The issue is present when `src` has a size known at compile time. In that case `__stpncpy_chk2` is used which always returns the `dest` pointer and not a pointer to the end of the string. This is not conform to stpncpy as it is defined in the C standard.

Note: The behavior can only be observed when BIONIC FORTIFY is used. This is the default behavior when using the NDK as part of building an application.

## Standalone C example

```c++
#include
#include

const char prefix[] = "prefix_";
const char *text = "FooBar";

int main(int argc, char **argv) {
char buffer[20];
size_t buffer_len = sizeof(buffer) - 1;
char *cp;

cp = stpncpy(buffer, prefix, buffer_len);
buffer_len -= sizeof(prefix) - 1;
cp = stpncpy(cp, text, buffer_len);

printf("Output: %s\n", buffer);
return 0;
}
```

This has to be compiled with `${ANDROID_CC} -D_FORTIFY_SOURCE=2 testcase_stpncpy.c -o testcase_stpncpy`.
The program will output `Output: FooBar`, but the correct output should be `Output: prefix_FooBar`.

Compiling the program with either gcc or clang on my host machine (x86_64, Linux in WSL) does not exhibit this issue, thus it is an issue with the NDK Toolchains.

## Example Android Application

[StpncpyExample.zip](https://github.com/user-attachments/files/29204524/StpncpyExample.zip) contains a small sample app which uses the above codesnippet to display some text. It exhibits the same behavior.

### I am using a supported NDK

- [x] I have checked and the NDK I'm using is currently supported

### Affected versions

r29

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.