emulator_windows.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  1. import codecs
  2. import os
  3. import re
  4. import typing as t
  5. import winreg
  6. from dataclasses import dataclass
  7. # module/device/platform/emulator_base.py
  8. # module/device/platform/emulator_windows.py
  9. # Will be used in Alas Easy Install, they shouldn't import any Alas modules.
  10. from module.device.platform2.emulator_base import (
  11. EmulatorBase,
  12. EmulatorInstanceBase,
  13. EmulatorManagerBase,
  14. remove_duplicated_path)
  15. from module.device.platform2.utils import cached_property, iter_folder
  16. @dataclass
  17. class RegValue:
  18. name: str
  19. value: str
  20. typ: int
  21. def list_reg(reg) -> t.List[RegValue]:
  22. """
  23. List all values in a reg key
  24. """
  25. rows = []
  26. index = 0
  27. try:
  28. while 1:
  29. value = RegValue(*winreg.EnumValue(reg, index))
  30. index += 1
  31. rows.append(value)
  32. except OSError:
  33. pass
  34. return rows
  35. def list_key(reg) -> t.List[RegValue]:
  36. """
  37. List all values in a reg key
  38. """
  39. rows = []
  40. index = 0
  41. try:
  42. while 1:
  43. value = winreg.EnumKey(reg, index)
  44. index += 1
  45. rows.append(value)
  46. except OSError:
  47. pass
  48. return rows
  49. def abspath(path):
  50. return os.path.abspath(path).replace('\\', '/')
  51. class EmulatorInstance(EmulatorInstanceBase):
  52. @cached_property
  53. def emulator(self):
  54. """
  55. Returns:
  56. Emulator:
  57. """
  58. return Emulator(self.path)
  59. class Emulator(EmulatorBase):
  60. @classmethod
  61. def path_to_type(cls, path: str) -> str:
  62. """
  63. Args:
  64. path: Path to .exe file, case insensitive
  65. Returns:
  66. str: Emulator type, such as Emulator.NoxPlayer
  67. """
  68. folder, exe = os.path.split(path)
  69. folder, dir1 = os.path.split(folder)
  70. folder, dir2 = os.path.split(folder)
  71. exe = exe.lower()
  72. dir1 = dir1.lower()
  73. dir2 = dir2.lower()
  74. if exe == 'nox.exe':
  75. if dir2 == 'nox':
  76. return cls.NoxPlayer
  77. elif dir2 == 'nox64':
  78. return cls.NoxPlayer64
  79. else:
  80. return cls.NoxPlayer
  81. if exe == 'bluestacks.exe':
  82. if dir1 in ['bluestacks', 'bluestacks_cn']:
  83. return cls.BlueStacks4
  84. elif dir1 in ['bluestacks_nxt', 'bluestacks_nxt_cn']:
  85. return cls.BlueStacks5
  86. else:
  87. return cls.BlueStacks4
  88. if exe == 'hd-player.exe':
  89. if dir1 in ['bluestacks', 'bluestacks_cn']:
  90. return cls.BlueStacks4
  91. elif dir1 in ['bluestacks_nxt', 'bluestacks_nxt_cn']:
  92. return cls.BlueStacks5
  93. else:
  94. return cls.BlueStacks5
  95. if exe == 'dnplayer.exe':
  96. if dir1 == 'ldplayer':
  97. return cls.LDPlayer3
  98. elif dir1 == 'ldplayer4':
  99. return cls.LDPlayer4
  100. elif dir1 == 'ldplayer9':
  101. return cls.LDPlayer9
  102. else:
  103. return cls.LDPlayer3
  104. if exe == 'nemuplayer.exe':
  105. if dir2 == 'nemu':
  106. return cls.MuMuPlayer
  107. elif dir2 == 'nemu9':
  108. return cls.MuMuPlayerX
  109. else:
  110. return cls.MuMuPlayer
  111. if exe in ['mumuplayer.exe', 'mumunxmain.exe']:
  112. return cls.MuMuPlayer12
  113. if exe == 'memu.exe':
  114. return cls.MEmuPlayer
  115. return ''
  116. @staticmethod
  117. def multi_to_single(exe):
  118. """
  119. Convert a string that might be a multi-instance manager to its single instance executable.
  120. Args:
  121. exe (str): Path to emulator executable
  122. Yields:
  123. str: Path to emulator executable
  124. """
  125. if 'HD-MultiInstanceManager.exe' in exe:
  126. yield exe.replace('HD-MultiInstanceManager.exe', 'HD-Player.exe')
  127. yield exe.replace('HD-MultiInstanceManager.exe', 'Bluestacks.exe')
  128. elif 'MultiPlayerManager.exe' in exe:
  129. yield exe.replace('MultiPlayerManager.exe', 'Nox.exe')
  130. elif 'dnmultiplayer.exe' in exe:
  131. yield exe.replace('dnmultiplayer.exe', 'dnplayer.exe')
  132. elif 'NemuMultiPlayer.exe' in exe:
  133. yield exe.replace('NemuMultiPlayer.exe', 'NemuPlayer.exe')
  134. elif 'MuMuMultiPlayer.exe' in exe:
  135. yield exe.replace('MuMuMultiPlayer.exe', 'MuMuPlayer.exe')
  136. elif 'MuMuManager.exe' in exe:
  137. yield exe.replace('MuMuManager.exe', 'MuMuPlayer.exe')
  138. elif 'MEmuConsole.exe' in exe:
  139. yield exe.replace('MEmuConsole.exe', 'MEmu.exe')
  140. else:
  141. yield exe
  142. @staticmethod
  143. def single_to_console(exe: str):
  144. """
  145. Convert a string that might be a single instance executable to its console.
  146. Args:
  147. exe (str): Path to emulator executable
  148. Returns:
  149. str: Path to emulator console
  150. """
  151. if 'MuMuPlayer.exe' in exe:
  152. return exe.replace('MuMuPlayer.exe', 'MuMuManager.exe')
  153. # MuMuPlayer12 5.0
  154. elif 'MuMuNxMain.exe' in exe:
  155. return exe.replace('MuMuNxMain.exe', 'MuMuManager.exe')
  156. elif 'LDPlayer.exe' in exe:
  157. return exe.replace('LDPlayer.exe', 'ldconsole.exe')
  158. elif 'dnplayer.exe' in exe:
  159. return exe.replace('dnplayer.exe', 'ldconsole.exe')
  160. elif 'Bluestacks.exe' in exe:
  161. return exe.replace('Bluestacks.exe', 'bsconsole.exe')
  162. elif 'MEmu.exe' in exe:
  163. return exe.replace('MEmu.exe', 'memuc.exe')
  164. else:
  165. return exe
  166. @staticmethod
  167. def vbox_file_to_serial(file: str) -> str:
  168. """
  169. Args:
  170. file: Path to vbox file
  171. Returns:
  172. str: serial such as `127.0.0.1:5555`
  173. """
  174. regex = re.compile('<*?hostport="(.*?)".*?guestport="5555"/>')
  175. try:
  176. with open(file, 'r', encoding='utf-8', errors='ignore') as f:
  177. for line in f.readlines():
  178. # <Forwarding name="port2" proto="1" hostip="127.0.0.1" hostport="62026" guestport="5555"/>
  179. res = regex.search(line)
  180. if res:
  181. return f'127.0.0.1:{res.group(1)}'
  182. return ''
  183. except FileNotFoundError:
  184. return ''
  185. def iter_instances(self):
  186. """
  187. Yields:
  188. EmulatorInstance: Emulator instances found in this emulator
  189. """
  190. if self == Emulator.NoxPlayerFamily:
  191. # ./BignoxVMS/{name}/{name}.vbox
  192. for folder in self.list_folder('./BignoxVMS', is_dir=True):
  193. for file in iter_folder(folder, ext='.vbox'):
  194. serial = Emulator.vbox_file_to_serial(file)
  195. if serial:
  196. yield EmulatorInstance(
  197. serial=serial,
  198. name=os.path.basename(folder),
  199. path=self.path,
  200. )
  201. elif self == Emulator.BlueStacks5:
  202. # Get UserDefinedDir, where BlueStacks stores data
  203. folder = None
  204. try:
  205. with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\BlueStacks_nxt") as reg:
  206. folder = winreg.QueryValueEx(reg, 'UserDefinedDir')[0]
  207. except FileNotFoundError:
  208. pass
  209. try:
  210. with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\BlueStacks_nxt_cn") as reg:
  211. folder = winreg.QueryValueEx(reg, 'UserDefinedDir')[0]
  212. except FileNotFoundError:
  213. pass
  214. if not folder:
  215. return
  216. # Read {UserDefinedDir}/bluestacks.conf
  217. try:
  218. with open(self.abspath('./bluestacks.conf', folder), encoding='utf-8') as f:
  219. content = f.read()
  220. except FileNotFoundError:
  221. return
  222. # bst.instance.Nougat64.adb_port="5555"
  223. emulators = re.findall(r'bst.instance.(\w+).status.adb_port="(\d+)"', content)
  224. for emulator in emulators:
  225. yield EmulatorInstance(
  226. serial=f'127.0.0.1:{emulator[1]}',
  227. name=emulator[0],
  228. path=self.path,
  229. )
  230. elif self == Emulator.BlueStacks4:
  231. # ../Engine/Android
  232. regex = re.compile(r'^Android')
  233. for folder in self.list_folder('../Engine', is_dir=True):
  234. folder = os.path.basename(folder)
  235. res = regex.match(folder)
  236. if not res:
  237. continue
  238. # Serial from BlueStacks4 are not static, they get increased on every emulator launch
  239. # Assume all use 127.0.0.1:5555
  240. yield EmulatorInstance(
  241. serial=f'127.0.0.1:5555',
  242. name=folder,
  243. path=self.path
  244. )
  245. elif self == Emulator.LDPlayerFamily:
  246. # ./vms/leidian0
  247. regex = re.compile(r'^leidian(\d+)$')
  248. for folder in self.list_folder('./vms', is_dir=True):
  249. folder = os.path.basename(folder)
  250. res = regex.match(folder)
  251. if not res:
  252. continue
  253. # LDPlayer has no forward port config in .vbox file
  254. # Ports are auto increase, 5555, 5557, 5559, etc
  255. port = int(res.group(1)) * 2 + 5555
  256. yield EmulatorInstance(
  257. serial=f'127.0.0.1:{port}',
  258. name=folder,
  259. path=self.path
  260. )
  261. elif self == Emulator.MuMuPlayer:
  262. # MuMu has no multi instances, on 7555 only
  263. yield EmulatorInstance(
  264. serial='127.0.0.1:7555',
  265. name='',
  266. path=self.path,
  267. )
  268. elif self == Emulator.MuMuPlayerX:
  269. # vms/nemu-12.0-x64-default
  270. for folder in self.list_folder('../vms', is_dir=True):
  271. for file in iter_folder(folder, ext='.nemu'):
  272. serial = Emulator.vbox_file_to_serial(file)
  273. if serial:
  274. yield EmulatorInstance(
  275. serial=serial,
  276. name=os.path.basename(folder),
  277. path=self.path,
  278. )
  279. elif self == Emulator.MuMuPlayer12:
  280. # vms/MuMuPlayer-12.0-0
  281. for folder in self.list_folder('../vms', is_dir=True):
  282. for file in iter_folder(folder, ext='.nemu'):
  283. serial = Emulator.vbox_file_to_serial(file)
  284. name = os.path.basename(folder)
  285. if serial:
  286. yield EmulatorInstance(
  287. serial=serial,
  288. name=name,
  289. path=self.path,
  290. )
  291. # Fix for MuMu12 v4.0.4, default instance of which has no forward record in vbox config
  292. else:
  293. instance = EmulatorInstance(
  294. serial=serial,
  295. name=name,
  296. path=self.path,
  297. )
  298. if instance.MuMuPlayer12_id:
  299. instance.serial = f'127.0.0.1:{16384 + 32 * instance.MuMuPlayer12_id}'
  300. yield instance
  301. elif self == Emulator.MEmuPlayer:
  302. # ./MemuHyperv VMs/{name}/{name}.memu
  303. for folder in self.list_folder('./MemuHyperv VMs', is_dir=True):
  304. for file in iter_folder(folder, ext='.memu'):
  305. serial = Emulator.vbox_file_to_serial(file)
  306. if serial:
  307. yield EmulatorInstance(
  308. serial=serial,
  309. name=os.path.basename(folder),
  310. path=self.path,
  311. )
  312. def iter_adb_binaries(self) -> t.Iterable[str]:
  313. """
  314. Yields:
  315. str: Filepath to adb binaries found in this emulator
  316. """
  317. if self == Emulator.NoxPlayerFamily:
  318. exe = self.abspath('./nox_adb.exe')
  319. if os.path.exists(exe):
  320. yield exe
  321. if self == Emulator.MuMuPlayerFamily:
  322. # From MuMu9\emulator\nemu9\EmulatorShell
  323. # to MuMu9\emulator\nemu9\vmonitor\bin\adb_server.exe
  324. exe = self.abspath('../vmonitor/bin/adb_server.exe')
  325. if os.path.exists(exe):
  326. yield exe
  327. # All emulators have adb.exe
  328. exe = self.abspath('./adb.exe')
  329. if os.path.exists(exe):
  330. yield exe
  331. class EmulatorManager(EmulatorManagerBase):
  332. @staticmethod
  333. def iter_user_assist():
  334. """
  335. Get recently executed programs in UserAssist
  336. https://github.com/forensicmatt/MonitorUserAssist
  337. Yields:
  338. str: Path to emulator executables, may contains duplicate values
  339. """
  340. path = r'Software\Microsoft\Windows\CurrentVersion\Explorer\UserAssist'
  341. # {XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\xxx.exe
  342. regex_hash = re.compile(r'{.*}')
  343. try:
  344. with winreg.OpenKey(winreg.HKEY_CURRENT_USER, path) as reg:
  345. folders = list_key(reg)
  346. except FileNotFoundError:
  347. return
  348. for folder in folders:
  349. try:
  350. with winreg.OpenKey(winreg.HKEY_CURRENT_USER, f'{path}\\{folder}\\Count') as reg:
  351. for key in list_reg(reg):
  352. key = codecs.decode(key.name, 'rot-13')
  353. # Skip those with hash
  354. if regex_hash.search(key):
  355. continue
  356. for file in Emulator.multi_to_single(key):
  357. yield file
  358. except FileNotFoundError:
  359. # FileNotFoundError: [WinError 2] 系统找不到指定的文件。
  360. # Might be a random directory without "Count" subdirectory
  361. continue
  362. @staticmethod
  363. def iter_mui_cache():
  364. """
  365. Iter emulator executables that has ever run.
  366. http://what-when-how.com/windows-forensic-analysis/registry-analysis-windows-forensic-analysis-part-8/
  367. https://3gstudent.github.io/%E6%B8%97%E9%80%8F%E6%8A%80%E5%B7%A7-Windows%E7%B3%BB%E7%BB%9F%E6%96%87%E4%BB%B6%E6%89%A7%E8%A1%8C%E8%AE%B0%E5%BD%95%E7%9A%84%E8%8E%B7%E5%8F%96%E4%B8%8E%E6%B8%85%E9%99%A4
  368. Yields:
  369. str: Path to emulator executable, may contains duplicate values
  370. """
  371. path = r'Software\Classes\Local Settings\Software\Microsoft\Windows\Shell\MuiCache'
  372. try:
  373. with winreg.OpenKey(winreg.HKEY_CURRENT_USER, path) as reg:
  374. rows = list_reg(reg)
  375. except FileNotFoundError:
  376. return
  377. regex = re.compile(r'(^.*\.exe)\.')
  378. for row in rows:
  379. res = regex.search(row.name)
  380. if not res:
  381. continue
  382. for file in Emulator.multi_to_single(res.group(1)):
  383. yield file
  384. @staticmethod
  385. def get_install_dir_from_reg(path, key):
  386. """
  387. Args:
  388. path (str): f'SOFTWARE\\leidian\\ldplayer'
  389. key (str): 'InstallDir'
  390. Returns:
  391. str: Installation dir or None
  392. """
  393. try:
  394. with winreg.OpenKey(winreg.HKEY_CURRENT_USER, path) as reg:
  395. root = winreg.QueryValueEx(reg, key)[0]
  396. return root
  397. except FileNotFoundError:
  398. pass
  399. try:
  400. with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path) as reg:
  401. root = winreg.QueryValueEx(reg, key)[0]
  402. return root
  403. except FileNotFoundError:
  404. pass
  405. return None
  406. @staticmethod
  407. def iter_uninstall_registry():
  408. """
  409. Iter emulator uninstaller from registry.
  410. Yields:
  411. str: Path to uninstall exe file
  412. """
  413. known_uninstall_registry_path = [
  414. r'SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall',
  415. r'Software\Microsoft\Windows\CurrentVersion\Uninstall'
  416. ]
  417. known_emulator_registry_name = [
  418. 'Nox',
  419. 'Nox64',
  420. 'BlueStacks',
  421. 'BlueStacks_nxt',
  422. 'BlueStacks_cn',
  423. 'BlueStacks_nxt_cn',
  424. 'LDPlayer',
  425. 'LDPlayer4',
  426. 'LDPlayer9',
  427. 'leidian',
  428. 'leidian4',
  429. 'leidian9',
  430. 'Nemu',
  431. 'Nemu9',
  432. 'MuMuPlayer',
  433. 'MuMuPlayer-12.0',
  434. 'MuMu Player 12.0',
  435. 'MEmu',
  436. ]
  437. for path in known_uninstall_registry_path:
  438. try:
  439. with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path) as reg:
  440. software_list = list_key(reg)
  441. except FileNotFoundError:
  442. continue
  443. for software in software_list:
  444. if software not in known_emulator_registry_name:
  445. continue
  446. try:
  447. with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, f'{path}\\{software}') as software_reg:
  448. uninstall = winreg.QueryValueEx(software_reg, 'UninstallString')[0]
  449. except FileNotFoundError:
  450. continue
  451. if not uninstall:
  452. continue
  453. # UninstallString is like:
  454. # C:\Program Files\BlueStacks_nxt\BlueStacksUninstaller.exe -tmp
  455. # "E:\ProgramFiles\Microvirt\MEmu\uninstall\uninstall.exe" -u
  456. # Extract path in ""
  457. res = re.search('"(.*?)"', uninstall)
  458. uninstall = res.group(1) if res else uninstall
  459. yield uninstall
  460. @staticmethod
  461. def iter_running_emulator():
  462. """
  463. Yields:
  464. str: Path to emulator executables, may contains duplicate values
  465. """
  466. try:
  467. import psutil
  468. except ModuleNotFoundError:
  469. return
  470. # Since this is a one-time-usage, we access psutil._psplatform.Process directly
  471. # to bypass the call of psutil.Process.is_running().
  472. # This only costs about 0.017s.
  473. for pid in psutil.pids():
  474. proc = psutil._psplatform.Process(pid)
  475. try:
  476. exe = proc.cmdline()
  477. exe = exe[0].replace(r'\\', '/').replace('\\', '/')
  478. except (psutil.AccessDenied, psutil.NoSuchProcess, IndexError, OSError):
  479. # psutil.AccessDenied
  480. # NoSuchProcess: process no longer exists (pid=xxx)
  481. # OSError: [WinError 87] 参数错误。: '(originated from ReadProcessMemory)'
  482. continue
  483. if Emulator.is_emulator(exe):
  484. yield exe
  485. @cached_property
  486. def all_emulators(self) -> t.List[Emulator]:
  487. """
  488. Get all emulators installed on current computer.
  489. """
  490. exe = set([])
  491. # MuiCache
  492. for file in EmulatorManager.iter_mui_cache():
  493. if Emulator.is_emulator(file) and os.path.exists(file):
  494. exe.add(file)
  495. # UserAssist
  496. for file in EmulatorManager.iter_user_assist():
  497. if Emulator.is_emulator(file) and os.path.exists(file):
  498. exe.add(file)
  499. # LDPlayer install path
  500. for path in [r'SOFTWARE\leidian\ldplayer',
  501. r'SOFTWARE\leidian\ldplayer9']:
  502. ld = self.get_install_dir_from_reg(path, 'InstallDir')
  503. if ld:
  504. ld = abspath(os.path.join(ld, './dnplayer.exe'))
  505. if Emulator.is_emulator(ld) and os.path.exists(ld):
  506. exe.add(ld)
  507. # Uninstall registry
  508. for uninstall in EmulatorManager.iter_uninstall_registry():
  509. # Find emulator executable from uninstaller
  510. for file in iter_folder(abspath(os.path.dirname(uninstall)), ext='.exe'):
  511. if Emulator.is_emulator(file) and os.path.exists(file):
  512. exe.add(file)
  513. # Find from parent directory
  514. for file in iter_folder(abspath(os.path.join(os.path.dirname(uninstall), '../')), ext='.exe'):
  515. if Emulator.is_emulator(file) and os.path.exists(file):
  516. exe.add(file)
  517. # MuMu specific directory
  518. for file in iter_folder(abspath(os.path.join(os.path.dirname(uninstall), 'EmulatorShell')), ext='.exe'):
  519. if Emulator.is_emulator(file) and os.path.exists(file):
  520. exe.add(file)
  521. # Running
  522. for file in EmulatorManager.iter_running_emulator():
  523. if os.path.exists(file):
  524. exe.add(file)
  525. # De-redundancy
  526. exe = [Emulator(path).path for path in exe if Emulator.is_emulator(path)]
  527. exe = [Emulator(path) for path in remove_duplicated_path(exe)]
  528. return exe
  529. @cached_property
  530. def all_emulator_instances(self) -> t.List[EmulatorInstance]:
  531. """
  532. Get all emulator instances installed on current computer.
  533. """
  534. instances = []
  535. for emulator in self.all_emulators:
  536. instances += list(emulator.iter_instances())
  537. instances: t.List[EmulatorInstance] = sorted(instances, key=lambda x: str(x))
  538. return instances
  539. if __name__ == '__main__':
  540. self = EmulatorManager()
  541. for emu in self.all_emulator_instances:
  542. print(emu)