Fail cleanly on allocation failures

Previously code in the SWIG tool didn't handle allocation failures
well.  Most places didn't check for NULL return from
malloc()/realloc()/calloc() at all, typically resulting in undefined
behaviour, and some places used assert() to check for a NULL return
(which is a misuse of assert() and such checks disappear if built with
NDEBUG defined leaving us back with undefined behaviour).

All C allocations are now done via wrapper functions (Malloc(),
Realloc() and Calloc()) which emit and error and exit with non-zero
status on failure, so a non-NULL return can be relied upon.

Fixes #1901.
This commit is contained in:
Olly Betts 2022-03-03 17:45:03 +13:00 committed by Olly Betts
commit e38847f7e1
14 changed files with 83 additions and 65 deletions

View file

@ -36,7 +36,7 @@ static char *fake_version = 0;
char *Swig_copy_string(const char *s) {
char *c = 0;
if (s) {
c = (char *) malloc(strlen(s) + 1);
c = (char *) Malloc(strlen(s) + 1);
strcpy(c, s);
}
return c;
@ -1251,7 +1251,7 @@ void Swig_offset_string(String *s, int number) {
if ((Char(s))[len-1] == '\n')
--lines;
/* allocate a temporary storage for a padded string */
res = (char*)malloc(len + lines * number * 2 + 1);
res = (char*)Malloc(len + lines * number * 2 + 1);
res[len + lines * number * 2] = 0;
/* copy lines to res, prepending tabs to each line */
@ -1275,7 +1275,7 @@ void Swig_offset_string(String *s, int number) {
/* replace 's' contents with 'res' */
Clear(s);
Append(s, res);
free(res);
Free(res);
}
@ -1458,11 +1458,11 @@ String *Swig_string_regex(String *s) {
String *Swig_pcre_version(void) {
int len = pcre2_config(PCRE2_CONFIG_VERSION, NULL);
char *buf = malloc(len);
char *buf = Malloc(len);
String *result;
pcre2_config(PCRE2_CONFIG_VERSION, buf);
result = NewStringf("PCRE2 Version: %s", buf);
free(buf);
Free(buf);
return result;
}