versioninfo.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  1. #-----------------------------------------------------------------------------
  2. # Copyright (c) 2013-2023, PyInstaller Development Team.
  3. #
  4. # Distributed under the terms of the GNU General Public License (version 2
  5. # or later) with exception for distributing the bootloader.
  6. #
  7. # The full license is in the file COPYING.txt, distributed with this software.
  8. #
  9. # SPDX-License-Identifier: (GPL-2.0-or-later WITH Bootloader-exception)
  10. #-----------------------------------------------------------------------------
  11. import struct
  12. import pefile
  13. from PyInstaller.compat import win32api
  14. def pefile_check_control_flow_guard(filename):
  15. """
  16. Checks if the specified PE file has CFG (Control Flow Guard) enabled.
  17. Parameters
  18. ----------
  19. filename : str
  20. Path to the PE file to inspect.
  21. Returns
  22. ----------
  23. bool
  24. True if file is a PE file with CFG enabled. False if CFG is not enabled or if file could not be processed using
  25. the pefile library.
  26. """
  27. try:
  28. pe = pefile.PE(filename, fast_load=True)
  29. # https://docs.microsoft.com/en-us/windows/win32/debug/pe-format
  30. # IMAGE_DLLCHARACTERISTICS_GUARD_CF = 0x4000
  31. return bool(pe.OPTIONAL_HEADER.DllCharacteristics & 0x4000)
  32. except Exception:
  33. return False
  34. # Ensures no code from the executable is executed.
  35. LOAD_LIBRARY_AS_DATAFILE = 2
  36. def getRaw(text):
  37. """
  38. Encodes text as UTF-16LE (Microsoft 'Unicode') for use in structs.
  39. """
  40. return text.encode('UTF-16LE')
  41. def read_version_info_from_executable(exe_filename):
  42. """
  43. Read the version information structure from the given executable's resources, and return it as an instance of
  44. `VSVersionInfo` structure.
  45. """
  46. h = win32api.LoadLibraryEx(exe_filename, 0, LOAD_LIBRARY_AS_DATAFILE)
  47. res = win32api.EnumResourceNames(h, pefile.RESOURCE_TYPE['RT_VERSION'])
  48. if not len(res):
  49. return None
  50. data = win32api.LoadResource(h, pefile.RESOURCE_TYPE['RT_VERSION'], res[0])
  51. info = VSVersionInfo()
  52. info.fromRaw(data)
  53. win32api.FreeLibrary(h)
  54. return info
  55. def nextDWord(offset):
  56. """
  57. Align `offset` to the next 4-byte boundary.
  58. """
  59. return ((offset + 3) >> 2) << 2
  60. class VSVersionInfo:
  61. """
  62. WORD wLength; // length of the VS_VERSION_INFO structure
  63. WORD wValueLength; // length of the Value member
  64. WORD wType; // 1 means text, 0 means binary
  65. WCHAR szKey[]; // Contains the Unicode string "VS_VERSION_INFO".
  66. WORD Padding1[];
  67. VS_FIXEDFILEINFO Value;
  68. WORD Padding2[];
  69. WORD Children[]; // zero or more StringFileInfo or VarFileInfo
  70. // structures (or both) that are children of the
  71. // current version structure.
  72. """
  73. def __init__(self, ffi=None, kids=None):
  74. self.ffi = ffi
  75. self.kids = kids or []
  76. def fromRaw(self, data):
  77. i, (sublen, vallen, wType, nm) = parseCommon(data)
  78. #vallen is length of the ffi, typ is 0, nm is 'VS_VERSION_INFO'.
  79. i = nextDWord(i)
  80. # Now a VS_FIXEDFILEINFO
  81. self.ffi = FixedFileInfo()
  82. j = self.ffi.fromRaw(data, i)
  83. i = j
  84. while i < sublen:
  85. j = i
  86. i, (csublen, cvallen, ctyp, nm) = parseCommon(data, i)
  87. if nm.strip() == 'StringFileInfo':
  88. sfi = StringFileInfo()
  89. k = sfi.fromRaw(csublen, cvallen, nm, data, i, j + csublen)
  90. self.kids.append(sfi)
  91. i = k
  92. else:
  93. vfi = VarFileInfo()
  94. k = vfi.fromRaw(csublen, cvallen, nm, data, i, j + csublen)
  95. self.kids.append(vfi)
  96. i = k
  97. i = j + csublen
  98. i = nextDWord(i)
  99. return i
  100. def toRaw(self):
  101. raw_name = getRaw('VS_VERSION_INFO')
  102. rawffi = self.ffi.toRaw()
  103. vallen = len(rawffi)
  104. typ = 0
  105. sublen = 6 + len(raw_name) + 2
  106. pad = b''
  107. if sublen % 4:
  108. pad = b'\000\000'
  109. sublen = sublen + len(pad) + vallen
  110. pad2 = b''
  111. if sublen % 4:
  112. pad2 = b'\000\000'
  113. tmp = b''.join([kid.toRaw() for kid in self.kids])
  114. sublen = sublen + len(pad2) + len(tmp)
  115. return struct.pack('HHH', sublen, vallen, typ) + raw_name + b'\000\000' + pad + rawffi + pad2 + tmp
  116. def __eq__(self, other):
  117. return self.toRaw() == other
  118. def __str__(self, indent=''):
  119. indent = indent + ' '
  120. tmp = [kid.__str__(indent + ' ') for kid in self.kids]
  121. tmp = ', \n'.join(tmp)
  122. return '\n'.join([
  123. "# UTF-8",
  124. "#",
  125. "# For more details about fixed file info 'ffi' see:",
  126. "# http://msdn.microsoft.com/en-us/library/ms646997.aspx",
  127. "VSVersionInfo(",
  128. indent + f"ffi={self.ffi.__str__(indent)},",
  129. indent + "kids=[",
  130. tmp,
  131. indent + "]",
  132. ")",
  133. ])
  134. def __repr__(self):
  135. return "versioninfo.VSVersionInfo(ffi=%r, kids=%r)" % (self.ffi, self.kids)
  136. def parseCommon(data, start=0):
  137. i = start + 6
  138. (wLength, wValueLength, wType) = struct.unpack('3H', data[start:i])
  139. i, text = parseUString(data, i, i + wLength)
  140. return i, (wLength, wValueLength, wType, text)
  141. def parseUString(data, start, limit):
  142. i = start
  143. while i < limit:
  144. if data[i:i + 2] == b'\000\000':
  145. break
  146. i += 2
  147. text = data[start:i].decode('UTF-16LE')
  148. i += 2
  149. return i, text
  150. class FixedFileInfo:
  151. """
  152. DWORD dwSignature; //Contains the value 0xFEEFO4BD
  153. DWORD dwStrucVersion; // binary version number of this structure.
  154. // The high-order word of this member contains
  155. // the major version number, and the low-order
  156. // word contains the minor version number.
  157. DWORD dwFileVersionMS; // most significant 32 bits of the file's binary
  158. // version number
  159. DWORD dwFileVersionLS; //
  160. DWORD dwProductVersionMS; // most significant 32 bits of the binary version
  161. // number of the product with which this file was
  162. // distributed
  163. DWORD dwProductVersionLS; //
  164. DWORD dwFileFlagsMask; // bitmask that specifies the valid bits in
  165. // dwFileFlags. A bit is valid only if it was
  166. // defined when the file was created.
  167. DWORD dwFileFlags; // VS_FF_DEBUG, VS_FF_PATCHED etc.
  168. DWORD dwFileOS; // VOS_NT, VOS_WINDOWS32 etc.
  169. DWORD dwFileType; // VFT_APP etc.
  170. DWORD dwFileSubtype; // 0 unless VFT_DRV or VFT_FONT or VFT_VXD
  171. DWORD dwFileDateMS;
  172. DWORD dwFileDateLS;
  173. """
  174. def __init__(
  175. self,
  176. filevers=(0, 0, 0, 0),
  177. prodvers=(0, 0, 0, 0),
  178. mask=0x3f,
  179. flags=0x0,
  180. OS=0x40004,
  181. fileType=0x1,
  182. subtype=0x0,
  183. date=(0, 0)
  184. ):
  185. self.sig = 0xfeef04bd
  186. self.strucVersion = 0x10000
  187. self.fileVersionMS = (filevers[0] << 16) | (filevers[1] & 0xffff)
  188. self.fileVersionLS = (filevers[2] << 16) | (filevers[3] & 0xffff)
  189. self.productVersionMS = (prodvers[0] << 16) | (prodvers[1] & 0xffff)
  190. self.productVersionLS = (prodvers[2] << 16) | (prodvers[3] & 0xffff)
  191. self.fileFlagsMask = mask
  192. self.fileFlags = flags
  193. self.fileOS = OS
  194. self.fileType = fileType
  195. self.fileSubtype = subtype
  196. self.fileDateMS = date[0]
  197. self.fileDateLS = date[1]
  198. def fromRaw(self, data, i):
  199. (
  200. self.sig,
  201. self.strucVersion,
  202. self.fileVersionMS,
  203. self.fileVersionLS,
  204. self.productVersionMS,
  205. self.productVersionLS,
  206. self.fileFlagsMask,
  207. self.fileFlags,
  208. self.fileOS,
  209. self.fileType,
  210. self.fileSubtype,
  211. self.fileDateMS,
  212. self.fileDateLS,
  213. ) = struct.unpack('13L', data[i:i + 52])
  214. return i + 52
  215. def toRaw(self):
  216. return struct.pack(
  217. '13L',
  218. self.sig,
  219. self.strucVersion,
  220. self.fileVersionMS,
  221. self.fileVersionLS,
  222. self.productVersionMS,
  223. self.productVersionLS,
  224. self.fileFlagsMask,
  225. self.fileFlags,
  226. self.fileOS,
  227. self.fileType,
  228. self.fileSubtype,
  229. self.fileDateMS,
  230. self.fileDateLS,
  231. )
  232. def __eq__(self, other):
  233. return self.toRaw() == other
  234. def __str__(self, indent=''):
  235. fv = (
  236. self.fileVersionMS >> 16, self.fileVersionMS & 0xffff,
  237. self.fileVersionLS >> 16, self.fileVersionLS & 0xffff,
  238. ) # yapf: disable
  239. pv = (
  240. self.productVersionMS >> 16, self.productVersionMS & 0xffff,
  241. self.productVersionLS >> 16, self.productVersionLS & 0xffff,
  242. ) # yapf: disable
  243. fd = (self.fileDateMS, self.fileDateLS)
  244. tmp = [
  245. 'FixedFileInfo(',
  246. '# filevers and prodvers should be always a tuple with four items: (1, 2, 3, 4)',
  247. '# Set not needed items to zero 0.',
  248. 'filevers=%s,' % (fv,),
  249. 'prodvers=%s,' % (pv,),
  250. "# Contains a bitmask that specifies the valid bits 'flags'r",
  251. 'mask=%s,' % hex(self.fileFlagsMask),
  252. '# Contains a bitmask that specifies the Boolean attributes of the file.',
  253. 'flags=%s,' % hex(self.fileFlags),
  254. '# The operating system for which this file was designed.',
  255. '# 0x4 - NT and there is no need to change it.',
  256. 'OS=%s,' % hex(self.fileOS),
  257. '# The general type of file.',
  258. '# 0x1 - the file is an application.',
  259. 'fileType=%s,' % hex(self.fileType),
  260. '# The function of the file.',
  261. '# 0x0 - the function is not defined for this fileType',
  262. 'subtype=%s,' % hex(self.fileSubtype),
  263. '# Creation date and time stamp.',
  264. 'date=%s' % (fd,),
  265. ')',
  266. ]
  267. return f'\n{indent} '.join(tmp)
  268. def __repr__(self):
  269. fv = (
  270. self.fileVersionMS >> 16, self.fileVersionMS & 0xffff,
  271. self.fileVersionLS >> 16, self.fileVersionLS & 0xffff,
  272. ) # yapf: disable
  273. pv = (
  274. self.productVersionMS >> 16, self.productVersionMS & 0xffff,
  275. self.productVersionLS >> 16, self.productVersionLS & 0xffff,
  276. ) # yapf: disable
  277. fd = (self.fileDateMS, self.fileDateLS)
  278. return (
  279. 'versioninfo.FixedFileInfo(filevers=%r, prodvers=%r, '
  280. 'mask=0x%x, flags=0x%x, OS=0x%x, '
  281. 'fileType=%r, subtype=0x%x, date=%r)' %
  282. (fv, pv, self.fileFlagsMask, self.fileFlags, self.fileOS, self.fileType, self.fileSubtype, fd)
  283. )
  284. class StringFileInfo:
  285. """
  286. WORD wLength; // length of the version resource
  287. WORD wValueLength; // length of the Value member in the current
  288. // VS_VERSION_INFO structure
  289. WORD wType; // 1 means text, 0 means binary
  290. WCHAR szKey[]; // Contains the Unicode string 'StringFileInfo'.
  291. WORD Padding[];
  292. StringTable Children[]; // list of zero or more String structures
  293. """
  294. def __init__(self, kids=None):
  295. self.name = 'StringFileInfo'
  296. self.kids = kids or []
  297. def fromRaw(self, sublen, vallen, name, data, i, limit):
  298. self.name = name
  299. while i < limit:
  300. st = StringTable()
  301. j = st.fromRaw(data, i, limit)
  302. self.kids.append(st)
  303. i = j
  304. return i
  305. def toRaw(self):
  306. raw_name = getRaw(self.name)
  307. vallen = 0
  308. typ = 1
  309. sublen = 6 + len(raw_name) + 2
  310. pad = b''
  311. if sublen % 4:
  312. pad = b'\000\000'
  313. tmp = b''.join([kid.toRaw() for kid in self.kids])
  314. sublen = sublen + len(pad) + len(tmp)
  315. return struct.pack('HHH', sublen, vallen, typ) + raw_name + b'\000\000' + pad + tmp
  316. def __eq__(self, other):
  317. return self.toRaw() == other
  318. def __str__(self, indent=''):
  319. new_indent = indent + ' '
  320. tmp = ', \n'.join(kid.__str__(new_indent) for kid in self.kids)
  321. return f'{indent}StringFileInfo(\n{new_indent}[\n{tmp}\n{new_indent}])'
  322. def __repr__(self):
  323. return 'versioninfo.StringFileInfo(%r)' % self.kids
  324. class StringTable:
  325. """
  326. WORD wLength;
  327. WORD wValueLength;
  328. WORD wType;
  329. WCHAR szKey[];
  330. String Children[]; // list of zero or more String structures.
  331. """
  332. def __init__(self, name=None, kids=None):
  333. self.name = name or ''
  334. self.kids = kids or []
  335. def fromRaw(self, data, i, limit):
  336. i, (cpsublen, cpwValueLength, cpwType, self.name) = parseCodePage(data, i, limit) # should be code page junk
  337. i = nextDWord(i)
  338. while i < limit:
  339. ss = StringStruct()
  340. j = ss.fromRaw(data, i, limit)
  341. i = j
  342. self.kids.append(ss)
  343. i = nextDWord(i)
  344. return i
  345. def toRaw(self):
  346. raw_name = getRaw(self.name)
  347. vallen = 0
  348. typ = 1
  349. sublen = 6 + len(raw_name) + 2
  350. tmp = []
  351. for kid in self.kids:
  352. raw = kid.toRaw()
  353. if len(raw) % 4:
  354. raw = raw + b'\000\000'
  355. tmp.append(raw)
  356. tmp = b''.join(tmp)
  357. sublen += len(tmp)
  358. return struct.pack('HHH', sublen, vallen, typ) + raw_name + b'\000\000' + tmp
  359. def __eq__(self, other):
  360. return self.toRaw() == other
  361. def __str__(self, indent=''):
  362. new_indent = indent + ' '
  363. tmp = (',\n' + new_indent).join(str(kid) for kid in self.kids)
  364. return f"{indent}StringTable(\n{new_indent}'{self.name}',\n{new_indent}[{tmp}])"
  365. def __repr__(self):
  366. return 'versioninfo.StringTable(%r, %r)' % (self.name, self.kids)
  367. class StringStruct:
  368. """
  369. WORD wLength;
  370. WORD wValueLength;
  371. WORD wType;
  372. WCHAR szKey[];
  373. WORD Padding[];
  374. String Value[];
  375. """
  376. def __init__(self, name=None, val=None):
  377. self.name = name or ''
  378. self.val = val or ''
  379. def fromRaw(self, data, i, limit):
  380. i, (sublen, vallen, typ, self.name) = parseCommon(data, i)
  381. limit = i + sublen
  382. i = nextDWord(i)
  383. i, self.val = parseUString(data, i, limit)
  384. return i
  385. def toRaw(self):
  386. raw_name = getRaw(self.name)
  387. raw_val = getRaw(self.val)
  388. # TODO: document the size of vallen and sublen.
  389. vallen = len(self.val) + 1 # Number of (wide-)characters, not bytes!
  390. typ = 1
  391. sublen = 6 + len(raw_name) + 2
  392. pad = b''
  393. if sublen % 4:
  394. pad = b'\000\000'
  395. sublen = sublen + len(pad) + (vallen * 2)
  396. return struct.pack('HHH', sublen, vallen, typ) + raw_name + b'\000\000' + pad + raw_val + b'\000\000'
  397. def __eq__(self, other):
  398. return self.toRaw() == other
  399. def __str__(self, indent=''):
  400. return "StringStruct(%r, %r)" % (self.name, self.val)
  401. def __repr__(self):
  402. return 'versioninfo.StringStruct(%r, %r)' % (self.name, self.val)
  403. def parseCodePage(data, i, limit):
  404. i, (sublen, wValueLength, wType, nm) = parseCommon(data, i)
  405. return i, (sublen, wValueLength, wType, nm)
  406. class VarFileInfo:
  407. """
  408. WORD wLength; // length of the version resource
  409. WORD wValueLength; // length of the Value member in the current
  410. // VS_VERSION_INFO structure
  411. WORD wType; // 1 means text, 0 means binary
  412. WCHAR szKey[]; // Contains the Unicode string 'VarFileInfo'.
  413. WORD Padding[];
  414. Var Children[]; // list of zero or more Var structures
  415. """
  416. def __init__(self, kids=None):
  417. self.kids = kids or []
  418. def fromRaw(self, sublen, vallen, name, data, i, limit):
  419. self.sublen = sublen
  420. self.vallen = vallen
  421. self.name = name
  422. i = nextDWord(i)
  423. while i < limit:
  424. vs = VarStruct()
  425. j = vs.fromRaw(data, i, limit)
  426. self.kids.append(vs)
  427. i = j
  428. return i
  429. def toRaw(self):
  430. self.vallen = 0
  431. self.wType = 1
  432. self.name = 'VarFileInfo'
  433. raw_name = getRaw(self.name)
  434. sublen = 6 + len(raw_name) + 2
  435. pad = b''
  436. if sublen % 4:
  437. pad = b'\000\000'
  438. tmp = b''.join([kid.toRaw() for kid in self.kids])
  439. self.sublen = sublen + len(pad) + len(tmp)
  440. return struct.pack('HHH', self.sublen, self.vallen, self.wType) + raw_name + b'\000\000' + pad + tmp
  441. def __eq__(self, other):
  442. return self.toRaw() == other
  443. def __str__(self, indent=''):
  444. return indent + "VarFileInfo([%s])" % ', '.join(str(kid) for kid in self.kids)
  445. def __repr__(self):
  446. return 'versioninfo.VarFileInfo(%r)' % self.kids
  447. class VarStruct:
  448. """
  449. WORD wLength; // length of the version resource
  450. WORD wValueLength; // length of the Value member in the current
  451. // VS_VERSION_INFO structure
  452. WORD wType; // 1 means text, 0 means binary
  453. WCHAR szKey[]; // Contains the Unicode string 'Translation'
  454. // or a user-defined key string value
  455. WORD Padding[]; //
  456. WORD Value[]; // list of one or more values that are language
  457. // and code-page identifiers
  458. """
  459. def __init__(self, name=None, kids=None):
  460. self.name = name or ''
  461. self.kids = kids or []
  462. def fromRaw(self, data, i, limit):
  463. i, (self.sublen, self.wValueLength, self.wType, self.name) = parseCommon(data, i)
  464. i = nextDWord(i)
  465. for j in range(0, self.wValueLength, 2):
  466. kid = struct.unpack('H', data[i:i + 2])[0]
  467. self.kids.append(kid)
  468. i += 2
  469. return i
  470. def toRaw(self):
  471. self.wValueLength = len(self.kids) * 2
  472. self.wType = 0
  473. raw_name = getRaw(self.name)
  474. sublen = 6 + len(raw_name) + 2
  475. pad = b''
  476. if sublen % 4:
  477. pad = b'\000\000'
  478. self.sublen = sublen + len(pad) + self.wValueLength
  479. tmp = b''.join([struct.pack('H', kid) for kid in self.kids])
  480. return struct.pack('HHH', self.sublen, self.wValueLength, self.wType) + raw_name + b'\000\000' + pad + tmp
  481. def __eq__(self, other):
  482. return self.toRaw() == other
  483. def __str__(self, indent=''):
  484. return "VarStruct('%s', %r)" % (self.name, self.kids)
  485. def __repr__(self):
  486. return 'versioninfo.VarStruct(%r, %r)' % (self.name, self.kids)
  487. def load_version_info_from_text_file(filename):
  488. """
  489. Load the `VSVersionInfo` structure from its string-based (`VSVersionInfo.__str__`) serialization by reading the
  490. text from the file and running it through `eval()`.
  491. """
  492. # Read and parse the version file. It may have a byte order marker or encoding cookie - respect it if it does.
  493. import PyInstaller.utils.misc as miscutils
  494. with open(filename, 'rb') as fp:
  495. text = miscutils.decode(fp.read())
  496. # Deserialize via eval()
  497. try:
  498. info = eval(text)
  499. except Exception as e:
  500. raise ValueError("Failed to deserialize VSVersionInfo from text-based representation!") from e
  501. # Sanity check
  502. assert isinstance(info, VSVersionInfo), \
  503. f"Loaded incompatible structure type! Expected VSVersionInfo, got: {type(info)!r}"
  504. return info
  505. def write_version_info_to_executable(exe_filename, info):
  506. assert isinstance(info, VSVersionInfo)
  507. # Remember overlay
  508. pe = pefile.PE(exe_filename, fast_load=True)
  509. overlay_before = pe.get_overlay()
  510. pe.close()
  511. hdst = win32api.BeginUpdateResource(exe_filename, 0)
  512. win32api.UpdateResource(hdst, pefile.RESOURCE_TYPE['RT_VERSION'], 1, info.toRaw())
  513. win32api.EndUpdateResource(hdst, 0)
  514. if overlay_before:
  515. # Check if the overlay is still present
  516. pe = pefile.PE(exe_filename, fast_load=True)
  517. overlay_after = pe.get_overlay()
  518. pe.close()
  519. # If the update removed the overlay data, re-append it
  520. if not overlay_after:
  521. with open(exe_filename, 'ab') as exef:
  522. exef.write(overlay_before)