Skip to content

Commit b3262c1

Browse files
mgreterxzyfer
authored andcommitted
Fix file content malloc to avoid reading beyond buffer
Add another byte to avoid lexer going into unallocated memory land. End of file handling was always pretty poor with libsass. This is just another hack and no real fix.
1 parent 6f8eb39 commit b3262c1

File tree

1 file changed

+8
-4
lines changed

1 file changed

+8
-4
lines changed

src/file.cpp

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -394,9 +394,11 @@ namespace Sass {
394394
DWORD dwFileLength = GetFileSize(hFile, NULL);
395395
if (dwFileLength == INVALID_FILE_SIZE) return 0;
396396
// allocate an extra byte for the null char
397-
pBuffer = (BYTE*)malloc((dwFileLength+1)*sizeof(BYTE));
397+
// and another one for edge-cases in lexer
398+
pBuffer = (BYTE*)malloc((dwFileLength+2)*sizeof(BYTE));
398399
ReadFile(hFile, pBuffer, dwFileLength, &dwBytes, NULL);
399-
pBuffer[dwFileLength] = '\0';
400+
pBuffer[dwFileLength+0] = '\0';
401+
pBuffer[dwFileLength+1] = '\0';
400402
CloseHandle(hFile);
401403
// just convert from unsigned char*
402404
char* contents = (char*) pBuffer;
@@ -408,10 +410,12 @@ namespace Sass {
408410
if (file.is_open()) {
409411
size_t size = file.tellg();
410412
// allocate an extra byte for the null char
411-
contents = (char*) malloc((size+1)*sizeof(char));
413+
// and another one for edge-cases in lexer
414+
contents = (char*) malloc((size+2)*sizeof(char));
412415
file.seekg(0, std::ios::beg);
413416
file.read(contents, size);
414-
contents[size] = '\0';
417+
contents[size+0] = '\0';
418+
contents[size+0] = '\0';
415419
file.close();
416420
}
417421
#endif

0 commit comments

Comments
 (0)