patch for expandmacro

jcopenha <[email protected]> Sun, 12 Sep 2004 19:28:47 -0400
Newsgroups gmane.comp.tex.latex.latex2rtf.devel
Message-ID <1095031727.17386.13.camel@adonix>
Hello,
	I was running into a problem on my particular tex file that had some
large parameters to macros.  This was causing a segfault in
definitions.c:expandmacro because it was overflowing the staticly
allocated buffer[1024].  I've changed it to calculate the max length
based on the args array and the macro passed in.  There are still some
other places where this code could fail but this fix solves my problem.
=)

(the patch can also be acquired at
http://www.typedef.org/jcopenha/patches/latex2rtf/l2r-expandmacro-fix-1.9.15.diff)

(Please CC me on any response as I'm not subscribed to the list)

Jason Copenhaver
l2r-expandmacro-fix-1.9.15.diff (text/x-patch, 1.5 KB)
diff -u latex2rtf-1.9.15/definitions.c latex2rtf-1.9.15-jc/definitions.c
--- latex2rtf-1.9.15/definitions.c	2003-07-16 20:25:25.000000000 -0400
+++ latex2rtf-1.9.15-jc/definitions.c	2004-09-12 19:15:23.027849528 -0400
@@ -110,7 +110,8 @@
 **************************************************************************/
 {
 	int i=0,param;
-	char * args[9], *dmacro, *macro_piece, *next_piece, *expanded, buffer[1024], *cs;
+	char * args[9], *dmacro, *macro_piece, *next_piece, *expanded, *buffer = NULL, *cs;
+	int max_len = 0;
 
 	if (params<=0) 
 		return strdup(macro);
@@ -118,18 +119,28 @@
 	if (opt_param) {
 		args[i++] = getBracketParam();
 		if (!args[0]) args[0] = strdup(opt_param);
+		max_len += strlen(args[i-1]);
 	}
 
 	for (; i<params; i++) {
 		args[i] = getBraceParam();
+		max_len += strlen(args[i]);
 		diagnostics(3, "argument #%d <%s>", i+1, args[i]);
 	}
+
 	
-	*buffer='\0';
-	expanded = buffer;
 	dmacro = strdup(macro);
 	macro_piece = dmacro;
+	max_len += strlen(macro_piece);
+
+	diagnostics(3, "max_len in expandmacro = %d\n", max_len);
+	if(max_len > 0) {
+		buffer = (char*)malloc(sizeof(char) * max_len);
+		memset(buffer,'\0',max_len);
+	}
 	
+	expanded = buffer;
+
 	/* convert "\csname" to "\" */
 	while ((cs=strstr(dmacro, "\\csname")) != NULL) strcpy(cs+1,cs+7);
 		
@@ -176,6 +187,7 @@
 		if (args[i]) free(args[i]);
 
 	if (dmacro) free(dmacro);
+	if (buffer) free(buffer);
 
 	diagnostics(3, "expandmacro expanded=<%s>", buffer);
 	return strdup(buffer);