celix icon indicating copy to clipboard operation
celix copied to clipboard

Check return value of `vasprintf` and `asprintf`

Open PengZheng opened this issue 2 years ago • 5 comments

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 avatar Mar 01 '23 06:03 PengZheng

@PengZheng Hi, would like to work on this issue!

ShaiviAgarwal2 avatar Jan 06 '25 12:01 ShaiviAgarwal2

@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?

ShaiviAgarwal2 avatar Jan 07 '25 09:01 ShaiviAgarwal2

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 avatar Jan 08 '25 02:01 PengZheng

@PengZheng Could you please assign this issue to me !!

ShaiviAgarwal2 avatar Jan 16 '25 07:01 ShaiviAgarwal2

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.

PengZheng avatar Jan 16 '25 11:01 PengZheng