We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Pyinstaller lock exe file while running on windows
Version of python: 2.7 32bit
Version of pyinstall: download from git

How to reproduce:
1: create 1.py, content:

```
import time
time.sleep(99999)
```

2: pack 1.py to 1.exe, run

```
pyinstaller.py 1.py
```

3: execute 1.exe

Then 1.exe cannot be rename while running.

I test py2exe and cx_Freeze they don't have this problem.
I think it's because pyinstaller didn't close file handle of exe after read it needs.

Pyinstaller use fopen not CreateFile so it has the default behavior.
other problem is pyinstaller will inhert file handles to child process but it's not necessarily,
I already test change py_utils.c:520 to FALSE is ok,
but problem still not resolved.

http://en.wikipedia.org/wiki/File_locking
http://msdn.microsoft.com/en-us/library/windows/desktop/aa363858%28v=vs.85%29.aspx
http://msdn.microsoft.com/en-us/library/windows/desktop/ms682425%28v=vs.85%29.aspx

If you still have problem to read this please contact me instead of close, otherwise I will open other again.


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `PyInstaller/loader/pyimod02_archive.py`
Content:
```
1 #-----------------------------------------------------------------------------
2 # Copyright (c) 2005-2016, PyInstaller Development Team.
3 #
4 # Distributed under the terms of the GNU General Public License with exception
5 # for distributing bootloader.
6 #
7 # The full license is in the file COPYING.txt, distributed with this software.
8 #-----------------------------------------------------------------------------
9 
10 # TODO clean up this module
11 
12 # Subclasses may not need marshal or struct, but since they're
13 # builtin, importing is safe.
14 #
15 # While an Archive is really an abstraction for any "filesystem
16 # within a file", it is tuned for use with imputil.FuncImporter.
17 # This assumes it contains python code objects, indexed by the
18 # the internal name (ie, no '.py').
19 
20 # See pyi_carchive.py for a more general archive (contains anything)
21 # that can be understood by a C program.
22 
23 
24 ### **NOTE** This module is used during bootstrap.
25 ### Import *ONLY* builtin modules.
26 
27 import marshal
28 import struct
29 import sys
30 import zlib
31 
32 
33 # For decrypting Python modules.
34 CRYPT_BLOCK_SIZE = 16
35 
36 
37 # content types for PYZ
38 PYZ_TYPE_MODULE = 0
39 PYZ_TYPE_PKG = 1
40 PYZ_TYPE_DATA = 2
41 
42 
43 class ArchiveFile(object):
44     """
45     File class support auto open when access member from file object
46     This class is use to avoid file locking on windows
47     """
48 
49     def __init__(self, *args, **kwargs):
50         self.args = args
51         self.kwargs = kwargs
52         self.pos = 0
53         self.fd = None
54         self.__open()
55 
56     def __getattr__(self, name):
57         """
58         Auto open file when access member from file object
59         This function only call when member of name not exist in self
60         """
61         assert self.fd
62         return getattr(self.fd, name)
63 
64     def __open(self):
65         """
66         Open file and seek to pos record from last close
67         """
68         if self.fd is None:
69             self.fd = open(*self.args, **self.kwargs)
70             self.fd.seek(self.pos)
71 
72     def __enter__(self):
73         self.__open()
74 
75     def __exit__(self, type, value, traceback):
76         assert self.fd
77         self.close()
78 
79     def close(self):
80         """
81         Close file and record pos
82         """
83         if self.fd is not None:
84             self.pos = self.fd.tell()
85             self.fd.close()
86             self.fd = None
87 
88 
89 class ArchiveReadError(RuntimeError):
90     pass
91 
92 
93 class ArchiveReader(object):
94     """
95     A base class for a repository of python code objects.
96     The extract method is used by imputil.ArchiveImporter
97     to get code objects by name (fully qualified name), so
98     an enduser "import a.b" would become
99       extract('a.__init__')
100       extract('a.b')
101     """
102     MAGIC = b'PYL\0'
103     HDRLEN = 12  # default is MAGIC followed by python's magic, int pos of toc
104     TOCPOS = 8
105     os = None
106     _bincache = None
107 
108     def __init__(self, path=None, start=0):
109         """
110         Initialize an Archive. If path is omitted, it will be an empty Archive.
111         """
112         self.toc = None
113         self.path = path
114         self.start = start
115 
116         # In Python 3 module 'imp' is no longer built-in and we cannot use it.
117         # There is for Python 3 another way how to obtain magic value.
118         if sys.version_info[0] == 2:
119             import imp
120             self.pymagic = imp.get_magic()
121         else:
122             # We cannot use at this bootstrap stage importlib directly
123             # but its frozen variant.
124             import _frozen_importlib
125             if sys.version_info[1] <= 3:
126                 # Python 3.3
127                 self.pymagic = _frozen_importlib._MAGIC_BYTES
128             elif sys.version_info[1] == 4:
129                 # Python 3.4
130                 self.pymagic = _frozen_importlib.MAGIC_NUMBER
131             else:
132                 # Python 3.5+
133                 self.pymagic = _frozen_importlib._bootstrap_external.MAGIC_NUMBER
134 
135         if path is not None:
136             self.lib = ArchiveFile(self.path, 'rb')
137             with self.lib:
138                 self.checkmagic()
139                 self.loadtoc()
140 
141 
142     def loadtoc(self):
143         """
144         Overridable.
145         Default: After magic comes an int (4 byte native) giving the
146         position of the TOC within self.lib.
147         Default: The TOC is a marshal-able string.
148         """
149         self.lib.seek(self.start + self.TOCPOS)
150         (offset,) = struct.unpack('!i', self.lib.read(4))
151         self.lib.seek(self.start + offset)
152         # Use marshal.loads() since load() arg must be a file object
153         # Convert the read list into a dict for faster access
154         self.toc = dict(marshal.loads(self.lib.read()))
155 
156     ######## This is what is called by FuncImporter #######
157     ## Since an Archive is flat, we ignore parent and modname.
158     #XXX obsolete - imputil only code
159     ##  def get_code(self, parent, modname, fqname):
160     ##      pass
161 
162     ####### Core method - Override as needed  #########
163     def extract(self, name):
164         """
165         Get the object corresponding to name, or None.
166         For use with imputil ArchiveImporter, object is a python code object.
167         'name' is the name as specified in an 'import name'.
168         'import a.b' will become:
169         extract('a') (return None because 'a' is not a code object)
170         extract('a.__init__') (return a code object)
171         extract('a.b') (return a code object)
172         Default implementation:
173           self.toc is a dict
174           self.toc[name] is pos
175           self.lib has the code object marshal-ed at pos
176         """
177         ispkg, pos = self.toc.get(name, (0, None))
178         if pos is None:
179             return None
180         with self.lib:
181             self.lib.seek(self.start + pos)
182             # use marshal.loads() sind load() arg must be a file object
183             obj = marshal.loads(self.lib.read())
184         return ispkg, obj
185 
186     ########################################################################
187     # Informational methods
188 
189     def contents(self):
190         """
191         Return a list of the contents
192         Default implementation assumes self.toc is a dict like object.
193         Not required by ArchiveImporter.
194         """
195         return list(self.toc.keys())
196 
197     def checkmagic(self):
198         """
199         Overridable.
200         Check to see if the file object self.lib actually has a file
201         we understand.
202         """
203         self.lib.seek(self.start)  # default - magic is at start of file
204 
205         if self.lib.read(len(self.MAGIC)) != self.MAGIC:
206             raise ArchiveReadError("%s is not a valid %s archive file"
207                                    % (self.path, self.__class__.__name__))
208 
209         if self.lib.read(len(self.pymagic)) != self.pymagic:
210             raise ArchiveReadError("%s has version mismatch to dll" %
211                 (self.path))
212 
213         self.lib.read(4)
214 
215 
216 class Cipher(object):
217     """
218     This class is used only to decrypt Python modules.
219     """
220     def __init__(self):
221         # At build-type the key is given to us from inside the spec file, at
222         # bootstrap-time, we must look for it ourselves by trying to import
223         # the generated 'pyi_crypto_key' module.
224         import pyimod00_crypto_key
225         key = pyimod00_crypto_key.key
226 
227         assert type(key) is str
228         if len(key) > CRYPT_BLOCK_SIZE:
229             self.key = key[0:CRYPT_BLOCK_SIZE]
230         else:
231             self.key = key.zfill(CRYPT_BLOCK_SIZE)
232         assert len(self.key) == CRYPT_BLOCK_SIZE
233 
234         # Import the right AES module.
235         self._aes = self._import_aesmod()
236 
237     def _import_aesmod(self):
238         """
239         Tries to import the AES module from PyCrypto.
240 
241         PyCrypto 2.4 and 2.6 uses different name of the AES extension.
242         """
243         # Not-so-easy way: at bootstrap time we have to load the module from the
244         # temporary directory in a manner similar to pyi_importers.CExtensionImporter.
245         from pyimod03_importers import CExtensionImporter
246         importer = CExtensionImporter()
247         # NOTE: We _must_ call find_module first.
248         # The _AES.so module exists only in PyCrypto 2.6 and later. Try to import
249         # that first.
250         modname = 'Crypto.Cipher._AES'
251         mod = importer.find_module(modname)
252         # Fallback to AES.so, which should be there in PyCrypto 2.4 and earlier.
253         if not mod:
254             modname = 'Crypto.Cipher.AES'
255             mod = importer.find_module(modname)
256             if not mod:
257                 # Raise import error if none of the AES modules is found.
258                 raise ImportError(modname)
259         mod = mod.load_module(modname)
260         # Issue #1663: Remove the AES module from sys.modules list. Otherwise
261         # it interferes with using 'Crypto.Cipher' module in users' code.
262         if modname in sys.modules:
263             del sys.modules[modname]
264         return mod
265 
266     def __create_cipher(self, iv):
267         # The 'BlockAlgo' class is stateful, this factory method is used to
268         # re-initialize the block cipher class with each call to encrypt() and
269         # decrypt().
270         return self._aes.new(self.key, self._aes.MODE_CFB, iv)
271 
272     def decrypt(self, data):
273         return self.__create_cipher(data[:CRYPT_BLOCK_SIZE]).decrypt(data[CRYPT_BLOCK_SIZE:])
274 
275 
276 class ZlibArchiveReader(ArchiveReader):
277     """
278     ZlibArchive - an archive with compressed entries. Archive is read
279     from the executable created by PyInstaller.
280 
281     This archive is used for bundling python modules inside the executable.
282 
283     NOTE: The whole ZlibArchive (PYZ) is compressed so it is not necessary
284           to compress single modules with zlib.
285     """
286     MAGIC = b'PYZ\0'
287     TOCPOS = 8
288     HDRLEN = ArchiveReader.HDRLEN + 5
289 
290     def __init__(self, path=None, offset=None):
291         if path is None:
292             offset = 0
293         elif offset is None:
294             for i in range(len(path) - 1, - 1, - 1):
295                 if path[i] == '?':
296                     try:
297                         offset = int(path[i + 1:])
298                     except ValueError:
299                         # Just ignore any spurious "?" in the path
300                         # (like in Windows UNC \\?\<path>).
301                         continue
302                     path = path[:i]
303                     break
304             else:
305                 offset = 0
306 
307         super(ZlibArchiveReader, self).__init__(path, offset)
308 
309         # Try to import the key module. If the key module is not available
310         # then it means that encryption is disabled.
311         try:
312             import pyimod00_crypto_key
313             self.cipher = Cipher()
314         except ImportError:
315             self.cipher = None
316 
317     def extract(self, name):
318         (typ, pos, length) = self.toc.get(name, (0, None, 0))
319         if pos is None:
320             return None
321         with self.lib:
322             self.lib.seek(self.start + pos)
323             obj = self.lib.read(length)
324         try:
325             if self.cipher:
326                 obj = self.cipher.decrypt(obj)
327             obj = zlib.decompress(obj)
328             if typ in (PYZ_TYPE_MODULE, PYZ_TYPE_PKG):
329                 obj = marshal.loads(obj)
330         except EOFError:
331             raise ImportError("PYZ entry '%s' failed to unmarshal" % name)
332         return typ, obj
333
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/PyInstaller/loader/pyimod02_archive.py b/PyInstaller/loader/pyimod02_archive.py
--- a/PyInstaller/loader/pyimod02_archive.py
+++ b/PyInstaller/loader/pyimod02_archive.py
@@ -28,6 +28,10 @@
 import struct
 import sys
 import zlib
+if sys.version_info[0] == 2:
+    import thread
+else:
+    import _thread as thread
 
 
 # For decrypting Python modules.
@@ -39,6 +43,17 @@
 PYZ_TYPE_PKG = 1
 PYZ_TYPE_DATA = 2
 
+class FilePos(object):
+    """
+    This class keeps track of the file object representing and current position
+    in a file.
+    """
+    def __init__(self):
+        # The file object representing this file.
+        self.file = None
+        # The position in the file when it was last closed.
+        self.pos = 0
+
 
 class ArchiveFile(object):
     """
@@ -49,41 +64,51 @@
     def __init__(self, *args, **kwargs):
         self.args = args
         self.kwargs = kwargs
-        self.pos = 0
-        self.fd = None
-        self.__open()
+        self._filePos = {}
 
-    def __getattr__(self, name):
+    def local(self):
         """
-        Auto open file when access member from file object
-        This function only call when member of name not exist in self
+        Return an instance of FilePos for the current thread. This is a crude
+        # re-implementation of threading.local, which isn't a built-in module
+        # and therefore isn't available.
         """
-        assert self.fd
-        return getattr(self.fd, name)
+        ti = thread.get_ident()
+        if ti not in self._filePos:
+            self._filePos[ti] = FilePos()
+        return self._filePos[ti]
 
-    def __open(self):
+    def __getattr__(self, name):
         """
-        Open file and seek to pos record from last close
+        Make this class act like a file, by invoking most methods on its
+        underlying file object.
         """
-        if self.fd is None:
-            self.fd = open(*self.args, **self.kwargs)
-            self.fd.seek(self.pos)
+        file = self.local().file
+        assert file
+        return getattr(file, name)
 
     def __enter__(self):
-        self.__open()
+        """
+        Open file and seek to pos record from last close.
+        """
+        # The file shouldn't be open yet.
+        fp = self.local()
+        assert not fp.file
+        # Open the file and seek to the last position.
+        fp.file = open(*self.args, **self.kwargs)
+        fp.file.seek(fp.pos)
 
     def __exit__(self, type, value, traceback):
-        assert self.fd
-        self.close()
-
-    def close(self):
         """
-        Close file and record pos
+        Close file and record pos.
         """
-        if self.fd is not None:
-            self.pos = self.fd.tell()
-            self.fd.close()
-            self.fd = None
+        # The file should still be open.
+        fp = self.local()
+        assert fp.file
+
+        # Close the file and record its position.
+        fp.pos = fp.file.tell()
+        fp.file.close()
+        fp.file = None
 
 
 class ArchiveReadError(RuntimeError):

{"golden_diff": "diff --git a/PyInstaller/loader/pyimod02_archive.py b/PyInstaller/loader/pyimod02_archive.py\n--- a/PyInstaller/loader/pyimod02_archive.py\n+++ b/PyInstaller/loader/pyimod02_archive.py\n@@ -28,6 +28,10 @@\n import struct\n import sys\n import zlib\n+if sys.version_info[0] == 2:\n+    import thread\n+else:\n+    import _thread as thread\n \n \n # For decrypting Python modules.\n@@ -39,6 +43,17 @@\n PYZ_TYPE_PKG = 1\n PYZ_TYPE_DATA = 2\n \n+class FilePos(object):\n+    \"\"\"\n+    This class keeps track of the file object representing and current position\n+    in a file.\n+    \"\"\"\n+    def __init__(self):\n+        # The file object representing this file.\n+        self.file = None\n+        # The position in the file when it was last closed.\n+        self.pos = 0\n+\n \n class ArchiveFile(object):\n     \"\"\"\n@@ -49,41 +64,51 @@\n     def __init__(self, *args, **kwargs):\n         self.args = args\n         self.kwargs = kwargs\n-        self.pos = 0\n-        self.fd = None\n-        self.__open()\n+        self._filePos = {}\n \n-    def __getattr__(self, name):\n+    def local(self):\n         \"\"\"\n-        Auto open file when access member from file object\n-        This function only call when member of name not exist in self\n+        Return an instance of FilePos for the current thread. This is a crude\n+        # re-implementation of threading.local, which isn't a built-in module\n+        # and therefore isn't available.\n         \"\"\"\n-        assert self.fd\n-        return getattr(self.fd, name)\n+        ti = thread.get_ident()\n+        if ti not in self._filePos:\n+            self._filePos[ti] = FilePos()\n+        return self._filePos[ti]\n \n-    def __open(self):\n+    def __getattr__(self, name):\n         \"\"\"\n-        Open file and seek to pos record from last close\n+        Make this class act like a file, by invoking most methods on its\n+        underlying file object.\n         \"\"\"\n-        if self.fd is None:\n-            self.fd = open(*self.args, **self.kwargs)\n-            self.fd.seek(self.pos)\n+        file = self.local().file\n+        assert file\n+        return getattr(file, name)\n \n     def __enter__(self):\n-        self.__open()\n+        \"\"\"\n+        Open file and seek to pos record from last close.\n+        \"\"\"\n+        # The file shouldn't be open yet.\n+        fp = self.local()\n+        assert not fp.file\n+        # Open the file and seek to the last position.\n+        fp.file = open(*self.args, **self.kwargs)\n+        fp.file.seek(fp.pos)\n \n     def __exit__(self, type, value, traceback):\n-        assert self.fd\n-        self.close()\n-\n-    def close(self):\n         \"\"\"\n-        Close file and record pos\n+        Close file and record pos.\n         \"\"\"\n-        if self.fd is not None:\n-            self.pos = self.fd.tell()\n-            self.fd.close()\n-            self.fd = None\n+        # The file should still be open.\n+        fp = self.local()\n+        assert fp.file\n+\n+        # Close the file and record its position.\n+        fp.pos = fp.file.tell()\n+        fp.file.close()\n+        fp.file = None\n \n \n class ArchiveReadError(RuntimeError):\n", "issue": "Pyinstaller lock exe file while running on windows\nVersion of python: 2.7 32bit\nVersion of pyinstall: download from git\n\nHow to reproduce:\n1: create 1.py, content:\n\n```\nimport time\ntime.sleep(99999)\n```\n\n2: pack 1.py to 1.exe, run\n\n```\npyinstaller.py 1.py\n```\n\n3: execute 1.exe\n\nThen 1.exe cannot be rename while running.\n\nI test py2exe and cx_Freeze they don't have this problem.\nI think it's because pyinstaller didn't close file handle of exe after read it needs.\n\nPyinstaller use fopen not CreateFile so it has the default behavior.\nother problem is pyinstaller will inhert file handles to child process but it's not necessarily,\nI already test change py_utils.c:520 to FALSE is ok,\nbut problem still not resolved.\n\nhttp://en.wikipedia.org/wiki/File_locking\nhttp://msdn.microsoft.com/en-us/library/windows/desktop/aa363858%28v=vs.85%29.aspx\nhttp://msdn.microsoft.com/en-us/library/windows/desktop/ms682425%28v=vs.85%29.aspx\n\nIf you still have problem to read this please contact me instead of close, otherwise I will open other again.\n\n", "before_files": [{"content": "#-----------------------------------------------------------------------------\n# Copyright (c) 2005-2016, PyInstaller Development Team.\n#\n# Distributed under the terms of the GNU General Public License with exception\n# for distributing bootloader.\n#\n# The full license is in the file COPYING.txt, distributed with this software.\n#-----------------------------------------------------------------------------\n\n# TODO clean up this module\n\n# Subclasses may not need marshal or struct, but since they're\n# builtin, importing is safe.\n#\n# While an Archive is really an abstraction for any \"filesystem\n# within a file\", it is tuned for use with imputil.FuncImporter.\n# This assumes it contains python code objects, indexed by the\n# the internal name (ie, no '.py').\n\n# See pyi_carchive.py for a more general archive (contains anything)\n# that can be understood by a C program.\n\n\n### **NOTE** This module is used during bootstrap.\n### Import *ONLY* builtin modules.\n\nimport marshal\nimport struct\nimport sys\nimport zlib\n\n\n# For decrypting Python modules.\nCRYPT_BLOCK_SIZE = 16\n\n\n# content types for PYZ\nPYZ_TYPE_MODULE = 0\nPYZ_TYPE_PKG = 1\nPYZ_TYPE_DATA = 2\n\n\nclass ArchiveFile(object):\n    \"\"\"\n    File class support auto open when access member from file object\n    This class is use to avoid file locking on windows\n    \"\"\"\n\n    def __init__(self, *args, **kwargs):\n        self.args = args\n        self.kwargs = kwargs\n        self.pos = 0\n        self.fd = None\n        self.__open()\n\n    def __getattr__(self, name):\n        \"\"\"\n        Auto open file when access member from file object\n        This function only call when member of name not exist in self\n        \"\"\"\n        assert self.fd\n        return getattr(self.fd, name)\n\n    def __open(self):\n        \"\"\"\n        Open file and seek to pos record from last close\n        \"\"\"\n        if self.fd is None:\n            self.fd = open(*self.args, **self.kwargs)\n            self.fd.seek(self.pos)\n\n    def __enter__(self):\n        self.__open()\n\n    def __exit__(self, type, value, traceback):\n        assert self.fd\n        self.close()\n\n    def close(self):\n        \"\"\"\n        Close file and record pos\n        \"\"\"\n        if self.fd is not None:\n            self.pos = self.fd.tell()\n            self.fd.close()\n            self.fd = None\n\n\nclass ArchiveReadError(RuntimeError):\n    pass\n\n\nclass ArchiveReader(object):\n    \"\"\"\n    A base class for a repository of python code objects.\n    The extract method is used by imputil.ArchiveImporter\n    to get code objects by name (fully qualified name), so\n    an enduser \"import a.b\" would become\n      extract('a.__init__')\n      extract('a.b')\n    \"\"\"\n    MAGIC = b'PYL\\0'\n    HDRLEN = 12  # default is MAGIC followed by python's magic, int pos of toc\n    TOCPOS = 8\n    os = None\n    _bincache = None\n\n    def __init__(self, path=None, start=0):\n        \"\"\"\n        Initialize an Archive. If path is omitted, it will be an empty Archive.\n        \"\"\"\n        self.toc = None\n        self.path = path\n        self.start = start\n\n        # In Python 3 module 'imp' is no longer built-in and we cannot use it.\n        # There is for Python 3 another way how to obtain magic value.\n        if sys.version_info[0] == 2:\n            import imp\n            self.pymagic = imp.get_magic()\n        else:\n            # We cannot use at this bootstrap stage importlib directly\n            # but its frozen variant.\n            import _frozen_importlib\n            if sys.version_info[1] <= 3:\n                # Python 3.3\n                self.pymagic = _frozen_importlib._MAGIC_BYTES\n            elif sys.version_info[1] == 4:\n                # Python 3.4\n                self.pymagic = _frozen_importlib.MAGIC_NUMBER\n            else:\n                # Python 3.5+\n                self.pymagic = _frozen_importlib._bootstrap_external.MAGIC_NUMBER\n\n        if path is not None:\n            self.lib = ArchiveFile(self.path, 'rb')\n            with self.lib:\n                self.checkmagic()\n                self.loadtoc()\n\n\n    def loadtoc(self):\n        \"\"\"\n        Overridable.\n        Default: After magic comes an int (4 byte native) giving the\n        position of the TOC within self.lib.\n        Default: The TOC is a marshal-able string.\n        \"\"\"\n        self.lib.seek(self.start + self.TOCPOS)\n        (offset,) = struct.unpack('!i', self.lib.read(4))\n        self.lib.seek(self.start + offset)\n        # Use marshal.loads() since load() arg must be a file object\n        # Convert the read list into a dict for faster access\n        self.toc = dict(marshal.loads(self.lib.read()))\n\n    ######## This is what is called by FuncImporter #######\n    ## Since an Archive is flat, we ignore parent and modname.\n    #XXX obsolete - imputil only code\n    ##  def get_code(self, parent, modname, fqname):\n    ##      pass\n\n    ####### Core method - Override as needed  #########\n    def extract(self, name):\n        \"\"\"\n        Get the object corresponding to name, or None.\n        For use with imputil ArchiveImporter, object is a python code object.\n        'name' is the name as specified in an 'import name'.\n        'import a.b' will become:\n        extract('a') (return None because 'a' is not a code object)\n        extract('a.__init__') (return a code object)\n        extract('a.b') (return a code object)\n        Default implementation:\n          self.toc is a dict\n          self.toc[name] is pos\n          self.lib has the code object marshal-ed at pos\n        \"\"\"\n        ispkg, pos = self.toc.get(name, (0, None))\n        if pos is None:\n            return None\n        with self.lib:\n            self.lib.seek(self.start + pos)\n            # use marshal.loads() sind load() arg must be a file object\n            obj = marshal.loads(self.lib.read())\n        return ispkg, obj\n\n    ########################################################################\n    # Informational methods\n\n    def contents(self):\n        \"\"\"\n        Return a list of the contents\n        Default implementation assumes self.toc is a dict like object.\n        Not required by ArchiveImporter.\n        \"\"\"\n        return list(self.toc.keys())\n\n    def checkmagic(self):\n        \"\"\"\n        Overridable.\n        Check to see if the file object self.lib actually has a file\n        we understand.\n        \"\"\"\n        self.lib.seek(self.start)  # default - magic is at start of file\n\n        if self.lib.read(len(self.MAGIC)) != self.MAGIC:\n            raise ArchiveReadError(\"%s is not a valid %s archive file\"\n                                   % (self.path, self.__class__.__name__))\n\n        if self.lib.read(len(self.pymagic)) != self.pymagic:\n            raise ArchiveReadError(\"%s has version mismatch to dll\" %\n                (self.path))\n\n        self.lib.read(4)\n\n\nclass Cipher(object):\n    \"\"\"\n    This class is used only to decrypt Python modules.\n    \"\"\"\n    def __init__(self):\n        # At build-type the key is given to us from inside the spec file, at\n        # bootstrap-time, we must look for it ourselves by trying to import\n        # the generated 'pyi_crypto_key' module.\n        import pyimod00_crypto_key\n        key = pyimod00_crypto_key.key\n\n        assert type(key) is str\n        if len(key) > CRYPT_BLOCK_SIZE:\n            self.key = key[0:CRYPT_BLOCK_SIZE]\n        else:\n            self.key = key.zfill(CRYPT_BLOCK_SIZE)\n        assert len(self.key) == CRYPT_BLOCK_SIZE\n\n        # Import the right AES module.\n        self._aes = self._import_aesmod()\n\n    def _import_aesmod(self):\n        \"\"\"\n        Tries to import the AES module from PyCrypto.\n\n        PyCrypto 2.4 and 2.6 uses different name of the AES extension.\n        \"\"\"\n        # Not-so-easy way: at bootstrap time we have to load the module from the\n        # temporary directory in a manner similar to pyi_importers.CExtensionImporter.\n        from pyimod03_importers import CExtensionImporter\n        importer = CExtensionImporter()\n        # NOTE: We _must_ call find_module first.\n        # The _AES.so module exists only in PyCrypto 2.6 and later. Try to import\n        # that first.\n        modname = 'Crypto.Cipher._AES'\n        mod = importer.find_module(modname)\n        # Fallback to AES.so, which should be there in PyCrypto 2.4 and earlier.\n        if not mod:\n            modname = 'Crypto.Cipher.AES'\n            mod = importer.find_module(modname)\n            if not mod:\n                # Raise import error if none of the AES modules is found.\n                raise ImportError(modname)\n        mod = mod.load_module(modname)\n        # Issue #1663: Remove the AES module from sys.modules list. Otherwise\n        # it interferes with using 'Crypto.Cipher' module in users' code.\n        if modname in sys.modules:\n            del sys.modules[modname]\n        return mod\n\n    def __create_cipher(self, iv):\n        # The 'BlockAlgo' class is stateful, this factory method is used to\n        # re-initialize the block cipher class with each call to encrypt() and\n        # decrypt().\n        return self._aes.new(self.key, self._aes.MODE_CFB, iv)\n\n    def decrypt(self, data):\n        return self.__create_cipher(data[:CRYPT_BLOCK_SIZE]).decrypt(data[CRYPT_BLOCK_SIZE:])\n\n\nclass ZlibArchiveReader(ArchiveReader):\n    \"\"\"\n    ZlibArchive - an archive with compressed entries. Archive is read\n    from the executable created by PyInstaller.\n\n    This archive is used for bundling python modules inside the executable.\n\n    NOTE: The whole ZlibArchive (PYZ) is compressed so it is not necessary\n          to compress single modules with zlib.\n    \"\"\"\n    MAGIC = b'PYZ\\0'\n    TOCPOS = 8\n    HDRLEN = ArchiveReader.HDRLEN + 5\n\n    def __init__(self, path=None, offset=None):\n        if path is None:\n            offset = 0\n        elif offset is None:\n            for i in range(len(path) - 1, - 1, - 1):\n                if path[i] == '?':\n                    try:\n                        offset = int(path[i + 1:])\n                    except ValueError:\n                        # Just ignore any spurious \"?\" in the path\n                        # (like in Windows UNC \\\\?\\<path>).\n                        continue\n                    path = path[:i]\n                    break\n            else:\n                offset = 0\n\n        super(ZlibArchiveReader, self).__init__(path, offset)\n\n        # Try to import the key module. If the key module is not available\n        # then it means that encryption is disabled.\n        try:\n            import pyimod00_crypto_key\n            self.cipher = Cipher()\n        except ImportError:\n            self.cipher = None\n\n    def extract(self, name):\n        (typ, pos, length) = self.toc.get(name, (0, None, 0))\n        if pos is None:\n            return None\n        with self.lib:\n            self.lib.seek(self.start + pos)\n            obj = self.lib.read(length)\n        try:\n            if self.cipher:\n                obj = self.cipher.decrypt(obj)\n            obj = zlib.decompress(obj)\n            if typ in (PYZ_TYPE_MODULE, PYZ_TYPE_PKG):\n                obj = marshal.loads(obj)\n        except EOFError:\n            raise ImportError(\"PYZ entry '%s' failed to unmarshal\" % name)\n        return typ, obj\n", "path": "PyInstaller/loader/pyimod02_archive.py"}], "after_files": [{"content": "#-----------------------------------------------------------------------------\n# Copyright (c) 2005-2016, PyInstaller Development Team.\n#\n# Distributed under the terms of the GNU General Public License with exception\n# for distributing bootloader.\n#\n# The full license is in the file COPYING.txt, distributed with this software.\n#-----------------------------------------------------------------------------\n\n# TODO clean up this module\n\n# Subclasses may not need marshal or struct, but since they're\n# builtin, importing is safe.\n#\n# While an Archive is really an abstraction for any \"filesystem\n# within a file\", it is tuned for use with imputil.FuncImporter.\n# This assumes it contains python code objects, indexed by the\n# the internal name (ie, no '.py').\n\n# See pyi_carchive.py for a more general archive (contains anything)\n# that can be understood by a C program.\n\n\n### **NOTE** This module is used during bootstrap.\n### Import *ONLY* builtin modules.\n\nimport marshal\nimport struct\nimport sys\nimport zlib\nif sys.version_info[0] == 2:\n    import thread\nelse:\n    import _thread as thread\n\n\n# For decrypting Python modules.\nCRYPT_BLOCK_SIZE = 16\n\n\n# content types for PYZ\nPYZ_TYPE_MODULE = 0\nPYZ_TYPE_PKG = 1\nPYZ_TYPE_DATA = 2\n\nclass FilePos(object):\n    \"\"\"\n    This class keeps track of the file object representing and current position\n    in a file.\n    \"\"\"\n    def __init__(self):\n        # The file object representing this file.\n        self.file = None\n        # The position in the file when it was last closed.\n        self.pos = 0\n\n\nclass ArchiveFile(object):\n    \"\"\"\n    File class support auto open when access member from file object\n    This class is use to avoid file locking on windows\n    \"\"\"\n\n    def __init__(self, *args, **kwargs):\n        self.args = args\n        self.kwargs = kwargs\n        self._filePos = {}\n\n    def local(self):\n        \"\"\"\n        Return an instance of FilePos for the current thread. This is a crude\n        # re-implementation of threading.local, which isn't a built-in module\n        # and therefore isn't available.\n        \"\"\"\n        ti = thread.get_ident()\n        if ti not in self._filePos:\n            self._filePos[ti] = FilePos()\n        return self._filePos[ti]\n\n    def __getattr__(self, name):\n        \"\"\"\n        Make this class act like a file, by invoking most methods on its\n        underlying file object.\n        \"\"\"\n        file = self.local().file\n        assert file\n        return getattr(file, name)\n\n    def __enter__(self):\n        \"\"\"\n        Open file and seek to pos record from last close.\n        \"\"\"\n        # The file shouldn't be open yet.\n        fp = self.local()\n        assert not fp.file\n        # Open the file and seek to the last position.\n        fp.file = open(*self.args, **self.kwargs)\n        fp.file.seek(fp.pos)\n\n    def __exit__(self, type, value, traceback):\n        \"\"\"\n        Close file and record pos.\n        \"\"\"\n        # The file should still be open.\n        fp = self.local()\n        assert fp.file\n\n        # Close the file and record its position.\n        fp.pos = fp.file.tell()\n        fp.file.close()\n        fp.file = None\n\n\nclass ArchiveReadError(RuntimeError):\n    pass\n\n\nclass ArchiveReader(object):\n    \"\"\"\n    A base class for a repository of python code objects.\n    The extract method is used by imputil.ArchiveImporter\n    to get code objects by name (fully qualified name), so\n    an enduser \"import a.b\" would become\n      extract('a.__init__')\n      extract('a.b')\n    \"\"\"\n    MAGIC = b'PYL\\0'\n    HDRLEN = 12  # default is MAGIC followed by python's magic, int pos of toc\n    TOCPOS = 8\n    os = None\n    _bincache = None\n\n    def __init__(self, path=None, start=0):\n        \"\"\"\n        Initialize an Archive. If path is omitted, it will be an empty Archive.\n        \"\"\"\n        self.toc = None\n        self.path = path\n        self.start = start\n\n        # In Python 3 module 'imp' is no longer built-in and we cannot use it.\n        # There is for Python 3 another way how to obtain magic value.\n        if sys.version_info[0] == 2:\n            import imp\n            self.pymagic = imp.get_magic()\n        else:\n            # We cannot use at this bootstrap stage importlib directly\n            # but its frozen variant.\n            import _frozen_importlib\n            if sys.version_info[1] <= 3:\n                # Python 3.3\n                self.pymagic = _frozen_importlib._MAGIC_BYTES\n            elif sys.version_info[1] == 4:\n                # Python 3.4\n                self.pymagic = _frozen_importlib.MAGIC_NUMBER\n            else:\n                # Python 3.5+\n                self.pymagic = _frozen_importlib._bootstrap_external.MAGIC_NUMBER\n\n        if path is not None:\n            self.lib = ArchiveFile(self.path, 'rb')\n            with self.lib:\n                self.checkmagic()\n                self.loadtoc()\n\n\n    def loadtoc(self):\n        \"\"\"\n        Overridable.\n        Default: After magic comes an int (4 byte native) giving the\n        position of the TOC within self.lib.\n        Default: The TOC is a marshal-able string.\n        \"\"\"\n        self.lib.seek(self.start + self.TOCPOS)\n        (offset,) = struct.unpack('!i', self.lib.read(4))\n        self.lib.seek(self.start + offset)\n        # Use marshal.loads() since load() arg must be a file object\n        # Convert the read list into a dict for faster access\n        self.toc = dict(marshal.loads(self.lib.read()))\n\n    ######## This is what is called by FuncImporter #######\n    ## Since an Archive is flat, we ignore parent and modname.\n    #XXX obsolete - imputil only code\n    ##  def get_code(self, parent, modname, fqname):\n    ##      pass\n\n    ####### Core method - Override as needed  #########\n    def extract(self, name):\n        \"\"\"\n        Get the object corresponding to name, or None.\n        For use with imputil ArchiveImporter, object is a python code object.\n        'name' is the name as specified in an 'import name'.\n        'import a.b' will become:\n        extract('a') (return None because 'a' is not a code object)\n        extract('a.__init__') (return a code object)\n        extract('a.b') (return a code object)\n        Default implementation:\n          self.toc is a dict\n          self.toc[name] is pos\n          self.lib has the code object marshal-ed at pos\n        \"\"\"\n        ispkg, pos = self.toc.get(name, (0, None))\n        if pos is None:\n            return None\n        with self.lib:\n            self.lib.seek(self.start + pos)\n            # use marshal.loads() sind load() arg must be a file object\n            obj = marshal.loads(self.lib.read())\n        return ispkg, obj\n\n    ########################################################################\n    # Informational methods\n\n    def contents(self):\n        \"\"\"\n        Return a list of the contents\n        Default implementation assumes self.toc is a dict like object.\n        Not required by ArchiveImporter.\n        \"\"\"\n        return list(self.toc.keys())\n\n    def checkmagic(self):\n        \"\"\"\n        Overridable.\n        Check to see if the file object self.lib actually has a file\n        we understand.\n        \"\"\"\n        self.lib.seek(self.start)  # default - magic is at start of file\n\n        if self.lib.read(len(self.MAGIC)) != self.MAGIC:\n            raise ArchiveReadError(\"%s is not a valid %s archive file\"\n                                   % (self.path, self.__class__.__name__))\n\n        if self.lib.read(len(self.pymagic)) != self.pymagic:\n            raise ArchiveReadError(\"%s has version mismatch to dll\" %\n                (self.path))\n\n        self.lib.read(4)\n\n\nclass Cipher(object):\n    \"\"\"\n    This class is used only to decrypt Python modules.\n    \"\"\"\n    def __init__(self):\n        # At build-type the key is given to us from inside the spec file, at\n        # bootstrap-time, we must look for it ourselves by trying to import\n        # the generated 'pyi_crypto_key' module.\n        import pyimod00_crypto_key\n        key = pyimod00_crypto_key.key\n\n        assert type(key) is str\n        if len(key) > CRYPT_BLOCK_SIZE:\n            self.key = key[0:CRYPT_BLOCK_SIZE]\n        else:\n            self.key = key.zfill(CRYPT_BLOCK_SIZE)\n        assert len(self.key) == CRYPT_BLOCK_SIZE\n\n        # Import the right AES module.\n        self._aes = self._import_aesmod()\n\n    def _import_aesmod(self):\n        \"\"\"\n        Tries to import the AES module from PyCrypto.\n\n        PyCrypto 2.4 and 2.6 uses different name of the AES extension.\n        \"\"\"\n        # Not-so-easy way: at bootstrap time we have to load the module from the\n        # temporary directory in a manner similar to pyi_importers.CExtensionImporter.\n        from pyimod03_importers import CExtensionImporter\n        importer = CExtensionImporter()\n        # NOTE: We _must_ call find_module first.\n        # The _AES.so module exists only in PyCrypto 2.6 and later. Try to import\n        # that first.\n        modname = 'Crypto.Cipher._AES'\n        mod = importer.find_module(modname)\n        # Fallback to AES.so, which should be there in PyCrypto 2.4 and earlier.\n        if not mod:\n            modname = 'Crypto.Cipher.AES'\n            mod = importer.find_module(modname)\n            if not mod:\n                # Raise import error if none of the AES modules is found.\n                raise ImportError(modname)\n        mod = mod.load_module(modname)\n        # Issue #1663: Remove the AES module from sys.modules list. Otherwise\n        # it interferes with using 'Crypto.Cipher' module in users' code.\n        if modname in sys.modules:\n            del sys.modules[modname]\n        return mod\n\n    def __create_cipher(self, iv):\n        # The 'BlockAlgo' class is stateful, this factory method is used to\n        # re-initialize the block cipher class with each call to encrypt() and\n        # decrypt().\n        return self._aes.new(self.key, self._aes.MODE_CFB, iv)\n\n    def decrypt(self, data):\n        return self.__create_cipher(data[:CRYPT_BLOCK_SIZE]).decrypt(data[CRYPT_BLOCK_SIZE:])\n\n\nclass ZlibArchiveReader(ArchiveReader):\n    \"\"\"\n    ZlibArchive - an archive with compressed entries. Archive is read\n    from the executable created by PyInstaller.\n\n    This archive is used for bundling python modules inside the executable.\n\n    NOTE: The whole ZlibArchive (PYZ) is compressed so it is not necessary\n          to compress single modules with zlib.\n    \"\"\"\n    MAGIC = b'PYZ\\0'\n    TOCPOS = 8\n    HDRLEN = ArchiveReader.HDRLEN + 5\n\n    def __init__(self, path=None, offset=None):\n        if path is None:\n            offset = 0\n        elif offset is None:\n            for i in range(len(path) - 1, - 1, - 1):\n                if path[i] == '?':\n                    try:\n                        offset = int(path[i + 1:])\n                    except ValueError:\n                        # Just ignore any spurious \"?\" in the path\n                        # (like in Windows UNC \\\\?\\<path>).\n                        continue\n                    path = path[:i]\n                    break\n            else:\n                offset = 0\n\n        super(ZlibArchiveReader, self).__init__(path, offset)\n\n        # Try to import the key module. If the key module is not available\n        # then it means that encryption is disabled.\n        try:\n            import pyimod00_crypto_key\n            self.cipher = Cipher()\n        except ImportError:\n            self.cipher = None\n\n    def extract(self, name):\n        (typ, pos, length) = self.toc.get(name, (0, None, 0))\n        if pos is None:\n            return None\n        with self.lib:\n            self.lib.seek(self.start + pos)\n            obj = self.lib.read(length)\n        try:\n            if self.cipher:\n                obj = self.cipher.decrypt(obj)\n            obj = zlib.decompress(obj)\n            if typ in (PYZ_TYPE_MODULE, PYZ_TYPE_PKG):\n                obj = marshal.loads(obj)\n        except EOFError:\n            raise ImportError(\"PYZ entry '%s' failed to unmarshal\" % name)\n        return typ, obj\n", "path": "PyInstaller/loader/pyimod02_archive.py"}]}