From 454fb20c95a2ece399482a297c3ed1708ec1de10 Mon Sep 17 00:00:00 2001 From: Y_Less Date: Mon, 7 Mar 2022 10:50:53 +0000 Subject: [PATCH] Fix a bug with empty global pawndoc: When you have `///` in the global scope with nothing after it, an extra space still gets appended to the output. However, this space isn't taken in to consideration when calculating the new length of the pawndoc and with enough of them you can get memory corruption. --- source/compiler/sc1.c | 41 ++++++++++++++++++++++++----------------- 1 file changed, 24 insertions(+), 17 deletions(-) diff --git a/source/compiler/sc1.c b/source/compiler/sc1.c index a50409e..308da67 100644 --- a/source/compiler/sc1.c +++ b/source/compiler/sc1.c @@ -1982,25 +1982,30 @@ void sc_attachdocumentation(symbol *sym) /* first check the size */ length=0; for (line=0; (str=get_docstring(line))!=NULL && *str!=sDOCSEP; line++) { - if (length>0) - length++; /* count 1 extra for a separating space */ - length+=strlen(str); + if (str[0]!='\0') { + if (length>0) + length++; /* count 1 extra for a separating space */ + length+=strlen(str); + } } /* for */ - if (sym==NULL && sc_documentation!=NULL) { - length += strlen(sc_documentation) + 1 + 4; /* plus 4 for "

" */ - assert(length>strlen(sc_documentation)); - } /* if */ - if (length>0) { - /* allocate memory for the documentation */ - if (sym!=NULL && sym->documentation!=NULL) + if (sym==NULL && sc_documentation!=NULL) { + length += strlen(sc_documentation) + 1 + 4; /* plus 4 for "

" */ + assert(length > strlen(sc_documentation)); + } else if (sym!=NULL && sym->documentation!=NULL) { length+=strlen(sym->documentation) + 1 + 4;/* plus 4 for "

" */ + assert(length > strlen(sym->documentation)); + } /* if */ + + /* allocate memory for the documentation */ doc=(char*)malloc((length+1)*sizeof(char)); if (doc!=NULL) { /* initialize string or concatenate */ if (sym==NULL && sc_documentation!=NULL) { strcpy(doc,sc_documentation); strcat(doc,"

"); + free(sc_documentation); + sc_documentation=NULL; } else if (sym!=NULL && sym->documentation!=NULL) { strcpy(doc,sym->documentation); strcat(doc,"

"); @@ -2011,9 +2016,11 @@ void sc_attachdocumentation(symbol *sym) } /* if */ /* collect all documentation */ while ((str=get_docstring(0))!=NULL && *str!=sDOCSEP) { - if (doc[0]!='\0') - strcat(doc," "); - strcat(doc,str); + if (str[0]!='\0') { + if (doc[0]!='\0') + strcat(doc," "); + strcat(doc,str); + } delete_docstring(0); } /* while */ if (str!=NULL) { @@ -2021,12 +2028,12 @@ void sc_attachdocumentation(symbol *sym) assert(*str==sDOCSEP); delete_docstring(0); } /* if */ - if (sym!=NULL) { + if (sym==NULL) { + assert(sc_documentation==NULL); + sc_documentation=doc; + } else { assert(sym->documentation==NULL); sym->documentation=doc; - } else { - free(sc_documentation); - sc_documentation=doc; } /* if */ } /* if */ } else {