Skip to content

Commit

Permalink
Add tests for stcncpy
Browse files Browse the repository at this point in the history
  • Loading branch information
jvoisin committed Jun 22, 2023
1 parent af7480d commit 532f4bf
Show file tree
Hide file tree
Showing 5 changed files with 55 additions and 1 deletion.
7 changes: 6 additions & 1 deletion include/string.h
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,13 @@ __access(write_only, 1)
__access(read_only, 2, 3)
_FORTIFY_FN(stpncpy) char *stpncpy(char *__d, const char *__s, size_t __n)
{
size_t __b = __bos(__d, 0);
/* trap if pointers are overlapping but not if dst == src.
* gcc seems to like to generate code that relies on dst == src */
if ((__d < __s && __d + __n > __s) ||
(__s < __d && __s + __n > __d))
__builtin_trap();

size_t __b = __bos(__d, 0);
if (__n > __b && strlen(__s) + 1 > __b)
__builtin_trap();
return __orig_stpncpy(__d, __s, __n);
Expand Down
3 changes: 3 additions & 0 deletions tests/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ TARGETS=test_memcpy_static_write \
test_strncpy_overwrite_over \
test_strncpy_overwrite_under \
test_strncpy_static_write \
test_stpncpy_overwrite_over \
test_stpncpy_overwrite_under \
test_stpncpy_static_write \
test_getcwd \

.SILENT:
Expand Down
15 changes: 15 additions & 0 deletions tests/test_stpncpy_overwrite_over.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#include "common.h"

#include <string.h>

int main(int argc, char** argv) {
char buffer[9] = {'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', '\0'};
puts(buffer);

CHK_FAIL_START
stpncpy(buffer+1, buffer, 5);
CHK_FAIL_END

puts(buffer);
return ret;
}
15 changes: 15 additions & 0 deletions tests/test_stpncpy_overwrite_under.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#include "common.h"

#include <string.h>

int main(int argc, char** argv) {
char buffer[9] = {'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', '\0'};
puts(buffer);

CHK_FAIL_START
stpncpy(buffer-1, buffer, 5);
CHK_FAIL_END

puts(buffer);
return ret;
}
16 changes: 16 additions & 0 deletions tests/test_stpncpy_static_write.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
#include "common.h"

#include <string.h>

int main(int argc, char** argv) {
char buffer[8] = {0};
stpncpy(buffer, "1234567", 5);
puts(buffer);

CHK_FAIL_START
stpncpy(buffer, "1234567890", 10);
CHK_FAIL_END

puts(buffer);
return ret;
}

0 comments on commit 532f4bf

Please sign in to comment.