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

@ -98,15 +98,15 @@ static TargetLanguageModule modules[] = {
void SWIG_merge_envopt(const char *env, int oargc, char *oargv[], int *nargc, char ***nargv) {
if (!env) {
*nargc = oargc;
*nargv = (char **)malloc(sizeof(char *) * (oargc + 1));
*nargv = (char **)Malloc(sizeof(char *) * (oargc + 1));
memcpy(*nargv, oargv, sizeof(char *) * (oargc + 1));
return;
}
int argc = 1;
int arge = oargc + 1024;
char **argv = (char **) malloc(sizeof(char *) * (arge + 1));
char *buffer = (char *) malloc(2048);
char **argv = (char **) Malloc(sizeof(char *) * (arge + 1));
char *buffer = (char *) Malloc(2048);
char *b = buffer;
char *be = b + 1023;
const char *c = env;
@ -139,11 +139,11 @@ static void insert_option(int *argc, char ***argv, int index, char const *start,
size_t option_len = end - start;
// Preserve the NULL pointer at argv[argc]
new_argv = (char **)realloc(new_argv, (new_argc + 2) * sizeof(char *));
new_argv = (char **)Realloc(new_argv, (new_argc + 2) * sizeof(char *));
memmove(&new_argv[index + 1], &new_argv[index], sizeof(char *) * (new_argc + 1 - index));
new_argc++;
new_argv[index] = (char *)malloc(option_len + 1);
new_argv[index] = (char *)Malloc(option_len + 1);
memcpy(new_argv[index], start, option_len);
new_argv[index][option_len] = '\0';