forked from mattayres/li2mod
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstrl.c
136 lines (110 loc) · 2.41 KB
/
strl.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "strl.h"
#ifdef STRL_DEBUG_BACKTRACE
#include <execinfo.h>
#endif
#define MIN(x,y) (((x) < (y)) ? (x) : (y))
#ifdef NEED_STRLCAT
size_t strlcat_s(char *dest, char *src, size_t n, int count) {
size_t fr;
size_t ret;
size_t copy;
size_t srclen;
char overflow;
srclen = strlen(src);
ret = strlen(dest) + srclen;
fr = n - (ret - srclen) - 1;
if (count < 0) {
copy = fr;
overflow = (ret >= n);
} else {
copy = MIN(count,(int)fr);
overflow = (count > (int)fr);
}
if (fr > 0)
strncat(dest, src, copy);
#ifdef STRL_DEBUG
if (overflow) {
if (count < 0)
fprintf(stdout, "strlcat: buffer overflow avoided (%zd >= %zd)\n", ret, n);
else
fprintf(stdout, "strlcat_s: buffer overflow avoided (%zd >= %zd)\n", (ret - srclen)+copy, n);
#ifdef STRL_DEBUG_BACKTRACE
{
void* array[10];
size_t size;
char **strings;
size_t i;
char s[64];
size_t sl;
sl = MIN(srclen,63);
strncpy(s, src, sl);
s[63] = '\0';
size = backtrace(array, 10);
strings = backtrace_symbols(array, size);
if (strings != NULL) {
for (i=0; i<size; i++)
fprintf(stdout, " %s\n", strings[i]);
free(strings);
}
fprintf(stdout, "Source buffer: %s%s\n", s, (ret > 63)?"...":"");
}
#endif
fflush(stdout);
}
#endif
return ret;
}
#endif
#ifdef NEED_STRLCPY
size_t strlcpy_s(char *dest, char *src, size_t n, int count) {
size_t ret;
size_t copy;
char overflow;
ret = strlen(src);
if (n == 0)
return ret;
if (count < 0) {
copy = n-1;
overflow = (ret >= n);
} else {
copy = MIN(count, (int)n-1);
overflow = (count >= (int)n);
}
strncpy(dest, src, copy);
*(dest+copy) = '\0';
#ifdef STRL_DEBUG
if (overflow) {
if (count < 0)
fprintf(stdout, "strlcpy: buffer overflow avoided (%zd >= %zd)\n", ret, n);
else
fprintf(stdout, "strlcpy_s: buffer overflow avoided (%d >= %zd)\n", count, n);
#ifdef STRL_DEBUG_BACKTRACE
{
void* array[10];
size_t size;
char **strings;
size_t i;
char s[64];
size_t sl;
sl = MIN(ret,63);
strncpy(s, src, sl);
s[63] = '\0';
size = backtrace(array, 10);
strings = backtrace_symbols(array, size);
if (strings != NULL) {
for (i=0; i<size; i++)
fprintf(stdout, " %s\n", strings[i]);
free(strings);
}
fprintf(stdout, "Source buffer: %s%s\n", s, (ret > 63)?"...":"");
}
#endif
fflush(stdout);
}
#endif
return ret;
}
#endif