diff mbox

avoid relying on getcwd extensions (PR 80047)

Message ID 0812b186-6181-f0d1-0da0-5869df832765@gmail.com
State New
Headers show

Commit Message

Martin Sebor March 15, 2017, 8:29 p.m. UTC
PR 80047 - fixincludes/fixincl.c: PVS-Studio: Improper Release
of Memory Before Removing Last Reference (CWE-401) points out
that the fixincludes program calls getcwd with the first argument
set to NULL, apparently a Glibc extension, to have the function
allocate the memory to which it then returns a pointer.

The attached patch avoids this and also avoids assuming the
function cannot fail.

This is not a regression so I assume it's not suitable for
GCC 7 but rather for GCC 8 when stage 1 opens.

Martin

Comments

Jeff Law March 21, 2017, 3:46 p.m. UTC | #1
On 03/15/2017 02:29 PM, Martin Sebor wrote:
> PR 80047 - fixincludes/fixincl.c: PVS-Studio: Improper Release
> of Memory Before Removing Last Reference (CWE-401) points out
> that the fixincludes program calls getcwd with the first argument
> set to NULL, apparently a Glibc extension, to have the function
> allocate the memory to which it then returns a pointer.
>
> The attached patch avoids this and also avoids assuming the
> function cannot fail.
>
> This is not a regression so I assume it's not suitable for
> GCC 7 but rather for GCC 8 when stage 1 opens.
OK for gcc-8.
jeff
diff mbox

Patch

PR other/80047 - fixincludes/fixincl.c: PVS-Studio: Improper Release of Memory Before Removing Last Reference (CWE-401)

fixincludes/ChangeLog:

	PR other/80047
	* fixincl.c (process): Avoid relying on getcwd extensions and assuming
	the function will succeed.

diff --git a/fixincludes/fixincl.c b/fixincludes/fixincl.c
index 6dba2f6..6e6eb21 100644
--- a/fixincludes/fixincl.c
+++ b/fixincludes/fixincl.c
@@ -1353,8 +1353,10 @@  process (void)
   if (access (pz_curr_file, R_OK) != 0)
     {
       int erno = errno;
+      char cwdbuf[MAXPATHLEN];
+      char *cwd = getcwd (cwdbuf, sizeof cwdbuf);
       fprintf (stderr, "Cannot access %s from %s\n\terror %d (%s)\n",
-               pz_curr_file, getcwd ((char *) NULL, MAXPATHLEN),
+               pz_curr_file, cwd ? cwd : "current working directory",
                erno, xstrerror (erno));
       return;
     }