Check return value of `vasprintf` and `asprintf`
According to man asprintf, leaving these return value unchecked is dangerous:
If memory allocation wasn't possible, or some other error occurs, these functions will return -1, and the contents of strp are undefined.
#define _GNU_SOURCE /* See feature_test_macros(7)*/
#include <stdio.h>
int asprintf(char **strp, const char *fmt, ...);
int vasprintf(char **strp, const char *fmt, va_list ap);
It does fail for various reasons, e.g. EILSEQ ( A wide-character code that does not correspond to a valid character has been detected.) https://pubs.opengroup.org/onlinepubs/9699919799/functions/fprintf.html
An example is given by https://stackoverflow.com/questions/65334245/what-is-an-encoding-error-for-sprintf-that-should-return-1:
char buf[42];
wchar_t s[] = { 0xFFFF,49,50,51,0 };
int i = snprintf(buf, sizeof buf, "<%ls>", s);
printf("%d\n", i);
asprintf is used extensively in various modules, we need to check its usage carefully.
@PengZheng Hi, would like to work on this issue!
@PengZheng
To solve the problem of return values for asprintf and vasprintf, we need to perform certain steps:
Firstly, we have to search for all instances of asprintf and vasprintf in the codebase.
Then for each identified instance, check the return value to ensure it is not -1. If the return value is -1, we need to handle it appropriately.
Finally we will modify the code to include checks for the return values of asprintf and vasprintf
Am I thinking in right direction?
Hi, Shaivi.
We're currently in the process of modernize our code base. For an example of the so-called "modern" error handling style, check rsaShm_create. Let me warn you that some cases especially in the legacy codes could be tricky to deal with. For theses cases, a rewrite might be a better choice.
@PengZheng Could you please assign this issue to me !!
You could try something small first, like fix issues of a specific bundle and add corresponding error injection tests to make sure your changes are covered by unit tests.
Your PR touched too much code, most of which you are not familiar with.