Skip to content

[BUG] Bug in stpncpy implementation: Wrong pointer returned #2240

Description

@Menkalian

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

#include <string.h>
#include <stdio.h>

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 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

  • I have checked and the NDK I'm using is currently supported

Affected versions

r29

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions