Last active
December 16, 2015 23:39
-
-
Save kosaki/5515798 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
% make | |
cc -D_FORTIFY_SOURCE=2 -Wall -g -O2 memcpy_test.c memcpy_chk.c -o memcpy_test | |
In function ‘my_memcpy’, | |
inlined from ‘main’ at memcpy_test.c:29: | |
memcpy_test.c:17: 警告: call to ‘my_memcpy_warn’ declared with attribute warning: my warning | |
% ./memcpy_test | |
my buffer overflow detection | |
[1] 27873 abort (core dumped) ./memcpy_test | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stddef.h> | |
#include <string.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
void* my_memcpy_chk (void *dest, const void *src, size_t len, size_t destlen) | |
{ | |
size_t i; | |
const char *s = src; | |
char *d = dest; | |
if (len > destlen) { | |
fprintf(stderr, "my buffer overflow detection\n"); | |
abort(); | |
} | |
for (i=0; i<len; i++) | |
d[i] = s[i]; | |
return dest; | |
} | |
char* my_memcpy_warn () __attribute__ ((alias("my_memcpy_chk"))); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <string.h> | |
#include <stdio.h> | |
char* my_memcpy_chk (char *dest, const char *src, size_t len, size_t destlen); | |
char* my_memcpy_warn (char *dest, const char *src, size_t len, size_t destlen) | |
__attribute__((__warning__ ("my warning"))); | |
static char* my_memcpy(char* dst, const char* src, size_t len) __attribute__((always_inline)); | |
static char* my_memcpy(char* dst, const char* src, size_t len) | |
{ | |
size_t d = __builtin_object_size(dst, 0); | |
if (d != (size_t) -1) { | |
if (__builtin_constant_p(len) && len > d) | |
return my_memcpy_warn(dst, src, len, d); | |
else | |
return my_memcpy_chk(dst, src, len, d); | |
} else | |
return memcpy (dst, src, len); | |
} | |
int main(void) | |
{ | |
const char *str = "12345"; | |
char buf[5]; | |
my_memcpy(buf, str, strlen(str)+1); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment