Skip to content

Commit 1ce42dc

Browse files
authored
Create test2.cpp
1 parent 6d800de commit 1ce42dc

File tree

1 file changed

+82
-0
lines changed
  • cpp/ql/test/experimental/query-tests/Security/CWE/CWE-125/semmle/tests

1 file changed

+82
-0
lines changed
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
#define NULL 0
2+
typedef unsigned int size_t;
3+
struct mbstate_t{};
4+
struct _locale_t{};
5+
int printf ( const char * format, ... );
6+
void* calloc (size_t num, size_t size);
7+
void* malloc (size_t size);
8+
9+
size_t mbstowcs(wchar_t *wcstr,const char *mbstr,size_t count);
10+
size_t _mbstowcs_l(wchar_t *wcstr,const char *mbstr,size_t count, _locale_t locale);
11+
size_t mbsrtowcs(wchar_t *wcstr,const char *mbstr,size_t count, mbstate_t *mbstate);
12+
13+
14+
void badTest1(void *src, int size) {
15+
mbstowcs((wchar_t*)src,(char*)src,size); // BAD
16+
_locale_t locale;
17+
_mbstowcs_l((wchar_t*)src,(char*)src,size,locale); // BAD
18+
mbstate_t *mbstate;
19+
mbsrtowcs((wchar_t*)src,(char*)src,size,mbstate); // BAD
20+
}
21+
void goodTest2(){
22+
char src[] = "0123456789ABCDEF";
23+
wchar_t dst[16];
24+
int res = mbstowcs(dst, src,16); // GOOD
25+
if (res == sizeof(dst)) {
26+
dst[res-1] = NULL;
27+
} else {
28+
dst[res] = NULL;
29+
}
30+
printf("%s\n", dst);
31+
}
32+
void badTest2(){
33+
char src[] = "0123456789ABCDEF";
34+
wchar_t dst[16];
35+
mbstowcs(dst, src,16); // BAD
36+
printf("%s\n", dst);
37+
}
38+
void goodTest3(){
39+
char src[] = "0123456789ABCDEF";
40+
int size = mbstowcs(NULL, src,NULL);
41+
wchar_t * dst = (wchar_t*)calloc(size + 1, sizeof(wchar_t));
42+
mbstowcs(dst, src,size+1); // GOOD
43+
}
44+
void badTest3(){
45+
char src[] = "0123456789ABCDEF";
46+
int size = mbstowcs(NULL, src,NULL);
47+
wchar_t * dst = (wchar_t*)calloc(size + 1, 1);
48+
mbstowcs(dst, src,size+1); // BAD
49+
}
50+
void goodTest4(){
51+
char src[] = "0123456789ABCDEF";
52+
int size = mbstowcs(NULL, src,NULL);
53+
wchar_t * dst = (wchar_t*)malloc((size + 1)*sizeof(wchar_t));
54+
mbstowcs(dst, src,size+1); // GOOD
55+
}
56+
void badTest4(){
57+
char src[] = "0123456789ABCDEF";
58+
int size = mbstowcs(NULL, src,NULL);
59+
wchar_t * dst = (wchar_t*)malloc(size + 1);
60+
mbstowcs(dst, src,size+1); // BAD
61+
}
62+
int goodTest5(void *src){
63+
return mbstowcs(NULL, (char*)src,NULL); // GOOD
64+
}
65+
int badTest5 (void *src) {
66+
return mbstowcs(NULL, (char*)src,3); // BAD
67+
}
68+
void goodTest6(void *src){
69+
wchar_t dst[5];
70+
int size = mbstowcs(NULL, (char*)src,NULL);
71+
if(size>=sizeof(dst)){
72+
printf("buffer size error\n");
73+
return;
74+
}
75+
mbstowcs(dst, (char*)src,sizeof(dst)); // GOOD
76+
printf("%s\n", dst);
77+
}
78+
void badTest6(void *src){
79+
wchar_t dst[5];
80+
mbstowcs(dst, (char*)src,260); // BAD
81+
printf("%s\n", dst);
82+
}

0 commit comments

Comments
 (0)