Skip to content

Commit 1c3cc2b

Browse files
Crispy-fried-chickenmarcelstoer
authored andcommitted
Fix potential integer overflow in getnum (#3633)
1 parent 6038307 commit 1c3cc2b

File tree

1 file changed

+6
-4
lines changed

1 file changed

+6
-4
lines changed

app/modules/struct.c

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -99,12 +99,14 @@ typedef struct Header {
9999
} Header;
100100

101101

102-
static int getnum (const char **fmt, int df) {
102+
static int getnum (lua_State *L, const char **fmt, int df) {
103103
if (!isdigit(**fmt)) /* no number? */
104104
return df; /* return default value */
105105
else {
106106
int a = 0;
107107
do {
108+
if (a > (INT_MAX / 10) || a * 10 > (INT_MAX - (**fmt - '0')))
109+
luaL_error(L, "integral size overflow");
108110
a = a*10 + *((*fmt)++) - '0';
109111
} while (isdigit(**fmt));
110112
return a;
@@ -127,9 +129,9 @@ static size_t optsize (lua_State *L, char opt, const char **fmt) {
127129
case 'd': return sizeof(double);
128130
#endif
129131
case 'x': return 1;
130-
case 'c': return getnum(fmt, 1);
132+
case 'c': return getnum(L, fmt, 1);
131133
case 'i': case 'I': {
132-
int sz = getnum(fmt, sizeof(int));
134+
int sz = getnum(L, fmt, sizeof(int));
133135
if (sz > MAXINTSIZE)
134136
luaL_error(L, "integral size %d is larger than limit of %d",
135137
sz, MAXINTSIZE);
@@ -162,7 +164,7 @@ static void controloptions (lua_State *L, int opt, const char **fmt,
162164
case '>': h->endian = BIG; return;
163165
case '<': h->endian = LITTLE; return;
164166
case '!': {
165-
int a = getnum(fmt, MAXALIGN);
167+
int a = getnum(L, fmt, MAXALIGN);
166168
if (!isp2(a))
167169
luaL_error(L, "alignment %d is not a power of 2", a);
168170
h->align = a;

0 commit comments

Comments
 (0)