shithub: riscv

Download patch

ref: 4808971db6c402f0f50a9bd2145e0e2daa5786fa
parent: c9e86d6b342bc68f174825178d57e1e171972f5f
author: cinap_lenrek <[email protected]>
date: Thu Oct 11 18:49:45 EDT 2018

plumber: fix memory and filedescriptor leaks (thanks BurnZeZ)

--- a/sys/src/cmd/plumb/fsys.c
+++ b/sys/src/cmd/plumb/fsys.c
@@ -739,7 +739,10 @@
 	}
 	if(clearrules){
 		writerules(nil, 0);
-		rules[0] = nil;
+		for(m=0; rules[m]; m++){
+			freeruleset(rules[m]);
+			rules[m] = nil;
+		}
 	}
 	t->qid = f->qid;
 	t->iounit = 0;
--- a/sys/src/cmd/plumb/plumber.c
+++ b/sys/src/cmd/plumb/plumber.c
@@ -68,7 +68,6 @@
 		error("parse error");
 
 	rules = readrules(plumbfile, fd);
-	close(fd);
 
 	/*
 	 * Start all processes and threads from other proc
--- a/sys/src/cmd/plumb/plumber.h
+++ b/sys/src/cmd/plumb/plumber.h
@@ -81,6 +81,7 @@
 char*	writerules(char*, int);
 char*	expand(Exec*, char*, char**);
 void		makeports(Ruleset*[]);
+void		freeruleset(Ruleset*);
 void		printinputstack(void);
 int		popinput(void);
 
--- a/sys/src/cmd/plumb/rules.c
+++ b/sys/src/cmd/plumb/rules.c
@@ -103,8 +103,7 @@
 	if(str)
 		in->s = str;
 	else{
-		in->fd = emalloc(sizeof(Biobuf));
-		if(Binit(in->fd, fd, OREAD) < 0)
+		if((in->fd = Bfdopen(fd, OREAD)) == nil)
 			parseerror("can't initialize Bio for rules file: %r");
 	}
 
@@ -119,10 +118,8 @@
 	if(in == nil)
 		return 0;
 	input = in->next;
-	if(in->fd){
+	if(in->fd)
 		Bterm(in->fd);
-		free(in->fd);
-	}
 	free(in->file);
 	free(in);
 	return 1;
@@ -429,6 +426,15 @@
 	return 0;
 }
 
+void
+freerule(Rule *r)
+{
+	free(r->arg);
+	free(r->qarg);
+	free(r->regex);
+	free(r);
+}
+
 Rule*
 readrule(int *eof)
 {
@@ -435,6 +441,7 @@
 	Rule *rp;
 	char *line, *p;
 	char *word;
+	jmp_buf ojmp;
 
 Top:
 	line = getline();
@@ -463,6 +470,12 @@
 		return nil;
 
 	rp = emalloc(sizeof(Rule));
+	
+	memmove(ojmp, parsejmp, sizeof(jmp_buf));
+	if(setjmp(parsejmp)){
+		freerule(rp);
+		longjmp(ojmp, 1);
+	}
 
 	/* object */
 	for(word=p; *p!=' ' && *p!='\t'; p++)
@@ -497,18 +510,12 @@
 
 	parserule(rp);
 
+	memmove(parsejmp, ojmp, sizeof(jmp_buf));
+
 	return rp;
 }
 
 void
-freerule(Rule *r)
-{
-	free(r->arg);
-	free(r->qarg);
-	free(r->regex);
-}
-
-void
 freerules(Rule **r)
 {
 	while(*r)
@@ -735,8 +742,10 @@
 		for(s=text; *s!='\0'; s++)
 			if(*s=='\n' && *++s=='\n')
 				endofrule = s+1;
-		if(endofrule == nil)
+		if(endofrule == nil){
+			popinput();
 			return text;
+		}
 		input->end = endofrule;
 	}
 	for(n=0; rules[n]; n++)
@@ -746,7 +755,7 @@
 		rules[n++] = rs;
 		rules[n] = nil;
 	}
-	otext =text;
+	otext = text;
 	if(input == nil)
 		text = (uchar*)estrdup("");
 	else