[njs] Fixed fd leakage in njs_process_file().

Dmitry Volyntsev xeioex at nginx.com
Fri Sep 1 15:51:50 UTC 2017


details:   http://hg.nginx.org/njs/rev/fa735c652e7c
branches:  
changeset: 407:fa735c652e7c
user:      Dmitry Volyntsev <xeioex at nginx.com>
date:      Fri Sep 01 18:51:20 2017 +0300
description:
Fixed fd leakage in njs_process_file().

Initially, njs_process_file() was not designed to be invoked multiple
times. Making it reusable by releasing the resources used.

diffstat:

 njs/njs.c |  29 +++++++++++++++++++++++------
 1 files changed, 23 insertions(+), 6 deletions(-)

diffs (72 lines):

diff -r fc92d8af502c -r fa735c652e7c njs/njs.c
--- a/njs/njs.c	Fri Sep 01 18:51:17 2017 +0300
+++ b/njs/njs.c	Fri Sep 01 18:51:20 2017 +0300
@@ -335,7 +335,8 @@ njs_process_file(njs_opts_t *opts, njs_v
     script.start = realloc(NULL, size);
     if (script.start == NULL) {
         fprintf(stderr, "alloc failed while reading '%s'\n", file);
-        return NXT_ERROR;
+        ret = NXT_ERROR;
+        goto done;
     }
 
     p = script.start;
@@ -351,7 +352,8 @@ njs_process_file(njs_opts_t *opts, njs_v
         if (n < 0) {
             fprintf(stderr, "failed to read file: '%s' (%s)\n",
                     file, strerror(errno));
-            return NXT_ERROR;
+            ret = NXT_ERROR;
+            goto done;
         }
 
         if (p + n > end) {
@@ -360,7 +362,8 @@ njs_process_file(njs_opts_t *opts, njs_v
             script.start = realloc(script.start, size);
             if (script.start == NULL) {
                 fprintf(stderr, "alloc failed while reading '%s'\n", file);
-                return NXT_ERROR;
+                ret = NXT_ERROR;
+                goto done;
             }
 
             p = script.start + script.length;
@@ -376,13 +379,15 @@ njs_process_file(njs_opts_t *opts, njs_v
     vm = njs_vm_create(vm_options);
     if (vm == NULL) {
         fprintf(stderr, "failed to create vm\n");
-        return NXT_ERROR;
+        ret = NXT_ERROR;
+        goto done;
     }
 
     ret = njs_process_script(vm, opts, &script, &out);
     if (ret != NXT_OK) {
         fprintf(stderr, "failed to get retval from VM\n");
-        return NXT_ERROR;
+        ret = NXT_ERROR;
+        goto done;
     }
 
     if (!opts->disassemble) {
@@ -394,7 +399,19 @@ njs_process_file(njs_opts_t *opts, njs_v
         }
     }
 
-    return NXT_OK;
+    ret = NXT_OK;
+
+done:
+
+    if (script.start != NULL) {
+        free(script.start);
+    }
+
+    if (fd != STDIN_FILENO) {
+        close(fd);
+    }
+
+    return ret;
 }
 
 


More information about the nginx-devel mailing list