Fix parser opens tmp file 2 times then crashes

When parsing binary data in the wmlparser3 script, a temporary file is
created and opened. The problem is that the temporary file is never
closed and in subsequent functions it is reopened.

The solution is first, create a list of temporary file paths to delete at
program’s exit. In the atexit’s registered cleaning function, all the
files in this list are deleted.

Then in the function that creates the temporary file, we simply close
the file after the binary data has been written in it.

Closes #3927
This commit is contained in:
Lovens Weche 2019-02-19 15:21:44 -05:00
parent 2396e0e734
commit 8322efa978

View file

@ -47,12 +47,14 @@ import os, glob, sys, re, subprocess, argparse, tempfile, shutil
import atexit
tempdirs_to_clean = []
tmpfiles_to_clean = []
@atexit.register
def cleaner():
for temp_dir in tempdirs_to_clean:
shutil.rmtree(temp_dir, ignore_errors=True)
for temp_file in tmpfiles_to_clean:
os.remove(temp_file)
class WMLError(Exception):
@ -371,11 +373,13 @@ class Parser:
"""
Parse a chunk of binary WML.
"""
temp = tempfile.NamedTemporaryFile(prefix="wmlparser_",
suffix=".cfg")
temp.write(binary)
temp.flush()
self.path = temp.name
td, tmpfilePath = tempfile.mkstemp(prefix="wmlparser_",
suffix=".cfg")
with open(tmpfilePath, 'wb') as temp:
temp.write(binary)
os.close(td)
self.path = tmpfilePath
tmpfiles_to_clean.append(tmpfilePath)
if not self.no_preprocess:
self.preprocess(defines)
return self.parse()