after_merge
stringlengths
28
79.6k
before_merge
stringlengths
20
79.6k
url
stringlengths
38
71
full_traceback
stringlengths
43
922k
traceback_type
stringclasses
555 values
def dex_2_jar(app_path, app_dir, tools_dir): """Run dex2jar.""" try: logger.info("DEX -> JAR") working_dir = None args = [] if settings.JAR_CONVERTER == "d2j": logger.info("Using JAR converter - dex2jar") dexes = get_dex_files(app_dir) for idx, dex in enumerate(dexes): logger.info("Converting " + dex + " to JAR") if len(settings.DEX2JAR_BINARY) > 0 and isFileExists( settings.DEX2JAR_BINARY ): d2j = settings.DEX2JAR_BINARY else: if platform.system() == "Windows": win_fix_java(tools_dir) d2j = os.path.join(tools_dir, "d2j2/d2j-dex2jar.bat") else: inv = os.path.join(tools_dir, "d2j2/d2j_invoke.sh") d2j = os.path.join(tools_dir, "d2j2/d2j-dex2jar.sh") subprocess.call(["chmod", "777", d2j]) subprocess.call(["chmod", "777", inv]) args = [d2j, dex, "-f", "-o", app_dir + "classes" + str(idx) + ".jar"] subprocess.call(args) elif settings.JAR_CONVERTER == "enjarify": logger.info("Using JAR converter - Google enjarify") if len(settings.ENJARIFY_DIRECTORY) > 0 and isDirExists( settings.ENJARIFY_DIRECTORY ): working_dir = settings.ENJARIFY_DIRECTORY else: working_dir = os.path.join(tools_dir, "enjarify/") if platform.system() == "Windows": win_fix_python3(tools_dir) enjarify = os.path.join(working_dir, "enjarify.bat") args = [enjarify, app_path, "-f", "-o", app_dir + "classes.jar"] else: if len(settings.PYTHON3_PATH) > 2: python3 = os.path.join(settings.PYTHON3_PATH, "python3") else: python3 = get_python() args = [ python3, "-O", "-m", "enjarify.main", app_path, "-f", "-o", app_dir + "classes.jar", ] subprocess.call(args, cwd=working_dir) except: PrintException("Converting Dex to JAR")
def dex_2_jar(app_path, app_dir, tools_dir): """Run dex2jar.""" try: logger.info("DEX -> JAR") working_dir = None args = [] if settings.JAR_CONVERTER == "d2j": logger.info("Using JAR converter - dex2jar") dexes = get_dex_files(app_dir) for idx, dex in enumerate(dexes): logger.info("Converting " + dex + " to JAR") if len(settings.DEX2JAR_BINARY) > 0 and isFileExists( settings.DEX2JAR_BINARY ): d2j = settings.DEX2JAR_BINARY else: if platform.system() == "Windows": win_fix_java(tools_dir) d2j = os.path.join(tools_dir, "d2j2/d2j-dex2jar.bat") else: inv = os.path.join(tools_dir, "d2j2/d2j_invoke.sh") d2j = os.path.join(tools_dir, "d2j2/d2j-dex2jar.sh") subprocess.call(["chmod", "777", d2j]) subprocess.call(["chmod", "777", inv]) args = [d2j, dex, "-f", "-o", app_dir + "classes" + str(idx) + ".jar"] subprocess.call(args) elif settings.JAR_CONVERTER == "enjarify": logger.info("Using JAR converter - Google enjarify") if len(settings.ENJARIFY_DIRECTORY) > 0 and isDirExists( settings.ENJARIFY_DIRECTORY ): working_dir = settings.ENJARIFY_DIRECTORY else: working_dir = os.path.join(tools_dir, "enjarify/") if platform.system() == "Windows": win_fix_python3(tools_dir) enjarify = os.path.join(working_dir, "enjarify.bat") args = [enjarify, app_path, "-f", "-o", app_dir + "classes.jar"] else: if len(settings.PYTHON3_PATH) > 2: python3 = os.path.join(settings.PYTHON3_PATH, "python3") else: python3 = get_python() args = [ python3, "-O", "-m", "enjarify.main", app_path, "-f", "-o", app_dir + "classes.jar", ] subprocess.call(args, cwd=working_dir) except: PrintException("[ERROR] Converting Dex to JAR")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def dex_2_smali(app_dir, tools_dir): """Run dex2smali""" try: logger.info("DEX -> SMALI") dexes = get_dex_files(app_dir) for dex_path in dexes: logger.info("Converting " + dex_path + " to Smali Code") if len(settings.BACKSMALI_BINARY) > 0 and isFileExists( settings.BACKSMALI_BINARY ): bs_path = settings.BACKSMALI_BINARY else: bs_path = os.path.join(tools_dir, "baksmali.jar") output = os.path.join(app_dir, "smali_source/") args = [ settings.JAVA_PATH + "java", "-jar", bs_path, dex_path, "-o", output, ] subprocess.call(args) except: PrintException("Converting DEX to SMALI")
def dex_2_smali(app_dir, tools_dir): """Run dex2smali""" try: logger.info("DEX -> SMALI") dexes = get_dex_files(app_dir) for dex_path in dexes: logger.info("Converting " + dex_path + " to Smali Code") if len(settings.BACKSMALI_BINARY) > 0 and isFileExists( settings.BACKSMALI_BINARY ): bs_path = settings.BACKSMALI_BINARY else: bs_path = os.path.join(tools_dir, "baksmali.jar") output = os.path.join(app_dir, "smali_source/") args = [ settings.JAVA_PATH + "java", "-jar", bs_path, dex_path, "-o", output, ] subprocess.call(args) except: PrintException("[ERROR] Converting DEX to SMALI")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def jar_2_java(app_dir, tools_dir): """Conver jar to java.""" try: logger.info("JAR -> JAVA") jar_files = get_jar_files(app_dir) output = os.path.join(app_dir, "java_source/") for jar_path in jar_files: logger.info("Decompiling {} to Java Code".format(jar_path)) if settings.DECOMPILER == "jd-core": if len(settings.JD_CORE_DECOMPILER_BINARY) > 0 and isFileExists( settings.JD_CORE_DECOMPILER_BINARY ): jd_path = settings.JD_CORE_DECOMPILER_BINARY else: jd_path = os.path.join(tools_dir, "jd-core.jar") args = [settings.JAVA_PATH + "java", "-jar", jd_path, jar_path, output] elif settings.DECOMPILER == "cfr": if len(settings.CFR_DECOMPILER_BINARY) > 0 and isFileExists( settings.CFR_DECOMPILER_BINARY ): jd_path = settings.CFR_DECOMPILER_BINARY else: jd_path = os.path.join(tools_dir, "cfr_0_132.jar") args = [ settings.JAVA_PATH + "java", "-jar", jd_path, jar_path, "--outputdir", output, "--silent", "true", ] elif settings.DECOMPILER == "procyon": if len(settings.PROCYON_DECOMPILER_BINARY) > 0 and isFileExists( settings.PROCYON_DECOMPILER_BINARY ): pd_path = settings.PROCYON_DECOMPILER_BINARY else: pd_path = os.path.join(tools_dir, "procyon-decompiler-0.5.30.jar") args = [ settings.JAVA_PATH + "java", "-jar", pd_path, jar_path, "-o", output, ] subprocess.call(args) except: PrintException("Converting JAR to JAVA")
def jar_2_java(app_dir, tools_dir): """Conver jar to java.""" try: logger.info("JAR -> JAVA") jar_files = get_jar_files(app_dir) output = os.path.join(app_dir, "java_source/") for jar_path in jar_files: logger.info("Decompiling {} to Java Code".format(jar_path)) if settings.DECOMPILER == "jd-core": if len(settings.JD_CORE_DECOMPILER_BINARY) > 0 and isFileExists( settings.JD_CORE_DECOMPILER_BINARY ): jd_path = settings.JD_CORE_DECOMPILER_BINARY else: jd_path = os.path.join(tools_dir, "jd-core.jar") args = [settings.JAVA_PATH + "java", "-jar", jd_path, jar_path, output] elif settings.DECOMPILER == "cfr": if len(settings.CFR_DECOMPILER_BINARY) > 0 and isFileExists( settings.CFR_DECOMPILER_BINARY ): jd_path = settings.CFR_DECOMPILER_BINARY else: jd_path = os.path.join(tools_dir, "cfr_0_132.jar") args = [ settings.JAVA_PATH + "java", "-jar", jd_path, jar_path, "--outputdir", output, "--silent", "true", ] elif settings.DECOMPILER == "procyon": if len(settings.PROCYON_DECOMPILER_BINARY) > 0 and isFileExists( settings.PROCYON_DECOMPILER_BINARY ): pd_path = settings.PROCYON_DECOMPILER_BINARY else: pd_path = os.path.join(tools_dir, "procyon-decompiler-0.5.30.jar") args = [ settings.JAVA_PATH + "java", "-jar", pd_path, jar_path, "-o", output, ] subprocess.call(args) except: PrintException("[ERROR] Converting JAR to JAVA")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def get_context_from_db_entry(db_entry: QuerySet) -> dict: """Return the context for APK/ZIP from DB""" try: logger.info("Analysis is already Done. Fetching data from the DB...") context = { "title": db_entry[0].TITLE, "name": db_entry[0].APP_NAME, "size": db_entry[0].SIZE, "md5": db_entry[0].MD5, "sha1": db_entry[0].SHA1, "sha256": db_entry[0].SHA256, "packagename": db_entry[0].PACKAGENAME, "mainactivity": db_entry[0].MAINACTIVITY, "targetsdk": db_entry[0].TARGET_SDK, "maxsdk": db_entry[0].MAX_SDK, "minsdk": db_entry[0].MIN_SDK, "androvername": db_entry[0].ANDROVERNAME, "androver": db_entry[0].ANDROVER, "manifest": python_list(db_entry[0].MANIFEST_ANAL), "permissions": python_dict(db_entry[0].PERMISSIONS), "binary_analysis": python_list(db_entry[0].BIN_ANALYSIS), "files": python_list(db_entry[0].FILES), "certz": db_entry[0].CERTZ, "icon_hidden": db_entry[0].ICON_HIDDEN, "icon_found": db_entry[0].ICON_FOUND, "activities": python_list(db_entry[0].ACTIVITIES), "receivers": python_list(db_entry[0].RECEIVERS), "providers": python_list(db_entry[0].PROVIDERS), "services": python_list(db_entry[0].SERVICES), "libraries": python_list(db_entry[0].LIBRARIES), "browsable_activities": python_dict(db_entry[0].BROWSABLE), "act_count": db_entry[0].CNT_ACT, "prov_count": db_entry[0].CNT_PRO, "serv_count": db_entry[0].CNT_SER, "bro_count": db_entry[0].CNT_BRO, "certinfo": db_entry[0].CERT_INFO, "issued": db_entry[0].ISSUED, "sha256Digest": db_entry[0].SHA256DIGEST, "api": python_dict(db_entry[0].API), "findings": python_dict(db_entry[0].DANG), "urls": python_list(db_entry[0].URLS), "domains": python_dict(db_entry[0].DOMAINS), "emails": python_list(db_entry[0].EMAILS), "strings": python_list(db_entry[0].STRINGS), "zipped": db_entry[0].ZIPPED, "mani": db_entry[0].MANI, "e_act": db_entry[0].E_ACT, "e_ser": db_entry[0].E_SER, "e_bro": db_entry[0].E_BRO, "e_cnt": db_entry[0].E_CNT, "apkid": python_dict(db_entry[0].APK_ID), } return context except: PrintException("Fetching from DB")
def get_context_from_db_entry(db_entry: QuerySet) -> dict: """Return the context for APK/ZIP from DB""" try: logger.info("Analysis is already Done. Fetching data from the DB...") context = { "title": db_entry[0].TITLE, "name": db_entry[0].APP_NAME, "size": db_entry[0].SIZE, "md5": db_entry[0].MD5, "sha1": db_entry[0].SHA1, "sha256": db_entry[0].SHA256, "packagename": db_entry[0].PACKAGENAME, "mainactivity": db_entry[0].MAINACTIVITY, "targetsdk": db_entry[0].TARGET_SDK, "maxsdk": db_entry[0].MAX_SDK, "minsdk": db_entry[0].MIN_SDK, "androvername": db_entry[0].ANDROVERNAME, "androver": db_entry[0].ANDROVER, "manifest": python_list(db_entry[0].MANIFEST_ANAL), "permissions": python_dict(db_entry[0].PERMISSIONS), "binary_analysis": python_list(db_entry[0].BIN_ANALYSIS), "files": python_list(db_entry[0].FILES), "certz": db_entry[0].CERTZ, "icon_hidden": db_entry[0].ICON_HIDDEN, "icon_found": db_entry[0].ICON_FOUND, "activities": python_list(db_entry[0].ACTIVITIES), "receivers": python_list(db_entry[0].RECEIVERS), "providers": python_list(db_entry[0].PROVIDERS), "services": python_list(db_entry[0].SERVICES), "libraries": python_list(db_entry[0].LIBRARIES), "browsable_activities": python_dict(db_entry[0].BROWSABLE), "act_count": db_entry[0].CNT_ACT, "prov_count": db_entry[0].CNT_PRO, "serv_count": db_entry[0].CNT_SER, "bro_count": db_entry[0].CNT_BRO, "certinfo": db_entry[0].CERT_INFO, "issued": db_entry[0].ISSUED, "sha256Digest": db_entry[0].SHA256DIGEST, "api": python_dict(db_entry[0].API), "findings": python_dict(db_entry[0].DANG), "urls": python_list(db_entry[0].URLS), "domains": python_dict(db_entry[0].DOMAINS), "emails": python_list(db_entry[0].EMAILS), "strings": python_list(db_entry[0].STRINGS), "zipped": db_entry[0].ZIPPED, "mani": db_entry[0].MANI, "e_act": db_entry[0].E_ACT, "e_ser": db_entry[0].E_SER, "e_bro": db_entry[0].E_BRO, "e_cnt": db_entry[0].E_CNT, "apkid": python_dict(db_entry[0].APK_ID), } return context except: PrintException("[ERROR] Fetching from DB")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def get_context_from_analysis( app_dic, man_data_dic, man_an_dic, code_an_dic, cert_dic, bin_anal, apk_id ) -> dict: """Get the context for APK/ZIP from analysis results""" try: context = { "title": "Static Analysis", "name": app_dic["app_name"], "size": app_dic["size"], "md5": app_dic["md5"], "sha1": app_dic["sha1"], "sha256": app_dic["sha256"], "packagename": man_data_dic["packagename"], "mainactivity": man_data_dic["mainactivity"], "targetsdk": man_data_dic["target_sdk"], "maxsdk": man_data_dic["max_sdk"], "minsdk": man_data_dic["min_sdk"], "androvername": man_data_dic["androvername"], "androver": man_data_dic["androver"], "manifest": man_an_dic["manifest_anal"], "permissions": man_an_dic["permissons"], "binary_analysis": bin_anal, "files": app_dic["files"], "certz": app_dic["certz"], "icon_hidden": app_dic["icon_hidden"], "icon_found": app_dic["icon_found"], "activities": man_data_dic["activities"], "receivers": man_data_dic["receivers"], "providers": man_data_dic["providers"], "services": man_data_dic["services"], "libraries": man_data_dic["libraries"], "browsable_activities": man_an_dic["browsable_activities"], "act_count": man_an_dic["cnt_act"], "prov_count": man_an_dic["cnt_pro"], "serv_count": man_an_dic["cnt_ser"], "bro_count": man_an_dic["cnt_bro"], "certinfo": cert_dic["cert_info"], "issued": cert_dic["issued"], "sha256Digest": cert_dic["sha256Digest"], "api": code_an_dic["api"], "findings": code_an_dic["findings"], "urls": code_an_dic["urls"], "domains": code_an_dic["domains"], "emails": code_an_dic["emails"], "strings": app_dic["strings"], "zipped": app_dic["zipped"], "mani": app_dic["mani"], "e_act": man_an_dic["exported_cnt"]["act"], "e_ser": man_an_dic["exported_cnt"]["ser"], "e_bro": man_an_dic["exported_cnt"]["bro"], "e_cnt": man_an_dic["exported_cnt"]["cnt"], "apkid": apk_id, } return context except: PrintException("Rendering to Template")
def get_context_from_analysis( app_dic, man_data_dic, man_an_dic, code_an_dic, cert_dic, bin_anal, apk_id ) -> dict: """Get the context for APK/ZIP from analysis results""" try: context = { "title": "Static Analysis", "name": app_dic["app_name"], "size": app_dic["size"], "md5": app_dic["md5"], "sha1": app_dic["sha1"], "sha256": app_dic["sha256"], "packagename": man_data_dic["packagename"], "mainactivity": man_data_dic["mainactivity"], "targetsdk": man_data_dic["target_sdk"], "maxsdk": man_data_dic["max_sdk"], "minsdk": man_data_dic["min_sdk"], "androvername": man_data_dic["androvername"], "androver": man_data_dic["androver"], "manifest": man_an_dic["manifest_anal"], "permissions": man_an_dic["permissons"], "binary_analysis": bin_anal, "files": app_dic["files"], "certz": app_dic["certz"], "icon_hidden": app_dic["icon_hidden"], "icon_found": app_dic["icon_found"], "activities": man_data_dic["activities"], "receivers": man_data_dic["receivers"], "providers": man_data_dic["providers"], "services": man_data_dic["services"], "libraries": man_data_dic["libraries"], "browsable_activities": man_an_dic["browsable_activities"], "act_count": man_an_dic["cnt_act"], "prov_count": man_an_dic["cnt_pro"], "serv_count": man_an_dic["cnt_ser"], "bro_count": man_an_dic["cnt_bro"], "certinfo": cert_dic["cert_info"], "issued": cert_dic["issued"], "sha256Digest": cert_dic["sha256Digest"], "api": code_an_dic["api"], "findings": code_an_dic["findings"], "urls": code_an_dic["urls"], "domains": code_an_dic["domains"], "emails": code_an_dic["emails"], "strings": app_dic["strings"], "zipped": app_dic["zipped"], "mani": app_dic["mani"], "e_act": man_an_dic["exported_cnt"]["act"], "e_ser": man_an_dic["exported_cnt"]["ser"], "e_bro": man_an_dic["exported_cnt"]["bro"], "e_cnt": man_an_dic["exported_cnt"]["cnt"], "apkid": apk_id, } return context except: PrintException("[ERROR] Rendering to Template")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def update_db_entry( app_dic, man_data_dic, man_an_dic, code_an_dic, cert_dic, bin_anal, apk_id ) -> None: """Update an APK/ZIP DB entry""" try: # pylint: disable=E1101 StaticAnalyzerAndroid.objects.filter(MD5=app_dic["md5"]).update( TITLE="Static Analysis", APP_NAME=app_dic["app_name"], SIZE=app_dic["size"], MD5=app_dic["md5"], SHA1=app_dic["sha1"], SHA256=app_dic["sha256"], PACKAGENAME=man_data_dic["packagename"], MAINACTIVITY=man_data_dic["mainactivity"], TARGET_SDK=man_data_dic["target_sdk"], MAX_SDK=man_data_dic["max_sdk"], MIN_SDK=man_data_dic["min_sdk"], ANDROVERNAME=man_data_dic["androvername"], ANDROVER=man_data_dic["androver"], MANIFEST_ANAL=man_an_dic["manifest_anal"], PERMISSIONS=man_an_dic["permissons"], BIN_ANALYSIS=bin_anal, FILES=app_dic["files"], CERTZ=app_dic["certz"], ICON_HIDDEN=app_dic["icon_hidden"], ICON_FOUND=app_dic["icon_found"], ACTIVITIES=man_data_dic["activities"], RECEIVERS=man_data_dic["receivers"], PROVIDERS=man_data_dic["providers"], SERVICES=man_data_dic["services"], LIBRARIES=man_data_dic["libraries"], BROWSABLE=man_an_dic["browsable_activities"], CNT_ACT=man_an_dic["cnt_act"], CNT_PRO=man_an_dic["cnt_pro"], CNT_SER=man_an_dic["cnt_ser"], CNT_BRO=man_an_dic["cnt_bro"], CERT_INFO=cert_dic["cert_info"], ISSUED=cert_dic["issued"], SHA256DIGEST=cert_dic["sha256Digest"], API=code_an_dic["api"], DANG=code_an_dic["findings"], URLS=code_an_dic["urls"], DOMAINS=code_an_dic["domains"], EMAILS=code_an_dic["emails"], STRINGS=app_dic["strings"], ZIPPED=app_dic["zipped"], MANI=app_dic["mani"], EXPORTED_ACT=man_an_dic["exported_act"], E_ACT=man_an_dic["exported_cnt"]["act"], E_SER=man_an_dic["exported_cnt"]["ser"], E_BRO=man_an_dic["exported_cnt"]["bro"], E_CNT=man_an_dic["exported_cnt"]["cnt"], APK_ID=apk_id, ) except: PrintException("Updating DB")
def update_db_entry( app_dic, man_data_dic, man_an_dic, code_an_dic, cert_dic, bin_anal, apk_id ) -> None: """Update an APK/ZIP DB entry""" try: # pylint: disable=E1101 StaticAnalyzerAndroid.objects.filter(MD5=app_dic["md5"]).update( TITLE="Static Analysis", APP_NAME=app_dic["app_name"], SIZE=app_dic["size"], MD5=app_dic["md5"], SHA1=app_dic["sha1"], SHA256=app_dic["sha256"], PACKAGENAME=man_data_dic["packagename"], MAINACTIVITY=man_data_dic["mainactivity"], TARGET_SDK=man_data_dic["target_sdk"], MAX_SDK=man_data_dic["max_sdk"], MIN_SDK=man_data_dic["min_sdk"], ANDROVERNAME=man_data_dic["androvername"], ANDROVER=man_data_dic["androver"], MANIFEST_ANAL=man_an_dic["manifest_anal"], PERMISSIONS=man_an_dic["permissons"], BIN_ANALYSIS=bin_anal, FILES=app_dic["files"], CERTZ=app_dic["certz"], ICON_HIDDEN=app_dic["icon_hidden"], ICON_FOUND=app_dic["icon_found"], ACTIVITIES=man_data_dic["activities"], RECEIVERS=man_data_dic["receivers"], PROVIDERS=man_data_dic["providers"], SERVICES=man_data_dic["services"], LIBRARIES=man_data_dic["libraries"], BROWSABLE=man_an_dic["browsable_activities"], CNT_ACT=man_an_dic["cnt_act"], CNT_PRO=man_an_dic["cnt_pro"], CNT_SER=man_an_dic["cnt_ser"], CNT_BRO=man_an_dic["cnt_bro"], CERT_INFO=cert_dic["cert_info"], ISSUED=cert_dic["issued"], SHA256DIGEST=cert_dic["sha256Digest"], API=code_an_dic["api"], DANG=code_an_dic["findings"], URLS=code_an_dic["urls"], DOMAINS=code_an_dic["domains"], EMAILS=code_an_dic["emails"], STRINGS=app_dic["strings"], ZIPPED=app_dic["zipped"], MANI=app_dic["mani"], EXPORTED_ACT=man_an_dic["exported_act"], E_ACT=man_an_dic["exported_cnt"]["act"], E_SER=man_an_dic["exported_cnt"]["ser"], E_BRO=man_an_dic["exported_cnt"]["bro"], E_CNT=man_an_dic["exported_cnt"]["cnt"], APK_ID=apk_id, ) except: PrintException("[ERROR] Updating DB")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def create_db_entry( app_dic, man_data_dic, man_an_dic, code_an_dic, cert_dic, bin_anal, apk_id ) -> None: """Create a new DB-Entry for APK/ZIP""" try: static_db = StaticAnalyzerAndroid( TITLE="Static Analysis", APP_NAME=app_dic["app_name"], SIZE=app_dic["size"], MD5=app_dic["md5"], SHA1=app_dic["sha1"], SHA256=app_dic["sha256"], PACKAGENAME=man_data_dic["packagename"], MAINACTIVITY=man_data_dic["mainactivity"], TARGET_SDK=man_data_dic["target_sdk"], MAX_SDK=man_data_dic["max_sdk"], MIN_SDK=man_data_dic["min_sdk"], ANDROVERNAME=man_data_dic["androvername"], ANDROVER=man_data_dic["androver"], MANIFEST_ANAL=man_an_dic["manifest_anal"], PERMISSIONS=man_an_dic["permissons"], BIN_ANALYSIS=bin_anal, FILES=app_dic["files"], CERTZ=app_dic["certz"], ICON_HIDDEN=app_dic["icon_hidden"], ICON_FOUND=app_dic["icon_found"], ACTIVITIES=man_data_dic["activities"], RECEIVERS=man_data_dic["receivers"], PROVIDERS=man_data_dic["providers"], SERVICES=man_data_dic["services"], LIBRARIES=man_data_dic["libraries"], BROWSABLE=man_an_dic["browsable_activities"], CNT_ACT=man_an_dic["cnt_act"], CNT_PRO=man_an_dic["cnt_pro"], CNT_SER=man_an_dic["cnt_ser"], CNT_BRO=man_an_dic["cnt_bro"], CERT_INFO=cert_dic["cert_info"], ISSUED=cert_dic["issued"], SHA256DIGEST=cert_dic["sha256Digest"], API=code_an_dic["api"], DANG=code_an_dic["findings"], URLS=code_an_dic["urls"], DOMAINS=code_an_dic["domains"], EMAILS=code_an_dic["emails"], STRINGS=app_dic["strings"], ZIPPED=app_dic["zipped"], MANI=app_dic["mani"], EXPORTED_ACT=man_an_dic["exported_act"], E_ACT=man_an_dic["exported_cnt"]["act"], E_SER=man_an_dic["exported_cnt"]["ser"], E_BRO=man_an_dic["exported_cnt"]["bro"], E_CNT=man_an_dic["exported_cnt"]["cnt"], APK_ID=apk_id, ) static_db.save() except: PrintException("Saving to DB")
def create_db_entry( app_dic, man_data_dic, man_an_dic, code_an_dic, cert_dic, bin_anal, apk_id ) -> None: """Create a new DB-Entry for APK/ZIP""" try: static_db = StaticAnalyzerAndroid( TITLE="Static Analysis", APP_NAME=app_dic["app_name"], SIZE=app_dic["size"], MD5=app_dic["md5"], SHA1=app_dic["sha1"], SHA256=app_dic["sha256"], PACKAGENAME=man_data_dic["packagename"], MAINACTIVITY=man_data_dic["mainactivity"], TARGET_SDK=man_data_dic["target_sdk"], MAX_SDK=man_data_dic["max_sdk"], MIN_SDK=man_data_dic["min_sdk"], ANDROVERNAME=man_data_dic["androvername"], ANDROVER=man_data_dic["androver"], MANIFEST_ANAL=man_an_dic["manifest_anal"], PERMISSIONS=man_an_dic["permissons"], BIN_ANALYSIS=bin_anal, FILES=app_dic["files"], CERTZ=app_dic["certz"], ICON_HIDDEN=app_dic["icon_hidden"], ICON_FOUND=app_dic["icon_found"], ACTIVITIES=man_data_dic["activities"], RECEIVERS=man_data_dic["receivers"], PROVIDERS=man_data_dic["providers"], SERVICES=man_data_dic["services"], LIBRARIES=man_data_dic["libraries"], BROWSABLE=man_an_dic["browsable_activities"], CNT_ACT=man_an_dic["cnt_act"], CNT_PRO=man_an_dic["cnt_pro"], CNT_SER=man_an_dic["cnt_ser"], CNT_BRO=man_an_dic["cnt_bro"], CERT_INFO=cert_dic["cert_info"], ISSUED=cert_dic["issued"], SHA256DIGEST=cert_dic["sha256Digest"], API=code_an_dic["api"], DANG=code_an_dic["findings"], URLS=code_an_dic["urls"], DOMAINS=code_an_dic["domains"], EMAILS=code_an_dic["emails"], STRINGS=app_dic["strings"], ZIPPED=app_dic["zipped"], MANI=app_dic["mani"], EXPORTED_ACT=man_an_dic["exported_act"], E_ACT=man_an_dic["exported_cnt"]["act"], E_SER=man_an_dic["exported_cnt"]["ser"], E_BRO=man_an_dic["exported_cnt"]["bro"], E_CNT=man_an_dic["exported_cnt"]["cnt"], APK_ID=apk_id, ) static_db.save() except: PrintException("[ERROR] Saving to DB")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def run(request): """Find in source files.""" try: match = re.match("^[0-9a-f]{32}$", request.POST["md5"]) if match: md5 = request.POST["md5"] query = request.POST["q"] code = request.POST["code"] matches = [] if code == "java": src = os.path.join(settings.UPLD_DIR, md5 + "/java_source/") ext = ".java" elif code == "smali": src = os.path.join(settings.UPLD_DIR, md5 + "/smali_source/") ext = ".smali" else: return print_n_send_error_response( request, "Only Java/Smali files are allowed" ) # pylint: disable=unused-variable # Needed by os.walk for dir_name, sub_dir, files in os.walk(src): for jfile in files: if jfile.endswith(ext): file_path = os.path.join(src, dir_name, jfile) if "+" in jfile: fp2 = os.path.join(src, dir_name, jfile.replace("+", "x")) shutil.move(file_path, fp2) file_path = fp2 fileparam = file_path.replace(src, "") with io.open( file_path, mode="r", encoding="utf8", errors="ignore" ) as file_pointer: dat = file_pointer.read() if query in dat: matches.append( "<a href='../ViewSource/?file=" + escape(fileparam) + "&md5=" + md5 + "&type=apk'>" + escape(fileparam) + "</a>" ) flz = len(matches) context = { "title": "Search Results", "matches": matches, "term": query, "found": str(flz), } template = "general/search.html" return render(request, template, context) except: PrintException("Searching Failed") return print_n_send_error_response(request, "Searching Failed")
def run(request): """Find in source files.""" try: match = re.match("^[0-9a-f]{32}$", request.POST["md5"]) if match: md5 = request.POST["md5"] query = request.POST["q"] code = request.POST["code"] matches = [] if code == "java": src = os.path.join(settings.UPLD_DIR, md5 + "/java_source/") ext = ".java" elif code == "smali": src = os.path.join(settings.UPLD_DIR, md5 + "/smali_source/") ext = ".smali" else: return HttpResponseRedirect("/error/") # pylint: disable=unused-variable # Needed by os.walk for dir_name, sub_dir, files in os.walk(src): for jfile in files: if jfile.endswith(ext): file_path = os.path.join(src, dir_name, jfile) if "+" in jfile: fp2 = os.path.join(src, dir_name, jfile.replace("+", "x")) shutil.move(file_path, fp2) file_path = fp2 fileparam = file_path.replace(src, "") with io.open( file_path, mode="r", encoding="utf8", errors="ignore" ) as file_pointer: dat = file_pointer.read() if query in dat: matches.append( "<a href='../ViewSource/?file=" + escape(fileparam) + "&md5=" + md5 + "&type=apk'>" + escape(fileparam) + "</a>" ) flz = len(matches) context = { "title": "Search Results", "matches": matches, "term": query, "found": str(flz), } template = "general/search.html" return render(request, template, context) except: PrintException("[ERROR] Searching Failed") return HttpResponseRedirect("/error/")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def find_icon_path_zip(res_dir, icon_paths_from_manifest): """Tries to find an icon, based on paths fetched from the manifest and by global search returns an empty string on fail or a full path""" global KNOWN_MIPMAP_SIZES try: logger.info("Guessing icon path") for icon_path in icon_paths_from_manifest: if icon_path.startswith("@"): path_array = icon_path.strip("@").split(os.sep) rel_path = os.sep.join(path_array[1:]) for size_str in KNOWN_MIPMAP_SIZES: tmp_path = os.path.join( res_dir, path_array[0] + size_str, rel_path + ".png" ) if os.path.exists(tmp_path): return tmp_path else: if icon_path.starswith("res/") or icon_path.starswith("/res/"): stripped_relative_path = icon_path.strip( "/res" ) # Works for neither /res and res full_path = os.path.join(res_dir, stripped_relative_path) if os.path.exists(full_path): return full_path full_path += ".png" if os.path.exists(full_path): return full_path file_name = icon_path.split(os.sep)[-1] if file_name.endswith(".png"): file_name += ".png" for guess in search_folder(res_dir, file_name): if os.path.exists(guess): return guess # If didn't find, try the default name.. returns empty if not find return guess_icon_path(res_dir) except: PrintException("Guessing icon path")
def find_icon_path_zip(res_dir, icon_paths_from_manifest): """Tries to find an icon, based on paths fetched from the manifest and by global search returns an empty string on fail or a full path""" global KNOWN_MIPMAP_SIZES try: logger.info("Guessing icon path") for icon_path in icon_paths_from_manifest: if icon_path.startswith("@"): path_array = icon_path.strip("@").split(os.sep) rel_path = os.sep.join(path_array[1:]) for size_str in KNOWN_MIPMAP_SIZES: tmp_path = os.path.join( res_dir, path_array[0] + size_str, rel_path + ".png" ) if os.path.exists(tmp_path): return tmp_path else: if icon_path.starswith("res/") or icon_path.starswith("/res/"): stripped_relative_path = icon_path.strip( "/res" ) # Works for neither /res and res full_path = os.path.join(res_dir, stripped_relative_path) if os.path.exists(full_path): return full_path full_path += ".png" if os.path.exists(full_path): return full_path file_name = icon_path.split(os.sep)[-1] if file_name.endswith(".png"): file_name += ".png" for guess in search_folder(res_dir, file_name): if os.path.exists(guess): return guess # If didn't find, try the default name.. returns empty if not find return guess_icon_path(res_dir) except: PrintException("[ERROR] Guessing icon path")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def get_icon(apk_path, res_dir): """Returns a dict with isHidden boolean and a relative path path is a full path (not relative to resource folder)""" try: logger.info("Fetching icon path") a = apk.APK(apk_path) icon_resolution = 0xFFFE - 1 icon_name = a.get_app_icon(max_dpi=icon_resolution) if icon_name: return { "path": os.path.join(os.path.dirname(apk_path), icon_name), "hidden": False, } return {"path": guess_icon_path(res_dir), "hidden": True} except: PrintException("Fetching icon function")
def get_icon(apk_path, res_dir): """Returns a dict with isHidden boolean and a relative path path is a full path (not relative to resource folder)""" try: logger.info("Fetching icon path") a = apk.APK(apk_path) icon_resolution = 0xFFFE - 1 icon_name = a.get_app_icon(max_dpi=icon_resolution) if icon_name: return { "path": os.path.join(os.path.dirname(apk_path), icon_name), "hidden": False, } return {"path": guess_icon_path(res_dir), "hidden": True} except: PrintException("[ERROR] Fetching icon function")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def run(request): """Show the java code.""" try: logger.debug("showing java code for request : {}".format(request)) match = re.match("^[0-9a-f]{32}$", request.GET["md5"]) typ = request.GET["type"] if match: md5 = request.GET["md5"] if typ == "eclipse": src = os.path.join(settings.UPLD_DIR, md5 + "/src/") elif typ == "studio": src = os.path.join(settings.UPLD_DIR, md5 + "/app/src/main/java/") elif typ == "apk": src = os.path.join(settings.UPLD_DIR, md5 + "/java_source/") else: return print_n_send_error_response( request, "Invalid Directory Structure" ) html = "" # pylint: disable=unused-variable # Needed by os.walk for dir_name, sub_dir, files in os.walk(src): for jfile in files: if jfile.endswith(".java"): file_path = os.path.join(src, dir_name, jfile) if "+" in jfile: fp2 = os.path.join(src, dir_name, jfile.replace("+", "x")) shutil.move(file_path, fp2) file_path = fp2 fileparam = file_path.replace(src, "") if ( any( re.search(cls, fileparam) for cls in settings.SKIP_CLASSES ) is False ): html += ( "<tr><td><a href='../ViewSource/?file=" + escape(fileparam) + "&md5=" + md5 + "&type=" + typ + "'>" + escape(fileparam) + "</a></td></tr>" ) context = { "title": "Java Source", "files": html, "md5": md5, "type": typ, } template = "static_analysis/java.html" return render(request, template, context) except: PrintException("Getting Java Files") return print_n_send_error_response(request, "Error Getting Java Files")
def run(request): """Show the java code.""" try: logger.debug("showing java code for request : {}".format(request)) match = re.match("^[0-9a-f]{32}$", request.GET["md5"]) typ = request.GET["type"] if match: md5 = request.GET["md5"] if typ == "eclipse": src = os.path.join(settings.UPLD_DIR, md5 + "/src/") elif typ == "studio": src = os.path.join(settings.UPLD_DIR, md5 + "/app/src/main/java/") elif typ == "apk": src = os.path.join(settings.UPLD_DIR, md5 + "/java_source/") else: return HttpResponseRedirect("/error/") html = "" # pylint: disable=unused-variable # Needed by os.walk for dir_name, sub_dir, files in os.walk(src): for jfile in files: if jfile.endswith(".java"): file_path = os.path.join(src, dir_name, jfile) if "+" in jfile: fp2 = os.path.join(src, dir_name, jfile.replace("+", "x")) shutil.move(file_path, fp2) file_path = fp2 fileparam = file_path.replace(src, "") if ( any( re.search(cls, fileparam) for cls in settings.SKIP_CLASSES ) is False ): html += ( "<tr><td><a href='../ViewSource/?file=" + escape(fileparam) + "&md5=" + md5 + "&type=" + typ + "'>" + escape(fileparam) + "</a></td></tr>" ) context = { "title": "Java Source", "files": html, "md5": md5, "type": typ, } template = "static_analysis/java.html" return render(request, template, context) except: PrintException("[ERROR] Getting Java Files") return HttpResponseRedirect("/error/")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def get_manifest(app_path, app_dir, tools_dir, typ, binary): """Get the manifest file.""" try: manifest = None dat = read_manifest(app_dir, app_path, tools_dir, typ, binary) try: logger.info("Parsing AndroidManifest.xml") manifest = minidom.parseString(dat) except: PrintException( "apktool failed to extract AndroidManifest.xml or parsing failed" ) manifest = minidom.parseString( ( r'<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android=' r'"http://schemas.android.com/apk/res/android" android:versionCode="Failed" ' r'android:versionName="Failed" package="Failed" ' r'platformBuildVersionCode="Failed" ' r'platformBuildVersionName="Failed XML Parsing" ></manifest>' ) ) logger.warning("Using Fake XML to continue the Analysis") return manifest except: PrintException("Parsing Manifest file")
def get_manifest(app_path, app_dir, tools_dir, typ, binary): """Get the manifest file.""" try: manifest = None dat = read_manifest(app_dir, app_path, tools_dir, typ, binary) try: logger.info("Parsing AndroidManifest.xml") manifest = minidom.parseString(dat) except: PrintException( "[ERROR] apktool failed to extract AndroidManifest.xml or parsing failed" ) manifest = minidom.parseString( ( r'<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android=' r'"http://schemas.android.com/apk/res/android" android:versionCode="Failed" ' r'android:versionName="Failed" package="Failed" ' r'platformBuildVersionCode="Failed" ' r'platformBuildVersionName="Failed XML Parsing" ></manifest>' ) ) logger.warning("Using Fake XML to continue the Analysis") return manifest except: PrintException("[ERROR] Parsing Manifest file")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def manifest_data(mfxml): """Extract manifest data.""" try: logger.info("Extracting Manifest Data") svc = [] act = [] brd = [] cnp = [] lib = [] perm = [] cat = [] icons = [] dvm_perm = {} package = "" minsdk = "" maxsdk = "" targetsdk = "" mainact = "" androidversioncode = "" androidversionname = "" applications = mfxml.getElementsByTagName("application") permissions = mfxml.getElementsByTagName("uses-permission") manifest = mfxml.getElementsByTagName("manifest") activities = mfxml.getElementsByTagName("activity") services = mfxml.getElementsByTagName("service") providers = mfxml.getElementsByTagName("provider") receivers = mfxml.getElementsByTagName("receiver") libs = mfxml.getElementsByTagName("uses-library") sdk = mfxml.getElementsByTagName("uses-sdk") categories = mfxml.getElementsByTagName("category") for node in sdk: minsdk = node.getAttribute("android:minSdkVersion") maxsdk = node.getAttribute("android:maxSdkVersion") # Esteve 08.08.2016 - begin - If android:targetSdkVersion is not set, # the default value is the one of the android:minSdkVersion # targetsdk=node.getAttribute("android:targetSdkVersion") if node.getAttribute("android:targetSdkVersion"): targetsdk = node.getAttribute("android:targetSdkVersion") else: targetsdk = node.getAttribute("android:minSdkVersion") # End for node in manifest: package = node.getAttribute("package") androidversioncode = node.getAttribute("android:versionCode") androidversionname = node.getAttribute("android:versionName") for activity in activities: act_2 = activity.getAttribute("android:name") act.append(act_2) if len(mainact) < 1: # ^ Fix for Shitty Manifest with more than one MAIN for sitem in activity.getElementsByTagName("action"): val = sitem.getAttribute("android:name") if val == "android.intent.action.MAIN": mainact = activity.getAttribute("android:name") if mainact == "": for sitem in activity.getElementsByTagName("category"): val = sitem.getAttribute("android:name") if val == "android.intent.category.LAUNCHER": mainact = activity.getAttribute("android:name") for service in services: service_name = service.getAttribute("android:name") svc.append(service_name) for provider in providers: provider_name = provider.getAttribute("android:name") cnp.append(provider_name) for receiver in receivers: rec = receiver.getAttribute("android:name") brd.append(rec) for _lib in libs: libary = _lib.getAttribute("android:name") lib.append(libary) for category in categories: cat.append(category.getAttribute("android:name")) for application in applications: try: icon_path = application.getAttribute("android:icon") icons.append(icon_path) except: continue # No icon attribute? for permission in permissions: perm.append(permission.getAttribute("android:name")) for i in perm: prm = i pos = i.rfind(".") if pos != -1: prm = i[pos + 1 :] try: dvm_perm[i] = DVM_PERMISSIONS["MANIFEST_PERMISSION"][prm] except KeyError: dvm_perm[i] = [ "dangerous", "Unknown permission from android reference", "Unknown permission from android reference", ] man_data_dic = { "services": svc, "activities": act, "receivers": brd, "providers": cnp, "libraries": lib, "categories": cat, "perm": dvm_perm, "packagename": package, "mainactivity": mainact, "min_sdk": minsdk, "max_sdk": maxsdk, "target_sdk": targetsdk, "androver": androidversioncode, "androvername": androidversionname, "icons": icons, } return man_data_dic except: PrintException("Extracting Manifest Data")
def manifest_data(mfxml): """Extract manifest data.""" try: logger.info("Extracting Manifest Data") svc = [] act = [] brd = [] cnp = [] lib = [] perm = [] cat = [] icons = [] dvm_perm = {} package = "" minsdk = "" maxsdk = "" targetsdk = "" mainact = "" androidversioncode = "" androidversionname = "" applications = mfxml.getElementsByTagName("application") permissions = mfxml.getElementsByTagName("uses-permission") manifest = mfxml.getElementsByTagName("manifest") activities = mfxml.getElementsByTagName("activity") services = mfxml.getElementsByTagName("service") providers = mfxml.getElementsByTagName("provider") receivers = mfxml.getElementsByTagName("receiver") libs = mfxml.getElementsByTagName("uses-library") sdk = mfxml.getElementsByTagName("uses-sdk") categories = mfxml.getElementsByTagName("category") for node in sdk: minsdk = node.getAttribute("android:minSdkVersion") maxsdk = node.getAttribute("android:maxSdkVersion") # Esteve 08.08.2016 - begin - If android:targetSdkVersion is not set, # the default value is the one of the android:minSdkVersion # targetsdk=node.getAttribute("android:targetSdkVersion") if node.getAttribute("android:targetSdkVersion"): targetsdk = node.getAttribute("android:targetSdkVersion") else: targetsdk = node.getAttribute("android:minSdkVersion") # End for node in manifest: package = node.getAttribute("package") androidversioncode = node.getAttribute("android:versionCode") androidversionname = node.getAttribute("android:versionName") for activity in activities: act_2 = activity.getAttribute("android:name") act.append(act_2) if len(mainact) < 1: # ^ Fix for Shitty Manifest with more than one MAIN for sitem in activity.getElementsByTagName("action"): val = sitem.getAttribute("android:name") if val == "android.intent.action.MAIN": mainact = activity.getAttribute("android:name") if mainact == "": for sitem in activity.getElementsByTagName("category"): val = sitem.getAttribute("android:name") if val == "android.intent.category.LAUNCHER": mainact = activity.getAttribute("android:name") for service in services: service_name = service.getAttribute("android:name") svc.append(service_name) for provider in providers: provider_name = provider.getAttribute("android:name") cnp.append(provider_name) for receiver in receivers: rec = receiver.getAttribute("android:name") brd.append(rec) for _lib in libs: libary = _lib.getAttribute("android:name") lib.append(libary) for category in categories: cat.append(category.getAttribute("android:name")) for application in applications: try: icon_path = application.getAttribute("android:icon") icons.append(icon_path) except: continue # No icon attribute? for permission in permissions: perm.append(permission.getAttribute("android:name")) for i in perm: prm = i pos = i.rfind(".") if pos != -1: prm = i[pos + 1 :] try: dvm_perm[i] = DVM_PERMISSIONS["MANIFEST_PERMISSION"][prm] except KeyError: dvm_perm[i] = [ "dangerous", "Unknown permission from android reference", "Unknown permission from android reference", ] man_data_dic = { "services": svc, "activities": act, "receivers": brd, "providers": cnp, "libraries": lib, "categories": cat, "perm": dvm_perm, "packagename": package, "mainactivity": mainact, "min_sdk": minsdk, "max_sdk": maxsdk, "target_sdk": targetsdk, "androver": androidversioncode, "androvername": androidversionname, "icons": icons, } return man_data_dic except: PrintException("[ERROR] Extracting Manifest Data")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def get_browsable_activities(node): """Get Browsable Activities""" try: browse_dic = {} schemes = [] mime_types = [] hosts = [] ports = [] paths = [] path_prefixs = [] path_patterns = [] catg = node.getElementsByTagName("category") for cat in catg: if cat.getAttribute("android:name") == "android.intent.category.BROWSABLE": datas = node.getElementsByTagName("data") for data in datas: scheme = data.getAttribute("android:scheme") if scheme and scheme not in schemes: schemes.append(scheme) mime = data.getAttribute("android:mimeType") if mime and mime not in mime_types: mime_types.append(mime) host = data.getAttribute("android:host") if host and host not in hosts: hosts.append(host) port = data.getAttribute("android:port") if port and port not in ports: ports.append(port) path = data.getAttribute("android:path") if path and path not in paths: paths.append(path) path_prefix = data.getAttribute("android:pathPrefix") if path_prefix and path_prefix not in path_prefixs: path_prefixs.append(path_prefix) path_pattern = data.getAttribute("android:pathPattern") if path_pattern and path_pattern not in path_patterns: path_patterns.append(path_pattern) schemes = [scheme + "://" for scheme in schemes] browse_dic["schemes"] = schemes browse_dic["mime_types"] = mime_types browse_dic["hosts"] = hosts browse_dic["ports"] = ports browse_dic["paths"] = paths browse_dic["path_prefixs"] = path_prefixs browse_dic["path_patterns"] = path_patterns browse_dic["browsable"] = bool(browse_dic["schemes"]) return browse_dic except: PrintException("Getting Browsable Activities")
def get_browsable_activities(node): """Get Browsable Activities""" try: browse_dic = {} schemes = [] mime_types = [] hosts = [] ports = [] paths = [] path_prefixs = [] path_patterns = [] catg = node.getElementsByTagName("category") for cat in catg: if cat.getAttribute("android:name") == "android.intent.category.BROWSABLE": datas = node.getElementsByTagName("data") for data in datas: scheme = data.getAttribute("android:scheme") if scheme and scheme not in schemes: schemes.append(scheme) mime = data.getAttribute("android:mimeType") if mime and mime not in mime_types: mime_types.append(mime) host = data.getAttribute("android:host") if host and host not in hosts: hosts.append(host) port = data.getAttribute("android:port") if port and port not in ports: ports.append(port) path = data.getAttribute("android:path") if path and path not in paths: paths.append(path) path_prefix = data.getAttribute("android:pathPrefix") if path_prefix and path_prefix not in path_prefixs: path_prefixs.append(path_prefix) path_pattern = data.getAttribute("android:pathPattern") if path_pattern and path_pattern not in path_patterns: path_patterns.append(path_pattern) schemes = [scheme + "://" for scheme in schemes] browse_dic["schemes"] = schemes browse_dic["mime_types"] = mime_types browse_dic["hosts"] = hosts browse_dic["ports"] = ports browse_dic["paths"] = paths browse_dic["path_prefixs"] = path_prefixs browse_dic["path_patterns"] = path_patterns browse_dic["browsable"] = bool(browse_dic["schemes"]) return browse_dic except: PrintException("[ERROR] Getting Browsable Activities")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def manifest_analysis(mfxml, man_data_dic): """Analyse manifest file.""" # pylint: disable=C0301 try: logger.info("Manifest Analysis Started") exp_count = dict.fromkeys(["act", "ser", "bro", "cnt"], 0) applications = mfxml.getElementsByTagName("application") datas = mfxml.getElementsByTagName("data") intents = mfxml.getElementsByTagName("intent-filter") actions = mfxml.getElementsByTagName("action") granturipermissions = mfxml.getElementsByTagName("grant-uri-permission") permissions = mfxml.getElementsByTagName("permission") ret_value = [] ret_list = [] exported = [] browsable_activities = {} permission_dict = {} icon_hidden = True # PERMISSION for permission in permissions: if permission.getAttribute("android:protectionLevel"): protectionlevel = permission.getAttribute("android:protectionLevel") if protectionlevel == "0x00000000": protectionlevel = "normal" elif protectionlevel == "0x00000001": protectionlevel = "dangerous" elif protectionlevel == "0x00000002": protectionlevel = "signature" elif protectionlevel == "0x00000003": protectionlevel = "signatureOrSystem" permission_dict[permission.getAttribute("android:name")] = ( protectionlevel ) elif permission.getAttribute("android:name"): permission_dict[permission.getAttribute("android:name")] = "normal" # APPLICATIONS for application in applications: # Esteve 23.07.2016 - begin - identify permission at the # application level if application.getAttribute("android:permission"): perm_appl_level_exists = True perm_appl_level = application.getAttribute("android:permission") else: perm_appl_level_exists = False # End if application.getAttribute("android:debuggable") == "true": ret_list.append( ( "a_debuggable", tuple(), tuple(), ) ) if application.getAttribute("android:allowBackup") == "true": ret_list.append( ( "a_allowbackup", tuple(), tuple(), ) ) elif application.getAttribute("android:allowBackup") == "false": pass else: ret_list.append( ( "a_allowbackup_miss", tuple(), tuple(), ) ) if application.getAttribute("android:testOnly") == "true": ret_list.append( ( "a_testonly", tuple(), tuple(), ) ) for node in application.childNodes: an_or_a = "" if node.nodeName == "activity": itemname = "Activity" cnt_id = "act" an_or_a = "n" browse_dic = get_browsable_activities(node) if browse_dic["browsable"]: browsable_activities[node.getAttribute("android:name")] = ( browse_dic ) elif node.nodeName == "activity-alias": itemname = "Activity-Alias" cnt_id = "act" an_or_a = "n" browse_dic = get_browsable_activities(node) if browse_dic["browsable"]: browsable_activities[node.getAttribute("android:name")] = ( browse_dic ) elif node.nodeName == "provider": itemname = "Content Provider" cnt_id = "cnt" elif node.nodeName == "receiver": itemname = "Broadcast Receiver" cnt_id = "bro" elif node.nodeName == "service": itemname = "Service" cnt_id = "ser" else: itemname = "NIL" item = "" # Task Affinity if itemname in ["Activity", "Activity-Alias"] and node.getAttribute( "android:taskAffinity" ): item = node.getAttribute("android:name") ret_list.append( ( "a_taskaffinity", (item,), tuple(), ) ) # LaunchMode try: affected_sdk = int(man_data_dic["min_sdk"]) < ANDROID_5_0_LEVEL except: # in case min_sdk is not defined we assume vulnerability affected_sdk = True if ( affected_sdk and itemname in ["Activity", "Activity-Alias"] and ( node.getAttribute("android:launchMode") == "singleInstance" or node.getAttribute("android:launchMode") == "singleTask" ) ): item = node.getAttribute("android:name") ret_list.append( ( "a_launchmode", (item,), tuple(), ) ) # Exported Check item = "" is_inf = False is_perm_exist = False # Esteve 23.07.2016 - begin - initialise variables to identify # the existence of a permission at the component level that # matches a permission at the manifest level prot_level_exist = False protlevel = "" # End if itemname != "NIL": if node.getAttribute("android:exported") == "true": perm = "" item = node.getAttribute("android:name") if node.getAttribute("android:permission"): # permission exists perm = "<strong>Permission: </strong>" + node.getAttribute( "android:permission" ) is_perm_exist = True if item != man_data_dic["mainactivity"]: if is_perm_exist: prot = "" if ( node.getAttribute("android:permission") in permission_dict ): prot = ( "</br><strong>protectionLevel: </strong>" + permission_dict[ node.getAttribute("android:permission") ] ) # Esteve 23.07.2016 - begin - take into account protection level of the permission when claiming that a component is protected by it; # - the permission might not be defined in the application being analysed, if so, the protection level is not known; # - activities (or activity-alias) that are exported and have an unknown or normal or dangerous protection level are # included in the EXPORTED data structure for further treatment; components in this situation are also # counted as exported. prot_level_exist = True protlevel = permission_dict[ node.getAttribute("android:permission") ] if prot_level_exist: if protlevel == "normal": ret_list.append( ( "a_prot_normal", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) if itemname in ["Activity", "Activity-Alias"]: exported.append(item) exp_count[cnt_id] = exp_count[cnt_id] + 1 elif protlevel == "dangerous": ret_list.append( ( "a_prot_danger", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) if itemname in ["Activity", "Activity-Alias"]: exported.append(item) exp_count[cnt_id] = exp_count[cnt_id] + 1 elif protlevel == "signature": ret_list.append( ( "a_prot_sign", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) elif protlevel == "signatureOrSystem": ret_list.append( ( "a_prot_sign_sys", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) else: ret_list.append( ( "a_prot_unknown", (itemname, item, perm), ( an_or_a, itemname, ), ) ) if itemname in ["Activity", "Activity-Alias"]: exported.append(item) exp_count[cnt_id] = exp_count[cnt_id] + 1 # Esteve 23.07.2016 - end else: # Esteve 24.07.2016 - begin - At this point, we are dealing with components that do not have a permission neither at the component level nor at the # application level. As they are exported, they # are not protected. if perm_appl_level_exists is False: ret_list.append( ( "a_not_protected", (itemname, item), ( an_or_a, itemname, ), ) ) if itemname in ["Activity", "Activity-Alias"]: exported.append(item) exp_count[cnt_id] = exp_count[cnt_id] + 1 # Esteve 24.07.2016 - end # Esteve 24.07.2016 - begin - At this point, we are dealing with components that have a permission at the application level, but not at the component # level. Two options are possible: # 1) The permission is defined at the manifest level, which allows us to differentiate the level of protection as # we did just above for permissions specified at the component level. # 2) The permission is not defined at the manifest level, which means the protection level is unknown, as it is not # defined in the analysed application. else: perm = ( "<strong>Permission: </strong>" + perm_appl_level ) prot = "" if perm_appl_level in permission_dict: prot = ( "</br><strong>protectionLevel: </strong>" + permission_dict[perm_appl_level] ) prot_level_exist = True protlevel = permission_dict[perm_appl_level] if prot_level_exist: if protlevel == "normal": ret_list.append( ( "a_prot_normal_appl", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) if itemname in [ "Activity", "Activity-Alias", ]: exported.append(item) exp_count[cnt_id] = exp_count[cnt_id] + 1 elif protlevel == "dangerous": ret_list.append( ( "a_prot_danger_appl", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) if itemname in [ "Activity", "Activity-Alias", ]: exported.append(item) exp_count[cnt_id] = exp_count[cnt_id] + 1 elif protlevel == "signature": ret_list.append( ( "a_prot_sign_appl", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) elif protlevel == "signatureOrSystem": ret_list.append( ( "a_prot_sign_sys_appl", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) else: ret_list.append( ( "a_prot_unknown_appl", (itemname, item, perm), ( an_or_a, itemname, ), ) ) if itemname in ["Activity", "Activity-Alias"]: exported.append(item) exp_count[cnt_id] = exp_count[cnt_id] + 1 # Esteve 24.07.2016 - end elif node.getAttribute("android:exported") != "false": # Check for Implicitly Exported # Logic to support intent-filter intentfilters = node.childNodes for i in intentfilters: inf = i.nodeName if inf == "intent-filter": is_inf = True if is_inf: item = node.getAttribute("android:name") if node.getAttribute("android:permission"): # permission exists perm = ( "<strong>Permission: </strong>" + node.getAttribute("android:permission") ) is_perm_exist = True if item != man_data_dic["mainactivity"]: if is_perm_exist: prot = "" if ( node.getAttribute("android:permission") in permission_dict ): prot = ( "</br><strong>protectionLevel: </strong>" + permission_dict[ node.getAttribute("android:permission") ] ) # Esteve 24.07.2016 - begin - take into account protection level of the permission when claiming that a component is protected by it; # - the permission might not be defined in the application being analysed, if so, the protection level is not known; # - activities (or activity-alias) that are exported and have an unknown or normal or dangerous protection level are # included in the EXPORTED data structure for further treatment; components in this situation are also # counted as exported. prot_level_exist = True protlevel = permission_dict[ node.getAttribute("android:permission") ] if prot_level_exist: if protlevel == "normal": ret_list.append( ( "a_prot_normal", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) if itemname in [ "Activity", "Activity-Alias", ]: exported.append(item) exp_count[cnt_id] = ( exp_count[cnt_id] + 1 ) elif protlevel == "dangerous": ret_list.append( ( "a_prot_danger", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) if itemname in [ "Activity", "Activity-Alias", ]: exported.append(item) exp_count[cnt_id] = ( exp_count[cnt_id] + 1 ) elif protlevel == "signature": ret_list.append( ( "a_prot_sign", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) elif protlevel == "signatureOrSystem": ret_list.append( ( "a_prot_sign_sys", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) else: ret_list.append( ( "a_prot_unknown", (itemname, item, perm), ( an_or_a, itemname, ), ) ) if itemname in [ "Activity", "Activity-Alias", ]: exported.append(item) exp_count[cnt_id] = exp_count[cnt_id] + 1 # Esteve 24.07.2016 - end else: # Esteve 24.07.2016 - begin - At this point, we are dealing with components that do not have a permission neither at the component level nor at the # application level. As they are exported, # they are not protected. if perm_appl_level_exists is False: ret_list.append( ( "a_not_protected_filter", ( itemname, item, ), ( an_or_a, itemname, itemname, ), ) ) if itemname in ["Activity", "Activity-Alias"]: exported.append(item) exp_count[cnt_id] = exp_count[cnt_id] + 1 # Esteve 24.07.2016 - end # Esteve 24.07.2016 - begin - At this point, we are dealing with components that have a permission at the application level, but not at the component # level. Two options are possible: # 1) The permission is defined at the manifest level, which allows us to differentiate the level of protection as # we did just above for permissions specified at the component level. # 2) The permission is not defined at the manifest level, which means the protection level is unknown, as it is not # defined in the analysed application. else: perm = ( "<strong>Permission: </strong>" + perm_appl_level ) prot = "" if perm_appl_level in permission_dict: prot = ( "</br><strong>protectionLevel: </strong>" + permission_dict[perm_appl_level] ) prot_level_exist = True protlevel = permission_dict[perm_appl_level] if prot_level_exist: if protlevel == "normal": ret_list.append( ( "a_prot_normal_appl", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) if itemname in [ "Activity", "Activity-Alias", ]: exported.append(item) exp_count[cnt_id] = ( exp_count[cnt_id] + 1 ) elif protlevel == "dangerous": ret_list.append( ( "a_prot_danger_appl", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) if itemname in [ "Activity", "Activity-Alias", ]: exported.append(item) exp_count[cnt_id] = ( exp_count[cnt_id] + 1 ) elif protlevel == "signature": ret_list.append( ( "a_prot_sign_appl", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) elif protlevel == "signatureOrSystem": ret_list.append( ( "a_prot_sign_sys_appl", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) else: ret_list.append( ( "a_prot_unknown_appl", (itemname, item, perm), ( an_or_a, itemname, ), ) ) if itemname in [ "Activity", "Activity-Alias", ]: exported.append(item) exp_count[cnt_id] = exp_count[cnt_id] + 1 # Esteve 24.07.2016 - end # Esteve 29.07.2016 - begin The component is not explicitly exported (android:exported is not "true"). It is not implicitly exported either (it does not # make use of an intent filter). Despite that, it could still be exported by default, if it is a content provider and the android:targetSdkVersion # is older than 17 (Jelly Bean, Android versionn 4.2). This is true regardless of the system's API level. # Finally, it must also be taken into account that, if the minSdkVersion is greater or equal than 17, this check is unnecessary, because the # app will not be run on a system where the # system's API level is below 17. else: if ( man_data_dic["min_sdk"] and man_data_dic["target_sdk"] and int(man_data_dic["min_sdk"]) < ANDROID_4_2_LEVEL ): if ( itemname == "Content Provider" and int(man_data_dic["target_sdk"]) < ANDROID_4_2_LEVEL ): perm = "" item = node.getAttribute("android:name") if node.getAttribute("android:permission"): # permission exists perm = ( "<strong>Permission: </strong>" + node.getAttribute("android:permission") ) is_perm_exist = True if is_perm_exist: prot = "" if ( node.getAttribute("android:permission") in permission_dict ): prot = ( "</br><strong>protectionLevel: </strong>" + permission_dict[ node.getAttribute( "android:permission" ) ] ) prot_level_exist = True protlevel = permission_dict[ node.getAttribute("android:permission") ] if prot_level_exist: if protlevel == "normal": ret_list.append( ( "c_prot_normal", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) exp_count[cnt_id] = ( exp_count[cnt_id] + 1 ) elif protlevel == "dangerous": ret_list.append( ( "c_prot_danger", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) exp_count[cnt_id] = ( exp_count[cnt_id] + 1 ) elif protlevel == "signature": ret_list.append( ( "c_prot_sign", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) elif protlevel == "signatureOrSystem": ret_list.append( ( "c_prot_sign_sys", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) else: ret_list.append( ( "c_prot_unknown", (itemname, item, perm), ( an_or_a, itemname, ), ) ) exp_count[cnt_id] = exp_count[cnt_id] + 1 else: if perm_appl_level_exists is False: ret_list.append( ( "c_not_protected", (itemname, item), ( an_or_a, itemname, ), ) ) exp_count[cnt_id] = exp_count[cnt_id] + 1 else: perm = ( "<strong>Permission: </strong>" + perm_appl_level ) prot = "" if perm_appl_level in permission_dict: prot = ( "</br><strong>protectionLevel: </strong>" + permission_dict[perm_appl_level] ) prot_level_exist = True protlevel = permission_dict[ perm_appl_level ] if prot_level_exist: if protlevel == "normal": ret_list.append( ( "c_prot_normal_appl", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) exp_count[cnt_id] = ( exp_count[cnt_id] + 1 ) elif protlevel == "dangerous": ret_list.append( ( "c_prot_danger_appl", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) exp_count[cnt_id] = ( exp_count[cnt_id] + 1 ) elif protlevel == "signature": ret_list.append( ( "c_prot_sign_appl", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) elif protlevel == "signatureOrSystem": ret_list.append( ( "c_prot_sign_sys_appl", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) else: ret_list.append( ( "c_prot_unknown_appl", (itemname, item, perm), ( an_or_a, itemname, ), ) ) exp_count[cnt_id] = ( exp_count[cnt_id] + 1 ) # Esteve 29.07.2016 - end # Esteve 08.08.2016 - begin - If the content provider does not target an API version lower than 17, it could still be exported by default, depending # on the API version of the platform. If it was below 17, the content # provider would be exported by default. else: if ( itemname == "Content Provider" and int(man_data_dic["target_sdk"]) >= 17 ): perm = "" item = node.getAttribute("android:name") if node.getAttribute("android:permission"): # permission exists perm = ( "<strong>Permission: </strong>" + node.getAttribute( "android:permission" ) ) is_perm_exist = True if is_perm_exist: prot = "" if ( node.getAttribute("android:permission") in permission_dict ): prot = ( "</br><strong>protectionLevel: </strong>" + permission_dict[ node.getAttribute( "android:permission" ) ] ) prot_level_exist = True protlevel = permission_dict[ node.getAttribute( "android:permission" ) ] if prot_level_exist: if protlevel == "normal": ret_list.append( ( "c_prot_normal_new", ( itemname, item, perm + prot, ), (itemname,), ) ) exp_count[cnt_id] = ( exp_count[cnt_id] + 1 ) if protlevel == "dangerous": ret_list.append( ( "c_prot_danger_new", ( itemname, item, perm + prot, ), (itemname,), ) ) exp_count[cnt_id] = ( exp_count[cnt_id] + 1 ) if protlevel == "signature": ret_list.append( ( "c_prot_sign_new", ( itemname, item, perm + prot, ), (itemname,), ) ) if protlevel == "signatureOrSystem": ret_list.append( ( "c_prot_sign_sys_new", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) else: ret_list.append( ( "c_prot_unknown_new", (itemname, item, perm), (itemname,), ) ) exp_count[cnt_id] = ( exp_count[cnt_id] + 1 ) else: if perm_appl_level_exists is False: ret_list.append( ( "c_not_protected2", (itemname, item), ( an_or_a, itemname, ), ) ) exp_count[cnt_id] = ( exp_count[cnt_id] + 1 ) else: perm = ( "<strong>Permission: </strong>" + perm_appl_level ) prot = "" if perm_appl_level in permission_dict: prot = ( "</br><strong>protectionLevel: </strong>" + permission_dict[ perm_appl_level ] ) prot_level_exist = True protlevel = permission_dict[ perm_appl_level ] if prot_level_exist: if protlevel == "normal": ret_list.append( ( "c_prot_normal_new_appl", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) exp_count[cnt_id] = ( exp_count[cnt_id] + 1 ) elif protlevel == "dangerous": ret_list.append( ( "c_prot_danger_new_appl", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) exp_count[cnt_id] = ( exp_count[cnt_id] + 1 ) elif protlevel == "signature": ret_list.append( ( "c_prot_sign_new_appl", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) elif ( protlevel == "signatureOrSystem" ): ret_list.append( ( "c_prot_sign_sys_new_appl", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) else: ret_list.append( ( "c_prot_unknown_new_appl", (itemname, item, perm), ( an_or_a, itemname, ), ) ) exp_count[cnt_id] = ( exp_count[cnt_id] + 1 ) # Esteve 08.08.2016 - end # GRANT-URI-PERMISSIONS for granturi in granturipermissions: if granturi.getAttribute("android:pathPrefix") == "/": ret_list.append( ( "a_improper_provider", ("pathPrefix=/",), tuple(), ) ) elif granturi.getAttribute("android:path") == "/": ret_list.append( ( "a_improper_provider", ("path=/",), tuple(), ) ) elif granturi.getAttribute("android:pathPattern") == "*": ret_list.append( ( "a_improper_provider", ("path=*",), tuple(), ) ) # DATA for data in datas: if data.getAttribute("android:scheme") == "android_secret_code": xmlhost = data.getAttribute("android:host") ret_list.append( ( "a_dailer_code", (xmlhost,), tuple(), ) ) elif data.getAttribute("android:port"): dataport = data.getAttribute("android:port") ret_list.append( ( "a_sms_receiver_port", (dataport,), tuple(), ) ) # INTENTS for intent in intents: if intent.getAttribute("android:priority").isdigit(): value = intent.getAttribute("android:priority") if int(value) > 100: ret_list.append( ( "a_high_intent_priority", (value,), tuple(), ) ) # ACTIONS for action in actions: if action.getAttribute("android:priority").isdigit(): value = action.getAttribute("android:priority") if int(value) > 100: ret_list.append( ( "a_high_action_priority", (value,), tuple(), ) ) for a_key, t_name, t_desc in ret_list: a_template = android_manifest_desc.MANIFEST_DESC.get(a_key) if a_template: ret_value.append( { "title": a_template["title"] % t_name, "stat": a_template["level"], "desc": a_template["description"] % t_desc, "name": a_template["name"], "component": t_name, } ) for category in man_data_dic["categories"]: if category == "android.intent.category.LAUNCHER": icon_hidden = False break permissons = {} for k, permisson in man_data_dic["perm"].items(): permissons[k] = { "status": permisson[0], "info": permisson[1], "description": permisson[2], } # Prepare return dict man_an_dic = { "manifest_anal": ret_value, "exported_act": exported, "exported_cnt": exp_count, "browsable_activities": browsable_activities, "permissons": permissons, "cnt_act": len(man_data_dic["activities"]), "cnt_pro": len(man_data_dic["providers"]), "cnt_ser": len(man_data_dic["services"]), "cnt_bro": len(man_data_dic["receivers"]), "icon_hidden": icon_hidden, } return man_an_dic except: PrintException("Performing Manifest Analysis")
def manifest_analysis(mfxml, man_data_dic): """Analyse manifest file.""" # pylint: disable=C0301 try: logger.info("Manifest Analysis Started") exp_count = dict.fromkeys(["act", "ser", "bro", "cnt"], 0) applications = mfxml.getElementsByTagName("application") datas = mfxml.getElementsByTagName("data") intents = mfxml.getElementsByTagName("intent-filter") actions = mfxml.getElementsByTagName("action") granturipermissions = mfxml.getElementsByTagName("grant-uri-permission") permissions = mfxml.getElementsByTagName("permission") ret_value = [] ret_list = [] exported = [] browsable_activities = {} permission_dict = {} icon_hidden = True # PERMISSION for permission in permissions: if permission.getAttribute("android:protectionLevel"): protectionlevel = permission.getAttribute("android:protectionLevel") if protectionlevel == "0x00000000": protectionlevel = "normal" elif protectionlevel == "0x00000001": protectionlevel = "dangerous" elif protectionlevel == "0x00000002": protectionlevel = "signature" elif protectionlevel == "0x00000003": protectionlevel = "signatureOrSystem" permission_dict[permission.getAttribute("android:name")] = ( protectionlevel ) elif permission.getAttribute("android:name"): permission_dict[permission.getAttribute("android:name")] = "normal" # APPLICATIONS for application in applications: # Esteve 23.07.2016 - begin - identify permission at the # application level if application.getAttribute("android:permission"): perm_appl_level_exists = True perm_appl_level = application.getAttribute("android:permission") else: perm_appl_level_exists = False # End if application.getAttribute("android:debuggable") == "true": ret_list.append( ( "a_debuggable", tuple(), tuple(), ) ) if application.getAttribute("android:allowBackup") == "true": ret_list.append( ( "a_allowbackup", tuple(), tuple(), ) ) elif application.getAttribute("android:allowBackup") == "false": pass else: ret_list.append( ( "a_allowbackup_miss", tuple(), tuple(), ) ) if application.getAttribute("android:testOnly") == "true": ret_list.append( ( "a_testonly", tuple(), tuple(), ) ) for node in application.childNodes: an_or_a = "" if node.nodeName == "activity": itemname = "Activity" cnt_id = "act" an_or_a = "n" browse_dic = get_browsable_activities(node) if browse_dic["browsable"]: browsable_activities[node.getAttribute("android:name")] = ( browse_dic ) elif node.nodeName == "activity-alias": itemname = "Activity-Alias" cnt_id = "act" an_or_a = "n" browse_dic = get_browsable_activities(node) if browse_dic["browsable"]: browsable_activities[node.getAttribute("android:name")] = ( browse_dic ) elif node.nodeName == "provider": itemname = "Content Provider" cnt_id = "cnt" elif node.nodeName == "receiver": itemname = "Broadcast Receiver" cnt_id = "bro" elif node.nodeName == "service": itemname = "Service" cnt_id = "ser" else: itemname = "NIL" item = "" # Task Affinity if itemname in ["Activity", "Activity-Alias"] and node.getAttribute( "android:taskAffinity" ): item = node.getAttribute("android:name") ret_list.append( ( "a_taskaffinity", (item,), tuple(), ) ) # LaunchMode try: affected_sdk = int(man_data_dic["min_sdk"]) < ANDROID_5_0_LEVEL except: # in case min_sdk is not defined we assume vulnerability affected_sdk = True if ( affected_sdk and itemname in ["Activity", "Activity-Alias"] and ( node.getAttribute("android:launchMode") == "singleInstance" or node.getAttribute("android:launchMode") == "singleTask" ) ): item = node.getAttribute("android:name") ret_list.append( ( "a_launchmode", (item,), tuple(), ) ) # Exported Check item = "" is_inf = False is_perm_exist = False # Esteve 23.07.2016 - begin - initialise variables to identify # the existence of a permission at the component level that # matches a permission at the manifest level prot_level_exist = False protlevel = "" # End if itemname != "NIL": if node.getAttribute("android:exported") == "true": perm = "" item = node.getAttribute("android:name") if node.getAttribute("android:permission"): # permission exists perm = "<strong>Permission: </strong>" + node.getAttribute( "android:permission" ) is_perm_exist = True if item != man_data_dic["mainactivity"]: if is_perm_exist: prot = "" if ( node.getAttribute("android:permission") in permission_dict ): prot = ( "</br><strong>protectionLevel: </strong>" + permission_dict[ node.getAttribute("android:permission") ] ) # Esteve 23.07.2016 - begin - take into account protection level of the permission when claiming that a component is protected by it; # - the permission might not be defined in the application being analysed, if so, the protection level is not known; # - activities (or activity-alias) that are exported and have an unknown or normal or dangerous protection level are # included in the EXPORTED data structure for further treatment; components in this situation are also # counted as exported. prot_level_exist = True protlevel = permission_dict[ node.getAttribute("android:permission") ] if prot_level_exist: if protlevel == "normal": ret_list.append( ( "a_prot_normal", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) if itemname in ["Activity", "Activity-Alias"]: exported.append(item) exp_count[cnt_id] = exp_count[cnt_id] + 1 elif protlevel == "dangerous": ret_list.append( ( "a_prot_danger", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) if itemname in ["Activity", "Activity-Alias"]: exported.append(item) exp_count[cnt_id] = exp_count[cnt_id] + 1 elif protlevel == "signature": ret_list.append( ( "a_prot_sign", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) elif protlevel == "signatureOrSystem": ret_list.append( ( "a_prot_sign_sys", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) else: ret_list.append( ( "a_prot_unknown", (itemname, item, perm), ( an_or_a, itemname, ), ) ) if itemname in ["Activity", "Activity-Alias"]: exported.append(item) exp_count[cnt_id] = exp_count[cnt_id] + 1 # Esteve 23.07.2016 - end else: # Esteve 24.07.2016 - begin - At this point, we are dealing with components that do not have a permission neither at the component level nor at the # application level. As they are exported, they # are not protected. if perm_appl_level_exists is False: ret_list.append( ( "a_not_protected", (itemname, item), ( an_or_a, itemname, ), ) ) if itemname in ["Activity", "Activity-Alias"]: exported.append(item) exp_count[cnt_id] = exp_count[cnt_id] + 1 # Esteve 24.07.2016 - end # Esteve 24.07.2016 - begin - At this point, we are dealing with components that have a permission at the application level, but not at the component # level. Two options are possible: # 1) The permission is defined at the manifest level, which allows us to differentiate the level of protection as # we did just above for permissions specified at the component level. # 2) The permission is not defined at the manifest level, which means the protection level is unknown, as it is not # defined in the analysed application. else: perm = ( "<strong>Permission: </strong>" + perm_appl_level ) prot = "" if perm_appl_level in permission_dict: prot = ( "</br><strong>protectionLevel: </strong>" + permission_dict[perm_appl_level] ) prot_level_exist = True protlevel = permission_dict[perm_appl_level] if prot_level_exist: if protlevel == "normal": ret_list.append( ( "a_prot_normal_appl", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) if itemname in [ "Activity", "Activity-Alias", ]: exported.append(item) exp_count[cnt_id] = exp_count[cnt_id] + 1 elif protlevel == "dangerous": ret_list.append( ( "a_prot_danger_appl", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) if itemname in [ "Activity", "Activity-Alias", ]: exported.append(item) exp_count[cnt_id] = exp_count[cnt_id] + 1 elif protlevel == "signature": ret_list.append( ( "a_prot_sign_appl", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) elif protlevel == "signatureOrSystem": ret_list.append( ( "a_prot_sign_sys_appl", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) else: ret_list.append( ( "a_prot_unknown_appl", (itemname, item, perm), ( an_or_a, itemname, ), ) ) if itemname in ["Activity", "Activity-Alias"]: exported.append(item) exp_count[cnt_id] = exp_count[cnt_id] + 1 # Esteve 24.07.2016 - end elif node.getAttribute("android:exported") != "false": # Check for Implicitly Exported # Logic to support intent-filter intentfilters = node.childNodes for i in intentfilters: inf = i.nodeName if inf == "intent-filter": is_inf = True if is_inf: item = node.getAttribute("android:name") if node.getAttribute("android:permission"): # permission exists perm = ( "<strong>Permission: </strong>" + node.getAttribute("android:permission") ) is_perm_exist = True if item != man_data_dic["mainactivity"]: if is_perm_exist: prot = "" if ( node.getAttribute("android:permission") in permission_dict ): prot = ( "</br><strong>protectionLevel: </strong>" + permission_dict[ node.getAttribute("android:permission") ] ) # Esteve 24.07.2016 - begin - take into account protection level of the permission when claiming that a component is protected by it; # - the permission might not be defined in the application being analysed, if so, the protection level is not known; # - activities (or activity-alias) that are exported and have an unknown or normal or dangerous protection level are # included in the EXPORTED data structure for further treatment; components in this situation are also # counted as exported. prot_level_exist = True protlevel = permission_dict[ node.getAttribute("android:permission") ] if prot_level_exist: if protlevel == "normal": ret_list.append( ( "a_prot_normal", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) if itemname in [ "Activity", "Activity-Alias", ]: exported.append(item) exp_count[cnt_id] = ( exp_count[cnt_id] + 1 ) elif protlevel == "dangerous": ret_list.append( ( "a_prot_danger", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) if itemname in [ "Activity", "Activity-Alias", ]: exported.append(item) exp_count[cnt_id] = ( exp_count[cnt_id] + 1 ) elif protlevel == "signature": ret_list.append( ( "a_prot_sign", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) elif protlevel == "signatureOrSystem": ret_list.append( ( "a_prot_sign_sys", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) else: ret_list.append( ( "a_prot_unknown", (itemname, item, perm), ( an_or_a, itemname, ), ) ) if itemname in [ "Activity", "Activity-Alias", ]: exported.append(item) exp_count[cnt_id] = exp_count[cnt_id] + 1 # Esteve 24.07.2016 - end else: # Esteve 24.07.2016 - begin - At this point, we are dealing with components that do not have a permission neither at the component level nor at the # application level. As they are exported, # they are not protected. if perm_appl_level_exists is False: ret_list.append( ( "a_not_protected_filter", ( itemname, item, ), ( an_or_a, itemname, itemname, ), ) ) if itemname in ["Activity", "Activity-Alias"]: exported.append(item) exp_count[cnt_id] = exp_count[cnt_id] + 1 # Esteve 24.07.2016 - end # Esteve 24.07.2016 - begin - At this point, we are dealing with components that have a permission at the application level, but not at the component # level. Two options are possible: # 1) The permission is defined at the manifest level, which allows us to differentiate the level of protection as # we did just above for permissions specified at the component level. # 2) The permission is not defined at the manifest level, which means the protection level is unknown, as it is not # defined in the analysed application. else: perm = ( "<strong>Permission: </strong>" + perm_appl_level ) prot = "" if perm_appl_level in permission_dict: prot = ( "</br><strong>protectionLevel: </strong>" + permission_dict[perm_appl_level] ) prot_level_exist = True protlevel = permission_dict[perm_appl_level] if prot_level_exist: if protlevel == "normal": ret_list.append( ( "a_prot_normal_appl", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) if itemname in [ "Activity", "Activity-Alias", ]: exported.append(item) exp_count[cnt_id] = ( exp_count[cnt_id] + 1 ) elif protlevel == "dangerous": ret_list.append( ( "a_prot_danger_appl", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) if itemname in [ "Activity", "Activity-Alias", ]: exported.append(item) exp_count[cnt_id] = ( exp_count[cnt_id] + 1 ) elif protlevel == "signature": ret_list.append( ( "a_prot_sign_appl", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) elif protlevel == "signatureOrSystem": ret_list.append( ( "a_prot_sign_sys_appl", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) else: ret_list.append( ( "a_prot_unknown_appl", (itemname, item, perm), ( an_or_a, itemname, ), ) ) if itemname in [ "Activity", "Activity-Alias", ]: exported.append(item) exp_count[cnt_id] = exp_count[cnt_id] + 1 # Esteve 24.07.2016 - end # Esteve 29.07.2016 - begin The component is not explicitly exported (android:exported is not "true"). It is not implicitly exported either (it does not # make use of an intent filter). Despite that, it could still be exported by default, if it is a content provider and the android:targetSdkVersion # is older than 17 (Jelly Bean, Android versionn 4.2). This is true regardless of the system's API level. # Finally, it must also be taken into account that, if the minSdkVersion is greater or equal than 17, this check is unnecessary, because the # app will not be run on a system where the # system's API level is below 17. else: if ( man_data_dic["min_sdk"] and man_data_dic["target_sdk"] and int(man_data_dic["min_sdk"]) < ANDROID_4_2_LEVEL ): if ( itemname == "Content Provider" and int(man_data_dic["target_sdk"]) < ANDROID_4_2_LEVEL ): perm = "" item = node.getAttribute("android:name") if node.getAttribute("android:permission"): # permission exists perm = ( "<strong>Permission: </strong>" + node.getAttribute("android:permission") ) is_perm_exist = True if is_perm_exist: prot = "" if ( node.getAttribute("android:permission") in permission_dict ): prot = ( "</br><strong>protectionLevel: </strong>" + permission_dict[ node.getAttribute( "android:permission" ) ] ) prot_level_exist = True protlevel = permission_dict[ node.getAttribute("android:permission") ] if prot_level_exist: if protlevel == "normal": ret_list.append( ( "c_prot_normal", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) exp_count[cnt_id] = ( exp_count[cnt_id] + 1 ) elif protlevel == "dangerous": ret_list.append( ( "c_prot_danger", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) exp_count[cnt_id] = ( exp_count[cnt_id] + 1 ) elif protlevel == "signature": ret_list.append( ( "c_prot_sign", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) elif protlevel == "signatureOrSystem": ret_list.append( ( "c_prot_sign_sys", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) else: ret_list.append( ( "c_prot_unknown", (itemname, item, perm), ( an_or_a, itemname, ), ) ) exp_count[cnt_id] = exp_count[cnt_id] + 1 else: if perm_appl_level_exists is False: ret_list.append( ( "c_not_protected", (itemname, item), ( an_or_a, itemname, ), ) ) exp_count[cnt_id] = exp_count[cnt_id] + 1 else: perm = ( "<strong>Permission: </strong>" + perm_appl_level ) prot = "" if perm_appl_level in permission_dict: prot = ( "</br><strong>protectionLevel: </strong>" + permission_dict[perm_appl_level] ) prot_level_exist = True protlevel = permission_dict[ perm_appl_level ] if prot_level_exist: if protlevel == "normal": ret_list.append( ( "c_prot_normal_appl", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) exp_count[cnt_id] = ( exp_count[cnt_id] + 1 ) elif protlevel == "dangerous": ret_list.append( ( "c_prot_danger_appl", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) exp_count[cnt_id] = ( exp_count[cnt_id] + 1 ) elif protlevel == "signature": ret_list.append( ( "c_prot_sign_appl", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) elif protlevel == "signatureOrSystem": ret_list.append( ( "c_prot_sign_sys_appl", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) else: ret_list.append( ( "c_prot_unknown_appl", (itemname, item, perm), ( an_or_a, itemname, ), ) ) exp_count[cnt_id] = ( exp_count[cnt_id] + 1 ) # Esteve 29.07.2016 - end # Esteve 08.08.2016 - begin - If the content provider does not target an API version lower than 17, it could still be exported by default, depending # on the API version of the platform. If it was below 17, the content # provider would be exported by default. else: if ( itemname == "Content Provider" and int(man_data_dic["target_sdk"]) >= 17 ): perm = "" item = node.getAttribute("android:name") if node.getAttribute("android:permission"): # permission exists perm = ( "<strong>Permission: </strong>" + node.getAttribute( "android:permission" ) ) is_perm_exist = True if is_perm_exist: prot = "" if ( node.getAttribute("android:permission") in permission_dict ): prot = ( "</br><strong>protectionLevel: </strong>" + permission_dict[ node.getAttribute( "android:permission" ) ] ) prot_level_exist = True protlevel = permission_dict[ node.getAttribute( "android:permission" ) ] if prot_level_exist: if protlevel == "normal": ret_list.append( ( "c_prot_normal_new", ( itemname, item, perm + prot, ), (itemname,), ) ) exp_count[cnt_id] = ( exp_count[cnt_id] + 1 ) if protlevel == "dangerous": ret_list.append( ( "c_prot_danger_new", ( itemname, item, perm + prot, ), (itemname,), ) ) exp_count[cnt_id] = ( exp_count[cnt_id] + 1 ) if protlevel == "signature": ret_list.append( ( "c_prot_sign_new", ( itemname, item, perm + prot, ), (itemname,), ) ) if protlevel == "signatureOrSystem": ret_list.append( ( "c_prot_sign_sys_new", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) else: ret_list.append( ( "c_prot_unknown_new", (itemname, item, perm), (itemname,), ) ) exp_count[cnt_id] = ( exp_count[cnt_id] + 1 ) else: if perm_appl_level_exists is False: ret_list.append( ( "c_not_protected2", (itemname, item), ( an_or_a, itemname, ), ) ) exp_count[cnt_id] = ( exp_count[cnt_id] + 1 ) else: perm = ( "<strong>Permission: </strong>" + perm_appl_level ) prot = "" if perm_appl_level in permission_dict: prot = ( "</br><strong>protectionLevel: </strong>" + permission_dict[ perm_appl_level ] ) prot_level_exist = True protlevel = permission_dict[ perm_appl_level ] if prot_level_exist: if protlevel == "normal": ret_list.append( ( "c_prot_normal_new_appl", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) exp_count[cnt_id] = ( exp_count[cnt_id] + 1 ) elif protlevel == "dangerous": ret_list.append( ( "c_prot_danger_new_appl", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) exp_count[cnt_id] = ( exp_count[cnt_id] + 1 ) elif protlevel == "signature": ret_list.append( ( "c_prot_sign_new_appl", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) elif ( protlevel == "signatureOrSystem" ): ret_list.append( ( "c_prot_sign_sys_new_appl", ( itemname, item, perm + prot, ), ( an_or_a, itemname, ), ) ) else: ret_list.append( ( "c_prot_unknown_new_appl", (itemname, item, perm), ( an_or_a, itemname, ), ) ) exp_count[cnt_id] = ( exp_count[cnt_id] + 1 ) # Esteve 08.08.2016 - end # GRANT-URI-PERMISSIONS for granturi in granturipermissions: if granturi.getAttribute("android:pathPrefix") == "/": ret_list.append( ( "a_improper_provider", ("pathPrefix=/",), tuple(), ) ) elif granturi.getAttribute("android:path") == "/": ret_list.append( ( "a_improper_provider", ("path=/",), tuple(), ) ) elif granturi.getAttribute("android:pathPattern") == "*": ret_list.append( ( "a_improper_provider", ("path=*",), tuple(), ) ) # DATA for data in datas: if data.getAttribute("android:scheme") == "android_secret_code": xmlhost = data.getAttribute("android:host") ret_list.append( ( "a_dailer_code", (xmlhost,), tuple(), ) ) elif data.getAttribute("android:port"): dataport = data.getAttribute("android:port") ret_list.append( ( "a_sms_receiver_port", (dataport,), tuple(), ) ) # INTENTS for intent in intents: if intent.getAttribute("android:priority").isdigit(): value = intent.getAttribute("android:priority") if int(value) > 100: ret_list.append( ( "a_high_intent_priority", (value,), tuple(), ) ) # ACTIONS for action in actions: if action.getAttribute("android:priority").isdigit(): value = action.getAttribute("android:priority") if int(value) > 100: ret_list.append( ( "a_high_action_priority", (value,), tuple(), ) ) for a_key, t_name, t_desc in ret_list: a_template = android_manifest_desc.MANIFEST_DESC.get(a_key) if a_template: ret_value.append( { "title": a_template["title"] % t_name, "stat": a_template["level"], "desc": a_template["description"] % t_desc, "name": a_template["name"], "component": t_name, } ) for category in man_data_dic["categories"]: if category == "android.intent.category.LAUNCHER": icon_hidden = False break permissons = {} for k, permisson in man_data_dic["perm"].items(): permissons[k] = { "status": permisson[0], "info": permisson[1], "description": permisson[2], } # Prepare return dict man_an_dic = { "manifest_anal": ret_value, "exported_act": exported, "exported_cnt": exp_count, "browsable_activities": browsable_activities, "permissons": permissons, "cnt_act": len(man_data_dic["activities"]), "cnt_pro": len(man_data_dic["providers"]), "cnt_ser": len(man_data_dic["services"]), "cnt_bro": len(man_data_dic["receivers"]), "icon_hidden": icon_hidden, } return man_an_dic except: PrintException("[ERROR] Performing Manifest Analysis")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def read_manifest(app_dir, app_path, tools_dir, typ, apk): """Read the manifest file.""" try: dat = "" manifest = "" if apk: manifest = get_manifest_file(app_path, app_dir, tools_dir) if isFileExists(manifest): logger.info("Reading Android Manifest") with io.open( manifest, mode="r", encoding="utf8", errors="ignore" ) as file_pointer: dat = file_pointer.read() else: logger.info("Reading Manifest from Source") if typ == "eclipse": manifest = os.path.join(app_dir, "AndroidManifest.xml") elif typ == "studio": manifest = os.path.join(app_dir, "app/src/main/AndroidManifest.xml") with io.open( manifest, mode="r", encoding="utf8", errors="ignore" ) as file_pointer: dat = file_pointer.read() return dat except: PrintException("Reading Manifest file")
def read_manifest(app_dir, app_path, tools_dir, typ, apk): """Read the manifest file.""" try: dat = "" manifest = "" if apk: manifest = get_manifest_file(app_path, app_dir, tools_dir) if isFileExists(manifest): logger.info("Reading Android Manifest") with io.open( manifest, mode="r", encoding="utf8", errors="ignore" ) as file_pointer: dat = file_pointer.read() else: logger.info("Reading Manifest from Source") if typ == "eclipse": manifest = os.path.join(app_dir, "AndroidManifest.xml") elif typ == "studio": manifest = os.path.join(app_dir, "app/src/main/AndroidManifest.xml") with io.open( manifest, mode="r", encoding="utf8", errors="ignore" ) as file_pointer: dat = file_pointer.read() return dat except: PrintException("[ERROR] Reading Manifest file")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def get_manifest_file(app_path, app_dir, tools_dir): """Get readable AndroidManifest.xml""" try: manifest = None if len(settings.APKTOOL_BINARY) > 0 and isFileExists(settings.APKTOOL_BINARY): apktool_path = settings.APKTOOL_BINARY else: apktool_path = os.path.join(tools_dir, "apktool_2.3.4.jar") output_dir = os.path.join(app_dir, "apktool_out") args = [ settings.JAVA_PATH + "java", "-jar", apktool_path, "--match-original", "-f", "-s", "d", app_path, "-o", output_dir, ] manifest = os.path.join(output_dir, "AndroidManifest.xml") if isFileExists(manifest): # APKTool already created readable XML return manifest logger.info("Converting AXML to XML") subprocess.check_output(args) return manifest except: PrintException("Getting Manifest file")
def get_manifest_file(app_path, app_dir, tools_dir): """Get readable AndroidManifest.xml""" try: manifest = None if len(settings.APKTOOL_BINARY) > 0 and isFileExists(settings.APKTOOL_BINARY): apktool_path = settings.APKTOOL_BINARY else: apktool_path = os.path.join(tools_dir, "apktool_2.3.4.jar") output_dir = os.path.join(app_dir, "apktool_out") args = [ settings.JAVA_PATH + "java", "-jar", apktool_path, "--match-original", "-f", "-s", "d", app_path, "-o", output_dir, ] manifest = os.path.join(output_dir, "AndroidManifest.xml") if isFileExists(manifest): # APKTool already created readable XML return manifest logger.info("Converting AXML to XML") subprocess.check_output(args) return manifest except: PrintException("[ERROR]Getting Manifest file")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def run(request): """View the manifest.""" try: directory = settings.BASE_DIR # BASE DIR md5 = request.GET["md5"] # MD5 typ = request.GET["type"] # APK or SOURCE binary = request.GET["bin"] match = re.match("^[0-9a-f]{32}$", md5) if match and (typ in ["eclipse", "studio", "apk"]) and (binary in ["1", "0"]): app_dir = os.path.join(settings.UPLD_DIR, md5 + "/") # APP DIRECTORY tools_dir = os.path.join(directory, "StaticAnalyzer/tools/") # TOOLS DIR if binary == "1": is_binary = True elif binary == "0": is_binary = False app_path = os.path.join(app_dir, md5 + ".apk") manifest = read_manifest(app_dir, app_path, tools_dir, typ, is_binary) context = { "title": "AndroidManifest.xml", "file": "AndroidManifest.xml", "dat": manifest, } template = "static_analysis/view_mani.html" return render(request, template, context) except: PrintException("Viewing AndroidManifest.xml") return print_n_send_error_response(request, "Error Viewing AndroidManifest.xml")
def run(request): """View the manifest.""" try: directory = settings.BASE_DIR # BASE DIR md5 = request.GET["md5"] # MD5 typ = request.GET["type"] # APK or SOURCE binary = request.GET["bin"] match = re.match("^[0-9a-f]{32}$", md5) if match and (typ in ["eclipse", "studio", "apk"]) and (binary in ["1", "0"]): app_dir = os.path.join(settings.UPLD_DIR, md5 + "/") # APP DIRECTORY tools_dir = os.path.join(directory, "StaticAnalyzer/tools/") # TOOLS DIR if binary == "1": is_binary = True elif binary == "0": is_binary = False app_path = os.path.join(app_dir, md5 + ".apk") manifest = read_manifest(app_dir, app_path, tools_dir, typ, is_binary) context = { "title": "AndroidManifest.xml", "file": "AndroidManifest.xml", "dat": manifest, } template = "static_analysis/view_mani.html" return render(request, template, context) except: PrintException("[ERROR] Viewing AndroidManifest.xml") return HttpResponseRedirect("/error/")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def run(request): """Show the smali code.""" try: match = re.match("^[0-9a-f]{32}$", request.GET["md5"]) if match: md5 = request.GET["md5"] src = os.path.join(settings.UPLD_DIR, md5 + "/smali_source/") html = "" # pylint: disable=unused-variable # Needed by os.walk for dir_name, sub_dir, files in os.walk(src): for jfile in files: if jfile.endswith(".smali"): file_path = os.path.join(src, dir_name, jfile) if "+" in jfile: fp2 = os.path.join(src, dir_name, jfile.replace("+", "x")) shutil.move(file_path, fp2) file_path = fp2 fileparam = file_path.replace(src, "") html += ( "<tr><td><a href='../ViewSource/?file=" + escape(fileparam) + "&type=apk&md5=" + md5 + "'>" + escape(fileparam) + "</a></td></tr>" ) context = { "title": "Smali Source", "files": html, "md5": md5, } template = "static_analysis/smali.html" return render(request, template, context) except: PrintException("Getting Smali Files") return print_n_send_error_response(request, "Error Getting Smali Files")
def run(request): """Show the smali code.""" try: match = re.match("^[0-9a-f]{32}$", request.GET["md5"]) if match: md5 = request.GET["md5"] src = os.path.join(settings.UPLD_DIR, md5 + "/smali_source/") html = "" # pylint: disable=unused-variable # Needed by os.walk for dir_name, sub_dir, files in os.walk(src): for jfile in files: if jfile.endswith(".smali"): file_path = os.path.join(src, dir_name, jfile) if "+" in jfile: fp2 = os.path.join(src, dir_name, jfile.replace("+", "x")) shutil.move(file_path, fp2) file_path = fp2 fileparam = file_path.replace(src, "") html += ( "<tr><td><a href='../ViewSource/?file=" + escape(fileparam) + "&type=apk&md5=" + md5 + "'>" + escape(fileparam) + "</a></td></tr>" ) context = { "title": "Smali Source", "files": html, "md5": md5, } template = "static_analysis/smali.html" return render(request, template, context) except: PrintException("[ERROR] Getting Smali Files") return HttpResponseRedirect("/error/")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def static_analyzer(request, api=False): """Do static analysis on an request and save to db.""" try: if api: typ = request.POST["scan_type"] checksum = request.POST["hash"] filename = request.POST["file_name"] rescan = str(request.POST.get("re_scan", 0)) else: typ = request.GET["type"] checksum = request.GET["checksum"] filename = request.GET["name"] rescan = str(request.GET.get("rescan", 0)) # Input validation app_dic = {} match = re.match("^[0-9a-f]{32}$", checksum) if ( (match) and (filename.lower().endswith(".apk") or filename.lower().endswith(".zip")) and (typ in ["zip", "apk"]) ): app_dic["dir"] = settings.BASE_DIR # BASE DIR app_dic["app_name"] = filename # APP ORGINAL NAME app_dic["md5"] = checksum # MD5 app_dic["app_dir"] = os.path.join( settings.UPLD_DIR, app_dic["md5"] + "/" ) # APP DIRECTORY app_dic["tools_dir"] = os.path.join( app_dic["dir"], "StaticAnalyzer/tools/" ) # TOOLS DIR # DWD_DIR = settings.DWD_DIR # not needed? Var is never used. logger.info("Starting Analysis on : " + app_dic["app_name"]) if typ == "apk": # Check if in DB # pylint: disable=E1101 db_entry = StaticAnalyzerAndroid.objects.filter(MD5=app_dic["md5"]) if db_entry.exists() and rescan == "0": context = get_context_from_db_entry(db_entry) else: app_dic["app_file"] = app_dic["md5"] + ".apk" # NEW FILENAME app_dic["app_path"] = ( app_dic["app_dir"] + app_dic["app_file"] ) # APP PATH # ANALYSIS BEGINS app_dic["size"] = ( str(file_size(app_dic["app_path"])) + "MB" ) # FILE SIZE app_dic["sha1"], app_dic["sha256"] = hash_gen(app_dic["app_path"]) app_dic["files"] = unzip(app_dic["app_path"], app_dic["app_dir"]) app_dic["certz"] = get_hardcoded_cert_keystore(app_dic["files"]) logger.info("APK Extracted") # Manifest XML app_dic["parsed_xml"] = get_manifest( app_dic["app_path"], app_dic["app_dir"], app_dic["tools_dir"], "", True, ) # Get icon res_path = os.path.join(app_dic["app_dir"], "res") app_dic["icon_hidden"] = True # Even if the icon is hidden, try to guess it by the # default paths app_dic["icon_found"] = False app_dic["icon_path"] = "" # TODO: Check for possible different names for resource # folder? if os.path.exists(res_path): icon_dic = get_icon(app_dic["app_path"], res_path) if icon_dic: app_dic["icon_hidden"] = icon_dic["hidden"] app_dic["icon_found"] = bool(icon_dic["path"]) app_dic["icon_path"] = icon_dic["path"] # Set Manifest link app_dic["mani"] = ( "../ManifestView/?md5=" + app_dic["md5"] + "&type=apk&bin=1" ) man_data_dic = manifest_data(app_dic["parsed_xml"]) man_an_dic = manifest_analysis(app_dic["parsed_xml"], man_data_dic) bin_an_buff = [] bin_an_buff += elf_analysis(app_dic["app_dir"]) bin_an_buff += res_analysis(app_dic["app_dir"]) cert_dic = cert_info(app_dic["app_dir"], app_dic["tools_dir"]) apkid_results = apkid_analysis( app_dic["app_dir"], app_dic["app_path"] ) dex_2_jar( app_dic["app_path"], app_dic["app_dir"], app_dic["tools_dir"] ) dex_2_smali(app_dic["app_dir"], app_dic["tools_dir"]) jar_2_java(app_dic["app_dir"], app_dic["tools_dir"]) code_an_dic = code_analysis( app_dic["app_dir"], man_an_dic["permissons"], "apk" ) logger.info("Generating Java and Smali Downloads") gen_downloads( app_dic["app_dir"], app_dic["md5"], app_dic["icon_path"] ) # Get the strings app_dic["strings"] = strings_jar( app_dic["app_file"], app_dic["app_dir"] ) app_dic["zipped"] = "&type=apk" logger.info("Connecting to Database") try: # SAVE TO DB if rescan == "1": logger.info("Updating Database...") update_db_entry( app_dic, man_data_dic, man_an_dic, code_an_dic, cert_dic, bin_an_buff, apkid_results, ) elif rescan == "0": logger.info("Saving to Database") create_db_entry( app_dic, man_data_dic, man_an_dic, code_an_dic, cert_dic, bin_an_buff, apkid_results, ) except: PrintException("Saving to Database Failed") context = get_context_from_analysis( app_dic, man_data_dic, man_an_dic, code_an_dic, cert_dic, bin_an_buff, apkid_results, ) context["average_cvss"], context["security_score"] = score( context["findings"] ) context["dynamic_analysis_done"] = os.path.exists( os.path.join(app_dic["app_dir"], "logcat.txt") ) context["VT_RESULT"] = None if settings.VT_ENABLED: vt = VirusTotal.VirusTotal() context["VT_RESULT"] = vt.get_result( os.path.join(app_dic["app_dir"], app_dic["md5"]) + ".apk", app_dic["md5"], ) template = "static_analysis/static_analysis.html" if api: return context else: return render(request, template, context) elif typ == "zip": # Check if in DB # pylint: disable=E1101 cert_dic = {} cert_dic["cert_info"] = "" cert_dic["issued"] = "" cert_dic["sha256Digest"] = False bin_an_buff = [] app_dic["strings"] = "" app_dic["zipped"] = "" # Above fields are only available for APK and not ZIP db_entry = StaticAnalyzerAndroid.objects.filter(MD5=app_dic["md5"]) if db_entry.exists() and rescan == "0": context = get_context_from_db_entry(db_entry) else: app_dic["app_file"] = app_dic["md5"] + ".zip" # NEW FILENAME app_dic["app_path"] = ( app_dic["app_dir"] + app_dic["app_file"] ) # APP PATH logger.info("Extracting ZIP") app_dic["files"] = unzip(app_dic["app_path"], app_dic["app_dir"]) # Check if Valid Directory Structure and get ZIP Type pro_type, valid = valid_android_zip(app_dic["app_dir"]) if valid and pro_type == "ios": logger.info("Redirecting to iOS Source Code Analyzer") if api: return {"type": "ios"} else: return HttpResponseRedirect( "/StaticAnalyzer_iOS/?name=" + app_dic["app_name"] + "&type=ios&checksum=" + app_dic["md5"] ) app_dic["certz"] = get_hardcoded_cert_keystore(app_dic["files"]) app_dic["zipped"] = pro_type logger.info("ZIP Type - " + pro_type) if valid and (pro_type in ["eclipse", "studio"]): # ANALYSIS BEGINS app_dic["size"] = ( str(file_size(app_dic["app_path"])) + "MB" ) # FILE SIZE app_dic["sha1"], app_dic["sha256"] = hash_gen( app_dic["app_path"] ) # Manifest XML app_dic["persed_xml"] = get_manifest( "", app_dic["app_dir"], app_dic["tools_dir"], pro_type, False, ) # Set manifest view link app_dic["mani"] = ( "../ManifestView/?md5=" + app_dic["md5"] + "&type=" + pro_type + "&bin=0" ) man_data_dic = manifest_data(app_dic["persed_xml"]) man_an_dic = manifest_analysis( app_dic["persed_xml"], man_data_dic ) # Get icon eclipse_res_path = os.path.join(app_dic["app_dir"], "res") studio_res_path = os.path.join( app_dic["app_dir"], "app", "src", "main", "res" ) if os.path.exists(eclipse_res_path): res_path = eclipse_res_path elif os.path.exists(studio_res_path): res_path = studio_res_path else: res_path = "" app_dic["icon_hidden"] = man_an_dic["icon_hidden"] app_dic["icon_found"] = False app_dic["icon_path"] = "" if res_path: app_dic["icon_path"] = find_icon_path_zip( res_path, man_data_dic["icons"] ) if app_dic["icon_path"]: app_dic["icon_found"] = True if app_dic["icon_path"]: if os.path.exists(app_dic["icon_path"]): shutil.copy2( app_dic["icon_path"], os.path.join( settings.DWD_DIR, app_dic["md5"] + "-icon.png" ), ) code_an_dic = code_analysis( app_dic["app_dir"], man_an_dic["permissons"], pro_type ) logger.info("Connecting to Database") try: # SAVE TO DB if rescan == "1": logger.info("Updating Database...") update_db_entry( app_dic, man_data_dic, man_an_dic, code_an_dic, cert_dic, bin_an_buff, {}, ) elif rescan == "0": logger.info("Saving to Database") create_db_entry( app_dic, man_data_dic, man_an_dic, code_an_dic, cert_dic, bin_an_buff, {}, ) except: PrintException("Saving to Database Failed") context = get_context_from_analysis( app_dic, man_data_dic, man_an_dic, code_an_dic, cert_dic, bin_an_buff, {}, ) else: msg = "This ZIP Format is not supported" if api: return print_n_send_error_response(request, msg, True) else: print_n_send_error_response(request, msg, False) return HttpResponseRedirect("/zip_format/") context["average_cvss"], context["security_score"] = score( context["findings"] ) template = "static_analysis/static_analysis_android_zip.html" if api: return context else: return render(request, template, context) else: logger.error( "Only APK,IPA and Zipped Android/iOS Source code supported now!" ) else: msg = "Hash match failed or Invalid file extension or file type" if api: return print_n_send_error_response(request, msg, True) else: return print_n_send_error_response(request, msg, False) except Exception as excep: msg = str(excep) exp = excep.__doc__ if api: return print_n_send_error_response(request, msg, True, exp) else: return print_n_send_error_response(request, msg, False, exp)
def static_analyzer(request, api=False): """Do static analysis on an request and save to db.""" try: if api: typ = request.POST["scan_type"] checksum = request.POST["hash"] filename = request.POST["file_name"] rescan = str(request.POST.get("re_scan", 0)) else: typ = request.GET["type"] checksum = request.GET["checksum"] filename = request.GET["name"] rescan = str(request.GET.get("rescan", 0)) # Input validation app_dic = {} match = re.match("^[0-9a-f]{32}$", checksum) if ( (match) and (filename.lower().endswith(".apk") or filename.lower().endswith(".zip")) and (typ in ["zip", "apk"]) ): app_dic["dir"] = settings.BASE_DIR # BASE DIR app_dic["app_name"] = filename # APP ORGINAL NAME app_dic["md5"] = checksum # MD5 app_dic["app_dir"] = os.path.join( settings.UPLD_DIR, app_dic["md5"] + "/" ) # APP DIRECTORY app_dic["tools_dir"] = os.path.join( app_dic["dir"], "StaticAnalyzer/tools/" ) # TOOLS DIR # DWD_DIR = settings.DWD_DIR # not needed? Var is never used. logger.info("Starting Analysis on : " + app_dic["app_name"]) if typ == "apk": # Check if in DB # pylint: disable=E1101 db_entry = StaticAnalyzerAndroid.objects.filter(MD5=app_dic["md5"]) if db_entry.exists() and rescan == "0": context = get_context_from_db_entry(db_entry) else: app_dic["app_file"] = app_dic["md5"] + ".apk" # NEW FILENAME app_dic["app_path"] = ( app_dic["app_dir"] + app_dic["app_file"] ) # APP PATH # ANALYSIS BEGINS app_dic["size"] = ( str(file_size(app_dic["app_path"])) + "MB" ) # FILE SIZE app_dic["sha1"], app_dic["sha256"] = hash_gen(app_dic["app_path"]) app_dic["files"] = unzip(app_dic["app_path"], app_dic["app_dir"]) app_dic["certz"] = get_hardcoded_cert_keystore(app_dic["files"]) logger.info("APK Extracted") # Manifest XML app_dic["parsed_xml"] = get_manifest( app_dic["app_path"], app_dic["app_dir"], app_dic["tools_dir"], "", True, ) # Get icon res_path = os.path.join(app_dic["app_dir"], "res") app_dic["icon_hidden"] = True # Even if the icon is hidden, try to guess it by the # default paths app_dic["icon_found"] = False app_dic["icon_path"] = "" # TODO: Check for possible different names for resource # folder? if os.path.exists(res_path): icon_dic = get_icon(app_dic["app_path"], res_path) if icon_dic: app_dic["icon_hidden"] = icon_dic["hidden"] app_dic["icon_found"] = bool(icon_dic["path"]) app_dic["icon_path"] = icon_dic["path"] # Set Manifest link app_dic["mani"] = ( "../ManifestView/?md5=" + app_dic["md5"] + "&type=apk&bin=1" ) man_data_dic = manifest_data(app_dic["parsed_xml"]) man_an_dic = manifest_analysis(app_dic["parsed_xml"], man_data_dic) bin_an_buff = [] bin_an_buff += elf_analysis(app_dic["app_dir"]) bin_an_buff += res_analysis(app_dic["app_dir"]) cert_dic = cert_info(app_dic["app_dir"], app_dic["tools_dir"]) apkid_results = apkid_analysis( app_dic["app_dir"], app_dic["app_path"] ) dex_2_jar( app_dic["app_path"], app_dic["app_dir"], app_dic["tools_dir"] ) dex_2_smali(app_dic["app_dir"], app_dic["tools_dir"]) jar_2_java(app_dic["app_dir"], app_dic["tools_dir"]) code_an_dic = code_analysis( app_dic["app_dir"], man_an_dic["permissons"], "apk" ) logger.info("Generating Java and Smali Downloads") gen_downloads( app_dic["app_dir"], app_dic["md5"], app_dic["icon_path"] ) # Get the strings app_dic["strings"] = strings_jar( app_dic["app_file"], app_dic["app_dir"] ) app_dic["zipped"] = "&type=apk" logger.info("Connecting to Database") try: # SAVE TO DB if rescan == "1": logger.info("Updating Database...") update_db_entry( app_dic, man_data_dic, man_an_dic, code_an_dic, cert_dic, bin_an_buff, apkid_results, ) elif rescan == "0": logger.info("Saving to Database") create_db_entry( app_dic, man_data_dic, man_an_dic, code_an_dic, cert_dic, bin_an_buff, apkid_results, ) except: PrintException("[ERROR] Saving to Database Failed") context = get_context_from_analysis( app_dic, man_data_dic, man_an_dic, code_an_dic, cert_dic, bin_an_buff, apkid_results, ) context["average_cvss"], context["security_score"] = score( context["findings"] ) context["dynamic_analysis_done"] = os.path.exists( os.path.join(app_dic["app_dir"], "logcat.txt") ) context["VT_RESULT"] = None if settings.VT_ENABLED: vt = VirusTotal.VirusTotal() context["VT_RESULT"] = vt.get_result( os.path.join(app_dic["app_dir"], app_dic["md5"]) + ".apk", app_dic["md5"], ) template = "static_analysis/static_analysis.html" if api: return context else: return render(request, template, context) elif typ == "zip": # Check if in DB # pylint: disable=E1101 cert_dic = {} cert_dic["cert_info"] = "" cert_dic["issued"] = "" cert_dic["sha256Digest"] = False bin_an_buff = [] app_dic["strings"] = "" app_dic["zipped"] = "" # Above fields are only available for APK and not ZIP db_entry = StaticAnalyzerAndroid.objects.filter(MD5=app_dic["md5"]) if db_entry.exists() and rescan == "0": context = get_context_from_db_entry(db_entry) else: app_dic["app_file"] = app_dic["md5"] + ".zip" # NEW FILENAME app_dic["app_path"] = ( app_dic["app_dir"] + app_dic["app_file"] ) # APP PATH logger.info("Extracting ZIP") app_dic["files"] = unzip(app_dic["app_path"], app_dic["app_dir"]) # Check if Valid Directory Structure and get ZIP Type pro_type, valid = valid_android_zip(app_dic["app_dir"]) if valid and pro_type == "ios": logger.info("Redirecting to iOS Source Code Analyzer") if api: return {"type": "ios"} else: return HttpResponseRedirect( "/StaticAnalyzer_iOS/?name=" + app_dic["app_name"] + "&type=ios&checksum=" + app_dic["md5"] ) app_dic["certz"] = get_hardcoded_cert_keystore(app_dic["files"]) app_dic["zipped"] = pro_type logger.info("ZIP Type - " + pro_type) if valid and (pro_type in ["eclipse", "studio"]): # ANALYSIS BEGINS app_dic["size"] = ( str(file_size(app_dic["app_path"])) + "MB" ) # FILE SIZE app_dic["sha1"], app_dic["sha256"] = hash_gen( app_dic["app_path"] ) # Manifest XML app_dic["persed_xml"] = get_manifest( "", app_dic["app_dir"], app_dic["tools_dir"], pro_type, False, ) # Set manifest view link app_dic["mani"] = ( "../ManifestView/?md5=" + app_dic["md5"] + "&type=" + pro_type + "&bin=0" ) man_data_dic = manifest_data(app_dic["persed_xml"]) man_an_dic = manifest_analysis( app_dic["persed_xml"], man_data_dic ) # Get icon eclipse_res_path = os.path.join(app_dic["app_dir"], "res") studio_res_path = os.path.join( app_dic["app_dir"], "app", "src", "main", "res" ) if os.path.exists(eclipse_res_path): res_path = eclipse_res_path elif os.path.exists(studio_res_path): res_path = studio_res_path else: res_path = "" app_dic["icon_hidden"] = man_an_dic["icon_hidden"] app_dic["icon_found"] = False app_dic["icon_path"] = "" if res_path: app_dic["icon_path"] = find_icon_path_zip( res_path, man_data_dic["icons"] ) if app_dic["icon_path"]: app_dic["icon_found"] = True if app_dic["icon_path"]: if os.path.exists(app_dic["icon_path"]): shutil.copy2( app_dic["icon_path"], os.path.join( settings.DWD_DIR, app_dic["md5"] + "-icon.png" ), ) code_an_dic = code_analysis( app_dic["app_dir"], man_an_dic["permissons"], pro_type ) logger.info("Connecting to Database") try: # SAVE TO DB if rescan == "1": logger.info("Updating Database...") update_db_entry( app_dic, man_data_dic, man_an_dic, code_an_dic, cert_dic, bin_an_buff, {}, ) elif rescan == "0": logger.info("Saving to Database") create_db_entry( app_dic, man_data_dic, man_an_dic, code_an_dic, cert_dic, bin_an_buff, {}, ) except: PrintException("[ERROR] Saving to Database Failed") context = get_context_from_analysis( app_dic, man_data_dic, man_an_dic, code_an_dic, cert_dic, bin_an_buff, {}, ) else: msg = "This ZIP Format is not supported" if api: return print_n_send_error_response(request, msg, True) else: print_n_send_error_response(request, msg, False) return HttpResponseRedirect("/zip_format/") context["average_cvss"], context["security_score"] = score( context["findings"] ) template = "static_analysis/static_analysis_android_zip.html" if api: return context else: return render(request, template, context) else: logger.error( "Only APK,IPA and Zipped Android/iOS Source code supported now!" ) else: msg = "Hash match failed or Invalid file extension or file type" if api: return print_n_send_error_response(request, msg, True) else: return print_n_send_error_response(request, msg, False) except Exception as excep: msg = str(excep) exp = excep.__doc__ if api: return print_n_send_error_response(request, msg, True, exp) else: return print_n_send_error_response(request, msg, False, exp)
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def valid_android_zip(app_dir): """Test if this is an valid android zip.""" try: logger.info("Checking for ZIP Validity and Mode") # Eclipse man = os.path.isfile(os.path.join(app_dir, "AndroidManifest.xml")) src = os.path.exists(os.path.join(app_dir, "src/")) if man and src: return "eclipse", True # Studio man = os.path.isfile(os.path.join(app_dir, "app/src/main/AndroidManifest.xml")) src = os.path.exists(os.path.join(app_dir, "app/src/main/java/")) if man and src: return "studio", True # iOS Source xcode = [f for f in os.listdir(app_dir) if f.endswith(".xcodeproj")] if xcode: return "ios", True return "", False except: PrintException("Determining Upload type")
def valid_android_zip(app_dir): """Test if this is an valid android zip.""" try: logger.info("Checking for ZIP Validity and Mode") # Eclipse man = os.path.isfile(os.path.join(app_dir, "AndroidManifest.xml")) src = os.path.exists(os.path.join(app_dir, "src/")) if man and src: return "eclipse", True # Studio man = os.path.isfile(os.path.join(app_dir, "app/src/main/AndroidManifest.xml")) src = os.path.exists(os.path.join(app_dir, "app/src/main/java/")) if man and src: return "studio", True # iOS Source xcode = [f for f in os.listdir(app_dir) if f.endswith(".xcodeproj")] if xcode: return "ios", True return "", False except: PrintException("[ERROR] Determining Upload type")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def gen_downloads(app_dir, md5, icon_path=""): """Generate downloads for java and smali.""" try: logger.info("Generating Downloads") # For Java directory = os.path.join(app_dir, "java_source/") dwd_dir = os.path.join(settings.DWD_DIR, md5 + "-java.zip") zipf = zipfile.ZipFile(dwd_dir, "w") zipdir(directory, zipf) zipf.close() # For Smali directory = os.path.join(app_dir, "smali_source/") dwd_dir = os.path.join(settings.DWD_DIR, md5 + "-smali.zip") zipf = zipfile.ZipFile(dwd_dir, "w") zipdir(directory, zipf) zipf.close() # Icon icon_path = icon_path.encode("utf-8") if icon_path: if os.path.exists(icon_path): shutil.copy2( icon_path, os.path.join(settings.DWD_DIR, md5 + "-icon.png") ) except: PrintException("Generating Downloads")
def gen_downloads(app_dir, md5, icon_path=""): """Generate downloads for java and smali.""" try: logger.info("Generating Downloads") # For Java directory = os.path.join(app_dir, "java_source/") dwd_dir = os.path.join(settings.DWD_DIR, md5 + "-java.zip") zipf = zipfile.ZipFile(dwd_dir, "w") zipdir(directory, zipf) zipf.close() # For Smali directory = os.path.join(app_dir, "smali_source/") dwd_dir = os.path.join(settings.DWD_DIR, md5 + "-smali.zip") zipf = zipfile.ZipFile(dwd_dir, "w") zipdir(directory, zipf) zipf.close() # Icon icon_path = icon_path.encode("utf-8") if icon_path: if os.path.exists(icon_path): shutil.copy2( icon_path, os.path.join(settings.DWD_DIR, md5 + "-icon.png") ) except: PrintException("[ERROR] Generating Downloads")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def strings_jar(app_file, app_dir): """Extract the strings from an app.""" try: logger.info("Extracting Strings from APK") dat = [] apk_file = os.path.join(app_dir, app_file) and_a = apk.APK(apk_file) rsrc = and_a.get_android_resources() pkg = rsrc.get_packages_names()[0] rsrc.get_strings_resources() for i in rsrc.values[pkg].keys(): string = rsrc.values[pkg][i].get("string") if string is None: return dat for duo in string: dat.append('"' + duo[0] + '" : "' + duo[1] + '"') return dat except: PrintException("Extracting Strings from APK")
def strings_jar(app_file, app_dir): """Extract the strings from an app.""" try: logger.info("Extracting Strings from APK") dat = [] apk_file = os.path.join(app_dir, app_file) and_a = apk.APK(apk_file) rsrc = and_a.get_android_resources() pkg = rsrc.get_packages_names()[0] rsrc.get_strings_resources() for i in rsrc.values[pkg].keys(): string = rsrc.values[pkg][i].get("string") if string is None: return dat for duo in string: dat.append('"' + duo[0] + '" : "' + duo[1] + '"') return dat except: PrintException("[ERROR] Extracting Strings from APK")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def win_fix_java(tools_dir): """Runn JAVA path fix in Windows""" try: logger.info("Running JAVA path fix in Windows") dmy = os.path.join(tools_dir, "d2j2/d2j_invoke.tmp") org = os.path.join(tools_dir, "d2j2/d2j_invoke.bat") dat = "" with open(dmy, "r") as file_pointer: dat = file_pointer.read().replace("[xxx]", settings.JAVA_PATH + "java") with open(org, "w") as file_pointer: file_pointer.write(dat) except: PrintException("Running JAVA path fix in Windows")
def win_fix_java(tools_dir): """Runn JAVA path fix in Windows""" try: logger.info("Running JAVA path fix in Windows") dmy = os.path.join(tools_dir, "d2j2/d2j_invoke.tmp") org = os.path.join(tools_dir, "d2j2/d2j_invoke.bat") dat = "" with open(dmy, "r") as file_pointer: dat = file_pointer.read().replace("[xxx]", settings.JAVA_PATH + "java") with open(org, "w") as file_pointer: file_pointer.write(dat) except: PrintException("[ERROR] Running JAVA path fix in Windows")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def win_fix_python3(tools_dir): """Runn Python 3 path fix in Windows.""" try: logger.info("Running Python 3 path fix in Windows") python3_path = "" if len(settings.PYTHON3_PATH) > 2: python3_path = settings.python3_path else: pathenv = os.environ["path"] if pathenv: paths = pathenv.split(";") for path in paths: if "python3" in path.lower(): python3_path = path python3 = '"' + os.path.join(python3_path, "python") + '"' dmy = os.path.join(tools_dir, "enjarify/enjarify.tmp") org = os.path.join(tools_dir, "enjarify/enjarify.bat") dat = "" with open(dmy, "r") as file_pointer: dat = file_pointer.read().replace("[xxx]", python3) with open(org, "w") as file_pointer: file_pointer.write(dat) except: PrintException("Running Python 3 path fix in Windows")
def win_fix_python3(tools_dir): """Runn Python 3 path fix in Windows.""" try: logger.info("Running Python 3 path fix in Windows") python3_path = "" if len(settings.PYTHON3_PATH) > 2: python3_path = settings.python3_path else: pathenv = os.environ["path"] if pathenv: paths = pathenv.split(";") for path in paths: if "python3" in path.lower(): python3_path = path python3 = '"' + os.path.join(python3_path, "python") + '"' dmy = os.path.join(tools_dir, "enjarify/enjarify.tmp") org = os.path.join(tools_dir, "enjarify/enjarify.bat") dat = "" with open(dmy, "r") as file_pointer: dat = file_pointer.read().replace("[xxx]", python3) with open(org, "w") as file_pointer: file_pointer.write(dat) except: PrintException("[ERROR] Running Python 3 path fix in Windows")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def otool_analysis(tools_dir, bin_name, bin_path, bin_dir): """OTOOL Analysis of Binary""" try: otool_dict = {"libs": [], "anal": []} logger.info("Running Object Analysis of Binary : " + bin_name) otool_dict["libs"] = get_otool_out(tools_dir, "libs", bin_path, bin_dir) # PIE pie_dat = get_otool_out(tools_dir, "header", bin_path, bin_dir) if b"PIE" in pie_dat: pie_flag = { "issue": "fPIE -pie flag is Found", "status": SECURE, "description": """App is compiled with Position Independent Executable (PIE) flag. This enables Address Space Layout Randomization (ASLR), a memory protection mechanism for exploit mitigation.""", } else: pie_flag = { "issue": "fPIE -pie flag is not Found", "status": IN_SECURE, "description": """with Position Independent Executable (PIE) flag. So Address Space Layout Randomization (ASLR) is missing. ASLR is a memory protection mechanism for exploit mitigation.""", } # Stack Smashing Protection & ARC dat = get_otool_out(tools_dir, "symbols", bin_path, bin_dir) if b"stack_chk_guard" in dat: ssmash = { "issue": "fstack-protector-all flag is Found", "status": SECURE, "description": """App is compiled with Stack Smashing Protector (SSP) flag and is having protection against Stack Overflows/Stack Smashing Attacks.""", } else: ssmash = { "issue": "fstack-protector-all flag is not Found", "status": IN_SECURE, "description": """App is not compiled with Stack Smashing Protector (SSP) flag. It is vulnerable to Stack Overflows/Stack Smashing Attacks.""", } # ARC if b"_objc_release" in dat: arc_flag = { "issue": "fobjc-arc flag is Found", "status": SECURE, "description": """App is compiled with Automatic Reference Counting (ARC) flag. ARC is a compiler feature that provides automatic memory management of Objective-C objects and is an exploit mitigation mechanism against memory corruption vulnerabilities.""", } else: arc_flag = { "issue": "fobjc-arc flag is not Found", "status": IN_SECURE, "description": """App is not compiled with Automatic Reference Counting (ARC) flag. ARC is a compiler feature that provides automatic memory management of Objective-C objects and protects from memory corruption vulnerabilities.""", } banned_apis = {} baned = re.findall( b"_alloca|_gets|_memcpy|_printf|_scanf|_sprintf|_sscanf|_strcat|StrCat|_strcpy|" + b"StrCpy|_strlen|StrLen|_strncat|StrNCat|_strncpy|StrNCpy|_strtok|_swprintf|_vsnprintf|" + b"_vsprintf|_vswprintf|_wcscat|_wcscpy|_wcslen|_wcsncat|_wcsncpy|_wcstok|_wmemcpy|" + b"_fopen|_chmod|_chown|_stat|_mktemp", dat, ) baned = list(set(baned)) baned_s = b", ".join(baned) if len(baned_s) > 1: banned_apis = { "issue": "Binary make use of banned API(s)", "status": IN_SECURE, "description": "The binary may contain the following banned API(s) " + baned_s.decode("utf-8", "ignore") + ".", } weak_cryptos = {} weak_algo = re.findall( b"kCCAlgorithmDES|kCCAlgorithm3DES||kCCAlgorithmRC2|kCCAlgorithmRC4|" + b"kCCOptionECBMode|kCCOptionCBCMode", dat, ) weak_algo = list(set(weak_algo)) weak_algo_s = b", ".join(weak_algo) if len(weak_algo_s) > 1: weak_cryptos = { "issue": "Binary make use of some Weak Crypto API(s)", "status": IN_SECURE, "description": "The binary may use the following weak crypto API(s) " + weak_algo_s.decode("utf-8", "ignore") + ".", } crypto = {} crypto_algo = re.findall( b"CCKeyDerivationPBKDF|CCCryptorCreate|CCCryptorCreateFromData|" + b"CCCryptorRelease|CCCryptorUpdate|CCCryptorFinal|CCCryptorGetOutputLength|" + b"CCCryptorReset|CCCryptorRef|kCCEncrypt|kCCDecrypt|kCCAlgorithmAES128|" + b"kCCKeySizeAES128|kCCKeySizeAES192|kCCKeySizeAES256|kCCAlgorithmCAST|" + b"SecCertificateGetTypeID|SecIdentityGetTypeID|SecKeyGetTypeID|SecPolicyGetTypeID|" + b"SecTrustGetTypeID|SecCertificateCreateWithData|SecCertificateCreateFromData|" + b"SecCertificateCopyData|SecCertificateAddToKeychain|SecCertificateGetData|" + b"SecCertificateCopySubjectSummary|SecIdentityCopyCertificate|" + b"SecIdentityCopyPrivateKey|SecPKCS12Import|SecKeyGeneratePair|SecKeyEncrypt|" + b"SecKeyDecrypt|SecKeyRawSign|SecKeyRawVerify|SecKeyGetBlockSize|" + b"SecPolicyCopyProperties|SecPolicyCreateBasicX509|SecPolicyCreateSSL|" + b"SecTrustCopyCustomAnchorCertificates|SecTrustCopyExceptions|" + b"SecTrustCopyProperties|SecTrustCopyPolicies|SecTrustCopyPublicKey|" + b"SecTrustCreateWithCertificates|SecTrustEvaluate|SecTrustEvaluateAsync|" + b"SecTrustGetCertificateCount|SecTrustGetCertificateAtIndex|SecTrustGetTrustResult|" + b"SecTrustGetVerifyTime|SecTrustSetAnchorCertificates|" + b"SecTrustSetAnchorCertificatesOnly|SecTrustSetExceptions|SecTrustSetPolicies|" + b"SecTrustSetVerifyDate|SecCertificateRef|" + b"SecIdentityRef|SecKeyRef|SecPolicyRef|SecTrustRef", dat, ) crypto_algo = list(set(crypto_algo)) crypto_algo_s = b", ".join(crypto_algo) if len(crypto_algo_s) > 1: crypto = { "issue": "Binary make use of the following Crypto API(s)", "status": "Info", "description": "The binary may use the following crypto API(s) " + crypto_algo_s.decode("utf-8", "ignore") + ".", } weak_hashes = {} weak_hash_algo = re.findall( b"CC_MD2_Init|CC_MD2_Update|CC_MD2_Final|CC_MD2|MD2_Init|" + b"MD2_Update|MD2_Final|CC_MD4_Init|CC_MD4_Update|CC_MD4_Final|CC_MD4|MD4_Init|" + b"MD4_Update|MD4_Final|CC_MD5_Init|CC_MD5_Update|CC_MD5_Final|CC_MD5|MD5_Init|" + b"MD5_Update|MD5_Final|MD5Init|MD5Update|MD5Final|CC_SHA1_Init|CC_SHA1_Update|" + b"CC_SHA1_Final|CC_SHA1|SHA1_Init|SHA1_Update|SHA1_Final", dat, ) weak_hash_algo = list(set(weak_hash_algo)) weak_hash_algo_s = b", ".join(weak_hash_algo) if len(weak_hash_algo_s) > 1: weak_hashe = { "issue": "Binary make use of the following Weak HASH API(s)", "status": IN_SECURE, "description": "The binary may use the following weak hash API(s) " + weak_hash_algo_s.decode("utf-8", "ignore") + ".", } hashes = {} hash_algo = re.findall( b"CC_SHA224_Init|CC_SHA224_Update|CC_SHA224_Final|CC_SHA224|" + b"SHA224_Init|SHA224_Update|SHA224_Final|CC_SHA256_Init|CC_SHA256_Update|" + b"CC_SHA256_Final|CC_SHA256|SHA256_Init|SHA256_Update|SHA256_Final|" + b"CC_SHA384_Init|CC_SHA384_Update|CC_SHA384_Final|CC_SHA384|SHA384_Init|" + b"SHA384_Update|SHA384_Final|CC_SHA512_Init|CC_SHA512_Update|CC_SHA512_Final|" + b"CC_SHA512|SHA512_Init|SHA512_Update|SHA512_Final", dat, ) hash_algo = list(set(hash_algo)) hash_algo_s = b", ".join(hash_algo) if len(hash_algo_s) > 1: hashes = { "issue": "Binary make use of the following HASH API(s)", "status": INFO, "description": "The binary may use the following hash API(s) " + hash_algo_s.decode("utf-8", "ignore") + ".", } randoms = {} rand_algo = re.findall(b"_srand|_random", dat) rand_algo = list(set(rand_algo)) rand_algo_s = b", ".join(rand_algo) if len(rand_algo_s) > 1: randoms = { "issue": "Binary make use of the insecure Random Function(s)", "status": IN_SECURE, "description": "The binary may use the following insecure Random Function(s) " + rand_algo_s.decode("utf-8", "ignore") + ".", } logging = {} log = re.findall(b"_NSLog", dat) log = list(set(log)) log_s = b", ".join(log) if len(log_s) > 1: logging = { "issue": "Binary make use of Logging Function", "status": INFO, "description": "The binary may use NSLog function for logging.", } malloc = {} mal = re.findall(b"_malloc", dat) mal = list(set(mal)) mal_s = b", ".join(mal) if len(mal_s) > 1: malloc = { "issue": "Binary make use of malloc Function", "status": IN_SECURE, "description": "The binary may use malloc function instead of calloc.", } debug = {} ptrace = re.findall(b"_ptrace", dat) ptrace = list(set(ptrace)) ptrace_s = b", ".join(ptrace) if len(ptrace_s) > 1: debug = { "issue": "Binary calls ptrace Function for anti-debugging.", "status": WARNING, "description": """The binary may use ptrace function. It can be used to detect and prevent debuggers. Ptrace is not a public API and Apps that use non-public APIs will be rejected from AppStore. """, } otool_dict["anal"] = [ pie_flag, ssmash, arc_flag, banned_apis, weak_cryptos, crypto, weak_hashes, hashes, randoms, logging, malloc, debug, ] return otool_dict except: PrintException("Performing Object Analysis of Binary")
def otool_analysis(tools_dir, bin_name, bin_path, bin_dir): """OTOOL Analysis of Binary""" try: otool_dict = {"libs": [], "anal": []} logger.info("Running Object Analysis of Binary : " + bin_name) otool_dict["libs"] = get_otool_out(tools_dir, "libs", bin_path, bin_dir) # PIE pie_dat = get_otool_out(tools_dir, "header", bin_path, bin_dir) if b"PIE" in pie_dat: pie_flag = { "issue": "fPIE -pie flag is Found", "status": SECURE, "description": """App is compiled with Position Independent Executable (PIE) flag. This enables Address Space Layout Randomization (ASLR), a memory protection mechanism for exploit mitigation.""", } else: pie_flag = { "issue": "fPIE -pie flag is not Found", "status": IN_SECURE, "description": """with Position Independent Executable (PIE) flag. So Address Space Layout Randomization (ASLR) is missing. ASLR is a memory protection mechanism for exploit mitigation.""", } # Stack Smashing Protection & ARC dat = get_otool_out(tools_dir, "symbols", bin_path, bin_dir) if b"stack_chk_guard" in dat: ssmash = { "issue": "fstack-protector-all flag is Found", "status": SECURE, "description": """App is compiled with Stack Smashing Protector (SSP) flag and is having protection against Stack Overflows/Stack Smashing Attacks.""", } else: ssmash = { "issue": "fstack-protector-all flag is not Found", "status": IN_SECURE, "description": """App is not compiled with Stack Smashing Protector (SSP) flag. It is vulnerable to Stack Overflows/Stack Smashing Attacks.""", } # ARC if b"_objc_release" in dat: arc_flag = { "issue": "fobjc-arc flag is Found", "status": SECURE, "description": """App is compiled with Automatic Reference Counting (ARC) flag. ARC is a compiler feature that provides automatic memory management of Objective-C objects and is an exploit mitigation mechanism against memory corruption vulnerabilities.""", } else: arc_flag = { "issue": "fobjc-arc flag is not Found", "status": IN_SECURE, "description": """App is not compiled with Automatic Reference Counting (ARC) flag. ARC is a compiler feature that provides automatic memory management of Objective-C objects and protects from memory corruption vulnerabilities.""", } banned_apis = {} baned = re.findall( b"_alloca|_gets|_memcpy|_printf|_scanf|_sprintf|_sscanf|_strcat|StrCat|_strcpy|" + b"StrCpy|_strlen|StrLen|_strncat|StrNCat|_strncpy|StrNCpy|_strtok|_swprintf|_vsnprintf|" + b"_vsprintf|_vswprintf|_wcscat|_wcscpy|_wcslen|_wcsncat|_wcsncpy|_wcstok|_wmemcpy|" + b"_fopen|_chmod|_chown|_stat|_mktemp", dat, ) baned = list(set(baned)) baned_s = b", ".join(baned) if len(baned_s) > 1: banned_apis = { "issue": "Binary make use of banned API(s)", "status": IN_SECURE, "description": "The binary may contain the following banned API(s) " + baned_s.decode("utf-8", "ignore") + ".", } weak_cryptos = {} weak_algo = re.findall( b"kCCAlgorithmDES|kCCAlgorithm3DES||kCCAlgorithmRC2|kCCAlgorithmRC4|" + b"kCCOptionECBMode|kCCOptionCBCMode", dat, ) weak_algo = list(set(weak_algo)) weak_algo_s = b", ".join(weak_algo) if len(weak_algo_s) > 1: weak_cryptos = { "issue": "Binary make use of some Weak Crypto API(s)", "status": IN_SECURE, "description": "The binary may use the following weak crypto API(s) " + weak_algo_s.decode("utf-8", "ignore") + ".", } crypto = {} crypto_algo = re.findall( b"CCKeyDerivationPBKDF|CCCryptorCreate|CCCryptorCreateFromData|" + b"CCCryptorRelease|CCCryptorUpdate|CCCryptorFinal|CCCryptorGetOutputLength|" + b"CCCryptorReset|CCCryptorRef|kCCEncrypt|kCCDecrypt|kCCAlgorithmAES128|" + b"kCCKeySizeAES128|kCCKeySizeAES192|kCCKeySizeAES256|kCCAlgorithmCAST|" + b"SecCertificateGetTypeID|SecIdentityGetTypeID|SecKeyGetTypeID|SecPolicyGetTypeID|" + b"SecTrustGetTypeID|SecCertificateCreateWithData|SecCertificateCreateFromData|" + b"SecCertificateCopyData|SecCertificateAddToKeychain|SecCertificateGetData|" + b"SecCertificateCopySubjectSummary|SecIdentityCopyCertificate|" + b"SecIdentityCopyPrivateKey|SecPKCS12Import|SecKeyGeneratePair|SecKeyEncrypt|" + b"SecKeyDecrypt|SecKeyRawSign|SecKeyRawVerify|SecKeyGetBlockSize|" + b"SecPolicyCopyProperties|SecPolicyCreateBasicX509|SecPolicyCreateSSL|" + b"SecTrustCopyCustomAnchorCertificates|SecTrustCopyExceptions|" + b"SecTrustCopyProperties|SecTrustCopyPolicies|SecTrustCopyPublicKey|" + b"SecTrustCreateWithCertificates|SecTrustEvaluate|SecTrustEvaluateAsync|" + b"SecTrustGetCertificateCount|SecTrustGetCertificateAtIndex|SecTrustGetTrustResult|" + b"SecTrustGetVerifyTime|SecTrustSetAnchorCertificates|" + b"SecTrustSetAnchorCertificatesOnly|SecTrustSetExceptions|SecTrustSetPolicies|" + b"SecTrustSetVerifyDate|SecCertificateRef|" + b"SecIdentityRef|SecKeyRef|SecPolicyRef|SecTrustRef", dat, ) crypto_algo = list(set(crypto_algo)) crypto_algo_s = b", ".join(crypto_algo) if len(crypto_algo_s) > 1: crypto = { "issue": "Binary make use of the following Crypto API(s)", "status": "Info", "description": "The binary may use the following crypto API(s) " + crypto_algo_s.decode("utf-8", "ignore") + ".", } weak_hashes = {} weak_hash_algo = re.findall( b"CC_MD2_Init|CC_MD2_Update|CC_MD2_Final|CC_MD2|MD2_Init|" + b"MD2_Update|MD2_Final|CC_MD4_Init|CC_MD4_Update|CC_MD4_Final|CC_MD4|MD4_Init|" + b"MD4_Update|MD4_Final|CC_MD5_Init|CC_MD5_Update|CC_MD5_Final|CC_MD5|MD5_Init|" + b"MD5_Update|MD5_Final|MD5Init|MD5Update|MD5Final|CC_SHA1_Init|CC_SHA1_Update|" + b"CC_SHA1_Final|CC_SHA1|SHA1_Init|SHA1_Update|SHA1_Final", dat, ) weak_hash_algo = list(set(weak_hash_algo)) weak_hash_algo_s = b", ".join(weak_hash_algo) if len(weak_hash_algo_s) > 1: weak_hashe = { "issue": "Binary make use of the following Weak HASH API(s)", "status": IN_SECURE, "description": "The binary may use the following weak hash API(s) " + weak_hash_algo_s.decode("utf-8", "ignore") + ".", } hashes = {} hash_algo = re.findall( b"CC_SHA224_Init|CC_SHA224_Update|CC_SHA224_Final|CC_SHA224|" + b"SHA224_Init|SHA224_Update|SHA224_Final|CC_SHA256_Init|CC_SHA256_Update|" + b"CC_SHA256_Final|CC_SHA256|SHA256_Init|SHA256_Update|SHA256_Final|" + b"CC_SHA384_Init|CC_SHA384_Update|CC_SHA384_Final|CC_SHA384|SHA384_Init|" + b"SHA384_Update|SHA384_Final|CC_SHA512_Init|CC_SHA512_Update|CC_SHA512_Final|" + b"CC_SHA512|SHA512_Init|SHA512_Update|SHA512_Final", dat, ) hash_algo = list(set(hash_algo)) hash_algo_s = b", ".join(hash_algo) if len(hash_algo_s) > 1: hashes = { "issue": "Binary make use of the following HASH API(s)", "status": INFO, "description": "The binary may use the following hash API(s) " + hash_algo_s.decode("utf-8", "ignore") + ".", } randoms = {} rand_algo = re.findall(b"_srand|_random", dat) rand_algo = list(set(rand_algo)) rand_algo_s = b", ".join(rand_algo) if len(rand_algo_s) > 1: randoms = { "issue": "Binary make use of the insecure Random Function(s)", "status": IN_SECURE, "description": "The binary may use the following insecure Random Function(s) " + rand_algo_s.decode("utf-8", "ignore") + ".", } logging = {} log = re.findall(b"_NSLog", dat) log = list(set(log)) log_s = b", ".join(log) if len(log_s) > 1: logging = { "issue": "Binary make use of Logging Function", "status": INFO, "description": "The binary may use NSLog function for logging.", } malloc = {} mal = re.findall(b"_malloc", dat) mal = list(set(mal)) mal_s = b", ".join(mal) if len(mal_s) > 1: malloc = { "issue": "Binary make use of malloc Function", "status": IN_SECURE, "description": "The binary may use malloc function instead of calloc.", } debug = {} ptrace = re.findall(b"_ptrace", dat) ptrace = list(set(ptrace)) ptrace_s = b", ".join(ptrace) if len(ptrace_s) > 1: debug = { "issue": "Binary calls ptrace Function for anti-debugging.", "status": WARNING, "description": """The binary may use ptrace function. It can be used to detect and prevent debuggers. Ptrace is not a public API and Apps that use non-public APIs will be rejected from AppStore. """, } otool_dict["anal"] = [ pie_flag, ssmash, arc_flag, banned_apis, weak_cryptos, crypto, weak_hashes, hashes, randoms, logging, malloc, debug, ] return otool_dict except: PrintException("[ERROR] Performing Object Analysis of Binary")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def class_dump_z(tools_dir, bin_path, app_dir): """Running Classdumpz on binary""" try: webview = {} if platform.system() == "Darwin": logger.info("Running class-dump-z against the binary for dumping classes") if len(settings.CLASSDUMPZ_BINARY) > 0 and isFileExists( settings.CLASSDUMPZ_BINARY ): class_dump_z_bin = settings.CLASSDUMPZ_BINARY else: class_dump_z_bin = os.path.join(tools_dir, "class-dump-z") subprocess.call(["chmod", "777", class_dump_z_bin]) args = [class_dump_z_bin, bin_path] elif platform.system() == "Linux": logger.info("Running jtool against the binary for dumping classes") if len(settings.JTOOL_BINARY) > 0 and isFileExists(settings.JTOOL_BINARY): jtool_bin = settings.JTOOL_BINARY else: jtool_bin = os.path.join(tools_dir, "jtool.ELF64") subprocess.call(["chmod", "777", jtool_bin]) args = [jtool_bin, "-arch", "arm", "-d", "objc", "-v", bin_path] else: # Platform not supported return {} classdump = subprocess.check_output(args) dump_file = os.path.join(app_dir, "classdump.txt") with open(dump_file, "w") as flip: flip.write(classdump.decode("utf-8", "ignore")) if b"UIWebView" in classdump: webview = { "issue": "Binary uses WebView Component.", "status": INFO, "description": "The binary may use WebView Component.", } return webview except: logger.warning("class-dump-z does not work on iOS apps developed in Swift") PrintException("Cannot perform class dump")
def class_dump_z(tools_dir, bin_path, app_dir): """Running Classdumpz on binary""" try: webview = {} if platform.system() == "Darwin": logger.info("Running class-dump-z against the binary for dumping classes") if len(settings.CLASSDUMPZ_BINARY) > 0 and isFileExists( settings.CLASSDUMPZ_BINARY ): class_dump_z_bin = settings.CLASSDUMPZ_BINARY else: class_dump_z_bin = os.path.join(tools_dir, "class-dump-z") subprocess.call(["chmod", "777", class_dump_z_bin]) args = [class_dump_z_bin, bin_path] elif platform.system() == "Linux": logger.info("Running jtool against the binary for dumping classes") if len(settings.JTOOL_BINARY) > 0 and isFileExists(settings.JTOOL_BINARY): jtool_bin = settings.JTOOL_BINARY else: jtool_bin = os.path.join(tools_dir, "jtool.ELF64") subprocess.call(["chmod", "777", jtool_bin]) args = [jtool_bin, "-arch", "arm", "-d", "objc", "-v", bin_path] else: # Platform not supported return {} classdump = subprocess.check_output(args) dump_file = os.path.join(app_dir, "classdump.txt") with open(dump_file, "w") as flip: flip.write(classdump.decode("utf-8", "ignore")) if b"UIWebView" in classdump: webview = { "issue": "Binary uses WebView Component.", "status": INFO, "description": "The binary may use WebView Component.", } return webview except: logger.warning("class-dump-z does not work on iOS apps developed in Swift") PrintException("[ERROR] - Cannot perform class dump")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def strings_on_ipa(bin_path): """Extract Strings from IPA""" try: logger.info("Running strings against the Binary") unique_str = [] unique_str = list(set(strings_util(bin_path))) # Make unique unique_str = [escape(ip_str) for ip_str in unique_str] # Escape evil strings return unique_str except: PrintException("Running strings against the Binary")
def strings_on_ipa(bin_path): """Extract Strings from IPA""" try: logger.info("Running strings against the Binary") unique_str = [] unique_str = list(set(strings_util(bin_path))) # Make unique unique_str = [escape(ip_str) for ip_str in unique_str] # Escape evil strings return unique_str except: PrintException("[ERROR] - Running strings against the Binary")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def binary_analysis(src, tools_dir, app_dir, executable_name): """Binary Analysis of IPA""" try: binary_analysis_dict = {} logger.info("Starting Binary Analysis") dirs = os.listdir(src) dot_app_dir = "" for dir_ in dirs: if dir_.endswith(".app"): dot_app_dir = dir_ break # Bin Dir - Dir/Payload/x.app/ bin_dir = os.path.join(src, dot_app_dir) if executable_name is None: bin_name = dot_app_dir.replace(".app", "") else: bin_name = executable_name # Bin Path - Dir/Payload/x.app/x bin_path = os.path.join(bin_dir, bin_name) binary_analysis_dict["libs"] = [] binary_analysis_dict["bin_res"] = [] binary_analysis_dict["strings"] = [] if not isFileExists(bin_path): logger.warning("MobSF Cannot find binary in " + bin_path) logger.warning("Skipping Otool, Classdump and Strings") else: otool_dict = otool_analysis(tools_dir, bin_name, bin_path, bin_dir) cls_dump = class_dump_z(tools_dir, bin_path, app_dir) # Classdumpz can fail on swift coded binaries if not cls_dump: cls_dump = {} strings_in_ipa = strings_on_ipa(bin_path) otool_dict["anal"] = list(filter(None, otool_dict["anal"] + [cls_dump])) binary_analysis_dict["libs"] = otool_dict["libs"] binary_analysis_dict["bin_res"] = otool_dict["anal"] binary_analysis_dict["strings"] = strings_in_ipa return binary_analysis_dict except: PrintException("iOS Binary Analysis")
def binary_analysis(src, tools_dir, app_dir, executable_name): """Binary Analysis of IPA""" try: binary_analysis_dict = {} logger.info("Starting Binary Analysis") dirs = os.listdir(src) dot_app_dir = "" for dir_ in dirs: if dir_.endswith(".app"): dot_app_dir = dir_ break # Bin Dir - Dir/Payload/x.app/ bin_dir = os.path.join(src, dot_app_dir) if executable_name is None: bin_name = dot_app_dir.replace(".app", "") else: bin_name = executable_name # Bin Path - Dir/Payload/x.app/x bin_path = os.path.join(bin_dir, bin_name) binary_analysis_dict["libs"] = [] binary_analysis_dict["bin_res"] = [] binary_analysis_dict["strings"] = [] if not isFileExists(bin_path): logger.warning("MobSF Cannot find binary in " + bin_path) logger.warning("Skipping Otool, Classdump and Strings") else: otool_dict = otool_analysis(tools_dir, bin_name, bin_path, bin_dir) cls_dump = class_dump_z(tools_dir, bin_path, app_dir) # Classdumpz can fail on swift coded binaries if not cls_dump: cls_dump = {} strings_in_ipa = strings_on_ipa(bin_path) otool_dict["anal"] = list(filter(None, otool_dict["anal"] + [cls_dump])) binary_analysis_dict["libs"] = otool_dict["libs"] binary_analysis_dict["bin_res"] = otool_dict["anal"] binary_analysis_dict["strings"] = strings_in_ipa return binary_analysis_dict except: PrintException("[ERROR] iOS Binary Analysis")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def ios_source_analysis(src): """iOS Objective-C Code Analysis""" try: logger.info("Starting iOS Source Code and PLIST Analysis") api_rules = ios_apis.CODE_APIS code_rules = ios_rules.CODE_RULES code_findings = {} api_findings = {} email_n_file = [] url_n_file = [] url_list = [] domains = {} for dirname, _, files in os.walk(src): for jfile in files: if jfile.endswith(".m"): jfile_path = os.path.join(src, dirname, jfile) if "+" in jfile: new_path = os.path.join(src, dirname, jfile.replace("+", "x")) shutil.move(jfile_path, new_path) jfile_path = new_path dat = "" with io.open( jfile_path, mode="r", encoding="utf8", errors="ignore" ) as flip: dat = flip.read() # Code Analysis relative_src_path = jfile_path.replace(src, "") code_rule_matcher( code_findings, [], dat, relative_src_path, code_rules ) # API Analysis api_rule_matcher( api_findings, [], dat, relative_src_path, api_rules ) # Extract URLs and Emails urls, urls_nf, emails_nf = url_n_email_extract( dat, relative_src_path ) url_list.extend(urls) url_n_file.extend(urls_nf) email_n_file.extend(emails_nf) # Domain Extraction and Malware Check logger.info("Performing Malware Check on extracted Domains") domains = malware_check(list(set(url_list))) logger.info("Finished Code Analysis, Email and URL Extraction") code_analysis_dict = { "api": api_findings, "code_anal": code_findings, "urlnfile": url_n_file, "domains": domains, "emailnfile": email_n_file, } return code_analysis_dict except: PrintException("iOS Source Code Analysis")
def ios_source_analysis(src): """iOS Objective-C Code Analysis""" try: logger.info("Starting iOS Source Code and PLIST Analysis") api_rules = ios_apis.CODE_APIS code_rules = ios_rules.CODE_RULES code_findings = {} api_findings = {} email_n_file = [] url_n_file = [] url_list = [] domains = {} for dirname, _, files in os.walk(src): for jfile in files: if jfile.endswith(".m"): jfile_path = os.path.join(src, dirname, jfile) if "+" in jfile: new_path = os.path.join(src, dirname, jfile.replace("+", "x")) shutil.move(jfile_path, new_path) jfile_path = new_path dat = "" with io.open( jfile_path, mode="r", encoding="utf8", errors="ignore" ) as flip: dat = flip.read() # Code Analysis relative_src_path = jfile_path.replace(src, "") code_rule_matcher( code_findings, [], dat, relative_src_path, code_rules ) # API Analysis api_rule_matcher( api_findings, [], dat, relative_src_path, api_rules ) # Extract URLs and Emails urls, urls_nf, emails_nf = url_n_email_extract( dat, relative_src_path ) url_list.extend(urls) url_n_file.extend(urls_nf) email_n_file.extend(emails_nf) # Domain Extraction and Malware Check logger.info("Performing Malware Check on extracted Domains") domains = malware_check(list(set(url_list))) logger.info("Finished Code Analysis, Email and URL Extraction") code_analysis_dict = { "api": api_findings, "code_anal": code_findings, "urlnfile": url_n_file, "domains": domains, "emailnfile": email_n_file, } return code_analysis_dict except: PrintException("[ERROR] iOS Source Code Analysis")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def get_context_from_analysis_ipa(app_dict, info_dict, bin_dict, files, sfiles): """Get the context for IPA from analysis results""" try: context = { "title": "Static Analysis", "file_name": app_dict["file_name"], "size": app_dict["size"], "md5": app_dict["md5_hash"], "sha1": app_dict["sha1"], "sha256": app_dict["sha256"], "plist": info_dict["plist_xml"], "bin_name": info_dict["bin_name"], "id": info_dict["id"], "build": info_dict["build"], "version": info_dict["bundle_version_name"], "sdk": info_dict["sdk"], "pltfm": info_dict["pltfm"], "min": info_dict["min"], "bin_anal": bin_dict["bin_res"], "libs": bin_dict["libs"], "files": files, "file_analysis": sfiles, "strings": bin_dict["strings"], "permissions": info_dict["permissions"], "insecure_connections": info_dict["inseccon"], "bundle_name": info_dict["bundle_name"], "bundle_url_types": info_dict["bundle_url_types"], "bundle_supported_platforms": info_dict["bundle_supported_platforms"], "bundle_localizations": info_dict["bundle_localizations"], } return context except: PrintException("Rendering to Template")
def get_context_from_analysis_ipa(app_dict, info_dict, bin_dict, files, sfiles): """Get the context for IPA from analysis results""" try: context = { "title": "Static Analysis", "file_name": app_dict["file_name"], "size": app_dict["size"], "md5": app_dict["md5_hash"], "sha1": app_dict["sha1"], "sha256": app_dict["sha256"], "plist": info_dict["plist_xml"], "bin_name": info_dict["bin_name"], "id": info_dict["id"], "build": info_dict["build"], "version": info_dict["bundle_version_name"], "sdk": info_dict["sdk"], "pltfm": info_dict["pltfm"], "min": info_dict["min"], "bin_anal": bin_dict["bin_res"], "libs": bin_dict["libs"], "files": files, "file_analysis": sfiles, "strings": bin_dict["strings"], "permissions": info_dict["permissions"], "insecure_connections": info_dict["inseccon"], "bundle_name": info_dict["bundle_name"], "bundle_url_types": info_dict["bundle_url_types"], "bundle_supported_platforms": info_dict["bundle_supported_platforms"], "bundle_localizations": info_dict["bundle_localizations"], } return context except: PrintException("[ERROR] Rendering to Template")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def get_context_from_db_entry_ipa(db_entry): """Return the context for IPA from DB""" try: logger.info("Analysis is already Done. Fetching data from the DB...") context = { "title": db_entry[0].TITLE, "file_name": db_entry[0].FILE_NAME, "size": db_entry[0].SIZE, "md5": db_entry[0].MD5, "sha1": db_entry[0].SHA1, "sha256": db_entry[0].SHA256, "plist": db_entry[0].INFOPLIST, "bin_name": db_entry[0].BINNAME, "id": db_entry[0].IDF, "build": db_entry[0].BUILD, "version": db_entry[0].VERSION, "sdk": db_entry[0].SDK, "pltfm": db_entry[0].PLTFM, "min": db_entry[0].MINX, "bin_anal": python_list(db_entry[0].BIN_ANAL), "libs": python_list(db_entry[0].LIBS), "files": python_list(db_entry[0].FILES), "file_analysis": python_list(db_entry[0].SFILESX), "strings": python_list(db_entry[0].STRINGS), "permissions": python_list(db_entry[0].PERMISSIONS), "insecure_connections": python_list(db_entry[0].INSECCON), "bundle_name": db_entry[0].BUNDLE_NAME, "bundle_url_types": python_list(db_entry[0].BUNDLE_URL_TYPES), "bundle_supported_platforms": python_list( db_entry[0].BUNDLE_SUPPORTED_PLATFORMS ), "bundle_localizations": python_list(db_entry[0].BUNDLE_LOCALIZATIONS), } return context except: PrintException("Fetching from DB")
def get_context_from_db_entry_ipa(db_entry): """Return the context for IPA from DB""" try: logger.info("Analysis is already Done. Fetching data from the DB...") context = { "title": db_entry[0].TITLE, "file_name": db_entry[0].FILE_NAME, "size": db_entry[0].SIZE, "md5": db_entry[0].MD5, "sha1": db_entry[0].SHA1, "sha256": db_entry[0].SHA256, "plist": db_entry[0].INFOPLIST, "bin_name": db_entry[0].BINNAME, "id": db_entry[0].IDF, "build": db_entry[0].BUILD, "version": db_entry[0].VERSION, "sdk": db_entry[0].SDK, "pltfm": db_entry[0].PLTFM, "min": db_entry[0].MINX, "bin_anal": python_list(db_entry[0].BIN_ANAL), "libs": python_list(db_entry[0].LIBS), "files": python_list(db_entry[0].FILES), "file_analysis": python_list(db_entry[0].SFILESX), "strings": python_list(db_entry[0].STRINGS), "permissions": python_list(db_entry[0].PERMISSIONS), "insecure_connections": python_list(db_entry[0].INSECCON), "bundle_name": db_entry[0].BUNDLE_NAME, "bundle_url_types": python_list(db_entry[0].BUNDLE_URL_TYPES), "bundle_supported_platforms": python_list( db_entry[0].BUNDLE_SUPPORTED_PLATFORMS ), "bundle_localizations": python_list(db_entry[0].BUNDLE_LOCALIZATIONS), } return context except: PrintException("[ERROR] Fetching from DB")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def update_db_entry_ipa(app_dict, info_dict, bin_dict, files, sfiles): """Update an IPA DB entry""" try: # pylint: disable=E1101 StaticAnalyzerIPA.objects.filter(MD5=app_dict["md5_hash"]).update( TITLE="Static Analysis", FILE_NAME=app_dict["file_name"], SIZE=app_dict["size"], MD5=app_dict["md5_hash"], SHA1=app_dict["sha1"], SHA256=app_dict["sha256"], INFOPLIST=info_dict["plist_xml"], BINNAME=info_dict["bin_name"], IDF=info_dict["id"], BUILD=info_dict["build"], VERSION=info_dict["bundle_version_name"], SDK=info_dict["sdk"], PLTFM=info_dict["pltfm"], MINX=info_dict["min"], BIN_ANAL=bin_dict["bin_res"], LIBS=bin_dict["libs"], FILES=files, SFILESX=sfiles, STRINGS=bin_dict["strings"], PERMISSIONS=info_dict["permissions"], INSECCON=info_dict["inseccon"], BUNDLE_NAME=info_dict["bundle_name"], BUNDLE_URL_TYPES=info_dict["bundle_url_types"], BUNDLE_SUPPORTED_PLATFORMS=info_dict["bundle_supported_platforms"], BUNDLE_LOCALIZATIONS=info_dict["bundle_localizations"], ) except: PrintException("Updating DB")
def update_db_entry_ipa(app_dict, info_dict, bin_dict, files, sfiles): """Update an IPA DB entry""" try: # pylint: disable=E1101 StaticAnalyzerIPA.objects.filter(MD5=app_dict["md5_hash"]).update( TITLE="Static Analysis", FILE_NAME=app_dict["file_name"], SIZE=app_dict["size"], MD5=app_dict["md5_hash"], SHA1=app_dict["sha1"], SHA256=app_dict["sha256"], INFOPLIST=info_dict["plist_xml"], BINNAME=info_dict["bin_name"], IDF=info_dict["id"], BUILD=info_dict["build"], VERSION=info_dict["bundle_version_name"], SDK=info_dict["sdk"], PLTFM=info_dict["pltfm"], MINX=info_dict["min"], BIN_ANAL=bin_dict["bin_res"], LIBS=bin_dict["libs"], FILES=files, SFILESX=sfiles, STRINGS=bin_dict["strings"], PERMISSIONS=info_dict["permissions"], INSECCON=info_dict["inseccon"], BUNDLE_NAME=info_dict["bundle_name"], BUNDLE_URL_TYPES=info_dict["bundle_url_types"], BUNDLE_SUPPORTED_PLATFORMS=info_dict["bundle_supported_platforms"], BUNDLE_LOCALIZATIONS=info_dict["bundle_localizations"], ) except: PrintException("[ERROR] Updating DB")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def create_db_entry_ipa(app_dict, info_dict, bin_dict, files, sfiles): """Save an IOS IPA DB entry""" try: static_db = StaticAnalyzerIPA( TITLE="Static Analysis", FILE_NAME=app_dict["file_name"], SIZE=app_dict["size"], MD5=app_dict["md5_hash"], SHA1=app_dict["sha1"], SHA256=app_dict["sha256"], INFOPLIST=info_dict["plist_xml"], BINNAME=info_dict["bin_name"], IDF=info_dict["id"], BUILD=info_dict["build"], VERSION=info_dict["bundle_version_name"], SDK=info_dict["sdk"], PLTFM=info_dict["pltfm"], MINX=info_dict["min"], BIN_ANAL=bin_dict["bin_res"], LIBS=bin_dict["libs"], FILES=files, SFILESX=sfiles, STRINGS=bin_dict["strings"], PERMISSIONS=info_dict["permissions"], INSECCON=info_dict["inseccon"], BUNDLE_NAME=info_dict["bundle_name"], BUNDLE_URL_TYPES=info_dict["bundle_url_types"], BUNDLE_SUPPORTED_PLATFORMS=info_dict["bundle_supported_platforms"], BUNDLE_LOCALIZATIONS=info_dict["bundle_localizations"], ) static_db.save() except: PrintException("Saving to DB")
def create_db_entry_ipa(app_dict, info_dict, bin_dict, files, sfiles): """Save an IOS IPA DB entry""" try: static_db = StaticAnalyzerIPA( TITLE="Static Analysis", FILE_NAME=app_dict["file_name"], SIZE=app_dict["size"], MD5=app_dict["md5_hash"], SHA1=app_dict["sha1"], SHA256=app_dict["sha256"], INFOPLIST=info_dict["plist_xml"], BINNAME=info_dict["bin_name"], IDF=info_dict["id"], BUILD=info_dict["build"], VERSION=info_dict["bundle_version_name"], SDK=info_dict["sdk"], PLTFM=info_dict["pltfm"], MINX=info_dict["min"], BIN_ANAL=bin_dict["bin_res"], LIBS=bin_dict["libs"], FILES=files, SFILESX=sfiles, STRINGS=bin_dict["strings"], PERMISSIONS=info_dict["permissions"], INSECCON=info_dict["inseccon"], BUNDLE_NAME=info_dict["bundle_name"], BUNDLE_URL_TYPES=info_dict["bundle_url_types"], BUNDLE_SUPPORTED_PLATFORMS=info_dict["bundle_supported_platforms"], BUNDLE_LOCALIZATIONS=info_dict["bundle_localizations"], ) static_db.save() except: PrintException("[ERROR] Saving to DB")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def get_context_from_analysis_ios(app_dict, info_dict, code_dict, files, sfiles): """Get the context for IOS ZIP from analysis results""" try: context = { "title": "Static Analysis", "file_name": app_dict["file_name"], "size": app_dict["size"], "md5": app_dict["md5_hash"], "sha1": app_dict["sha1"], "sha256": app_dict["sha256"], "plist": info_dict["plist_xml"], "bin_name": info_dict["bin_name"], "id": info_dict["id"], "build": info_dict["bundle_version_name"], "version": info_dict["bundle_version_name"], "sdk": info_dict["sdk"], "pltfm": info_dict["pltfm"], "min": info_dict["min"], "files": files, "file_analysis": sfiles, "api": code_dict["api"], "insecure": code_dict["code_anal"], "urls": code_dict["urlnfile"], "domains": code_dict["domains"], "emails": code_dict["emailnfile"], "permissions": info_dict["permissions"], "insecure_connections": info_dict["inseccon"], "bundle_name": info_dict["bundle_name"], "bundle_url_types": info_dict["bundle_url_types"], "bundle_supported_platforms": info_dict["bundle_supported_platforms"], "bundle_localizations": info_dict["bundle_localizations"], } return context except: PrintException("Rendering to Template")
def get_context_from_analysis_ios(app_dict, info_dict, code_dict, files, sfiles): """Get the context for IOS ZIP from analysis results""" try: context = { "title": "Static Analysis", "file_name": app_dict["file_name"], "size": app_dict["size"], "md5": app_dict["md5_hash"], "sha1": app_dict["sha1"], "sha256": app_dict["sha256"], "plist": info_dict["plist_xml"], "bin_name": info_dict["bin_name"], "id": info_dict["id"], "build": info_dict["bundle_version_name"], "version": info_dict["bundle_version_name"], "sdk": info_dict["sdk"], "pltfm": info_dict["pltfm"], "min": info_dict["min"], "files": files, "file_analysis": sfiles, "api": code_dict["api"], "insecure": code_dict["code_anal"], "urls": code_dict["urlnfile"], "domains": code_dict["domains"], "emails": code_dict["emailnfile"], "permissions": info_dict["permissions"], "insecure_connections": info_dict["inseccon"], "bundle_name": info_dict["bundle_name"], "bundle_url_types": info_dict["bundle_url_types"], "bundle_supported_platforms": info_dict["bundle_supported_platforms"], "bundle_localizations": info_dict["bundle_localizations"], } return context except: PrintException("[ERROR] Rendering to Template")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def get_context_from_db_entry_ios(db_entry): """Return the context for IOS ZIP from DB""" try: logger.info("Analysis is already Done. Fetching data from the DB...") context = { "title": db_entry[0].TITLE, "file_name": db_entry[0].FILE_NAME, "size": db_entry[0].SIZE, "md5": db_entry[0].MD5, "sha1": db_entry[0].SHA1, "sha256": db_entry[0].SHA256, "plist": db_entry[0].INFOPLIST, "bin_name": db_entry[0].BINNAME, "id": db_entry[0].IDF, "build": db_entry[0].BUILD, "version": db_entry[0].VERSION, "sdk": db_entry[0].SDK, "pltfm": db_entry[0].PLTFM, "min": db_entry[0].MINX, "files": python_list(db_entry[0].FILES), "file_analysis": python_list(db_entry[0].SFILESX), "api": python_dict(db_entry[0].API), "insecure": python_dict(db_entry[0].CODEANAL), "urls": python_list(db_entry[0].URLnFile), "domains": python_dict(db_entry[0].DOMAINS), "emails": python_list(db_entry[0].EmailnFile), "permissions": python_list(db_entry[0].PERMISSIONS), "insecure_connections": python_list(db_entry[0].INSECCON), "bundle_name": db_entry[0].BUNDLE_NAME, "bundle_url_types": python_list(db_entry[0].BUNDLE_URL_TYPES), "bundle_supported_platforms": python_list( db_entry[0].BUNDLE_SUPPORTED_PLATFORMS ), "bundle_localizations": python_list(db_entry[0].BUNDLE_LOCALIZATIONS), } return context except: PrintException("Fetching from DB")
def get_context_from_db_entry_ios(db_entry): """Return the context for IOS ZIP from DB""" try: logger.info("Analysis is already Done. Fetching data from the DB...") context = { "title": db_entry[0].TITLE, "file_name": db_entry[0].FILE_NAME, "size": db_entry[0].SIZE, "md5": db_entry[0].MD5, "sha1": db_entry[0].SHA1, "sha256": db_entry[0].SHA256, "plist": db_entry[0].INFOPLIST, "bin_name": db_entry[0].BINNAME, "id": db_entry[0].IDF, "build": db_entry[0].BUILD, "version": db_entry[0].VERSION, "sdk": db_entry[0].SDK, "pltfm": db_entry[0].PLTFM, "min": db_entry[0].MINX, "files": python_list(db_entry[0].FILES), "file_analysis": python_list(db_entry[0].SFILESX), "api": python_dict(db_entry[0].API), "insecure": python_dict(db_entry[0].CODEANAL), "urls": python_list(db_entry[0].URLnFile), "domains": python_dict(db_entry[0].DOMAINS), "emails": python_list(db_entry[0].EmailnFile), "permissions": python_list(db_entry[0].PERMISSIONS), "insecure_connections": python_list(db_entry[0].INSECCON), "bundle_name": db_entry[0].BUNDLE_NAME, "bundle_url_types": python_list(db_entry[0].BUNDLE_URL_TYPES), "bundle_supported_platforms": python_list( db_entry[0].BUNDLE_SUPPORTED_PLATFORMS ), "bundle_localizations": python_list(db_entry[0].BUNDLE_LOCALIZATIONS), } return context except: PrintException("[ERROR] Fetching from DB")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def update_db_entry_ios(app_dict, info_dict, code_dict, files, sfiles): """Update an IOS ZIP DB entry""" try: # pylint: disable=E1101 StaticAnalyzerIOSZIP.objects.filter(MD5=app_dict["md5_hash"]).update( TITLE="Static Analysis", FILE_NAME=app_dict["file_name"], SIZE=app_dict["size"], MD5=app_dict["md5_hash"], SHA1=app_dict["sha1"], SHA256=app_dict["sha256"], INFOPLIST=info_dict["plist_xml"], BINNAME=info_dict["bin_name"], IDF=info_dict["id"], BUILD=info_dict["build"], VERSION=info_dict["bundle_version_name"], SDK=info_dict["sdk"], PLTFM=info_dict["pltfm"], MINX=info_dict["min"], FILES=files, SFILESX=sfiles, API=code_dict["api"], CODEANAL=code_dict["code_anal"], URLnFile=code_dict["urlnfile"], DOMAINS=code_dict["domains"], EmailnFile=code_dict["emailnfile"], PERMISSIONS=info_dict["permissions"], INSECCON=info_dict["inseccon"], BUNDLE_NAME=info_dict["bundle_name"], BUNDLE_URL_TYPES=info_dict["bundle_url_types"], BUNDLE_SUPPORTED_PLATFORMS=info_dict["bundle_supported_platforms"], BUNDLE_LOCALIZATIONS=info_dict["bundle_localizations"], ) except: PrintException("Updating DB")
def update_db_entry_ios(app_dict, info_dict, code_dict, files, sfiles): """Update an IOS ZIP DB entry""" try: # pylint: disable=E1101 StaticAnalyzerIOSZIP.objects.filter(MD5=app_dict["md5_hash"]).update( TITLE="Static Analysis", FILE_NAME=app_dict["file_name"], SIZE=app_dict["size"], MD5=app_dict["md5_hash"], SHA1=app_dict["sha1"], SHA256=app_dict["sha256"], INFOPLIST=info_dict["plist_xml"], BINNAME=info_dict["bin_name"], IDF=info_dict["id"], BUILD=info_dict["build"], VERSION=info_dict["bundle_version_name"], SDK=info_dict["sdk"], PLTFM=info_dict["pltfm"], MINX=info_dict["min"], FILES=files, SFILESX=sfiles, API=code_dict["api"], CODEANAL=code_dict["code_anal"], URLnFile=code_dict["urlnfile"], DOMAINS=code_dict["domains"], EmailnFile=code_dict["emailnfile"], PERMISSIONS=info_dict["permissions"], INSECCON=info_dict["inseccon"], BUNDLE_NAME=info_dict["bundle_name"], BUNDLE_URL_TYPES=info_dict["bundle_url_types"], BUNDLE_SUPPORTED_PLATFORMS=info_dict["bundle_supported_platforms"], BUNDLE_LOCALIZATIONS=info_dict["bundle_localizations"], ) except: PrintException("[ERROR] Updating DB")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def create_db_entry_ios(app_dict, info_dict, code_dict, files, sfiles): """Save an IOS ZIP DB entry""" try: # pylint: disable=E1101 static_db = StaticAnalyzerIOSZIP( TITLE="Static Analysis", FILE_NAME=app_dict["file_name"], SIZE=app_dict["size"], MD5=app_dict["md5_hash"], SHA1=app_dict["sha1"], SHA256=app_dict["sha256"], INFOPLIST=info_dict["plist_xml"], BINNAME=info_dict["bin_name"], IDF=info_dict["id"], BUILD=info_dict["build"], VERSION=info_dict["bundle_version_name"], SDK=info_dict["sdk"], PLTFM=info_dict["pltfm"], MINX=info_dict["min"], FILES=files, SFILESX=sfiles, API=code_dict["api"], CODEANAL=code_dict["code_anal"], URLnFile=code_dict["urlnfile"], DOMAINS=code_dict["domains"], EmailnFile=code_dict["emailnfile"], PERMISSIONS=info_dict["permissions"], INSECCON=info_dict["inseccon"], BUNDLE_NAME=info_dict["bundle_name"], BUNDLE_URL_TYPES=info_dict["bundle_url_types"], BUNDLE_SUPPORTED_PLATFORMS=info_dict["bundle_supported_platforms"], BUNDLE_LOCALIZATIONS=info_dict["bundle_localizations"], ) static_db.save() except: PrintException("Updating DB")
def create_db_entry_ios(app_dict, info_dict, code_dict, files, sfiles): """Save an IOS ZIP DB entry""" try: # pylint: disable=E1101 static_db = StaticAnalyzerIOSZIP( TITLE="Static Analysis", FILE_NAME=app_dict["file_name"], SIZE=app_dict["size"], MD5=app_dict["md5_hash"], SHA1=app_dict["sha1"], SHA256=app_dict["sha256"], INFOPLIST=info_dict["plist_xml"], BINNAME=info_dict["bin_name"], IDF=info_dict["id"], BUILD=info_dict["build"], VERSION=info_dict["bundle_version_name"], SDK=info_dict["sdk"], PLTFM=info_dict["pltfm"], MINX=info_dict["min"], FILES=files, SFILESX=sfiles, API=code_dict["api"], CODEANAL=code_dict["code_anal"], URLnFile=code_dict["urlnfile"], DOMAINS=code_dict["domains"], EmailnFile=code_dict["emailnfile"], PERMISSIONS=info_dict["permissions"], INSECCON=info_dict["inseccon"], BUNDLE_NAME=info_dict["bundle_name"], BUNDLE_URL_TYPES=info_dict["bundle_url_types"], BUNDLE_SUPPORTED_PLATFORMS=info_dict["bundle_supported_platforms"], BUNDLE_LOCALIZATIONS=info_dict["bundle_localizations"], ) static_db.save() except: PrintException("[ERROR] Updating DB")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def plist_analysis(src, is_source): """Plist Analysis""" try: logger.info("iOS Info.plist Analysis Started") plist_info = { "bin_name": "", "bin": "", "id": "", "version": "", "build": "", "sdk": "", "pltfm": "", "min": "", "plist_xml": "", "permissions": [], "inseccon": [], "bundle_name": "", "build_version_name": "", "bundle_url_types": [], "bundle_supported_platforms": [], "bundle_localizations": [], } plist_file = None if is_source: logger.info("Finding Info.plist in iOS Source") for ifile in os.listdir(src): if ifile.endswith(".xcodeproj"): app_name = ifile.replace(".xcodeproj", "") break app_plist_file = "Info.plist" for dirpath, dirnames, files in os.walk(src): for name in files: if "__MACOSX" not in dirpath and name == app_plist_file: plist_file = os.path.join(dirpath, name) break else: logger.info("Finding Info.plist in iOS Binary") dirs = os.listdir(src) dot_app_dir = "" for dir_ in dirs: if dir_.endswith(".app"): dot_app_dir = dir_ break bin_dir = os.path.join(src, dot_app_dir) # Full Dir/Payload/x.app plist_file = os.path.join(bin_dir, "Info.plist") if not isFileExists(plist_file): logger.warning("Cannot find Info.plist file. Skipping Plist Analysis.") else: # Generic Plist Analysis plist_obj = plistlib.readPlist(plist_file) plist_info["plist_xml"] = plistlib.writePlistToBytes(plist_obj).decode( "utf-8", "ignore" ) if "CFBundleDisplayName" in plist_obj: plist_info["bin_name"] = plist_obj["CFBundleDisplayName"] else: if not is_source: # For iOS IPA plist_info["bin_name"] = dot_app_dir.replace(".app", "") if "CFBundleExecutable" in plist_obj: plist_info["bin"] = plist_obj["CFBundleExecutable"] if "CFBundleIdentifier" in plist_obj: plist_info["id"] = plist_obj["CFBundleIdentifier"] # build if "CFBundleVersion" in plist_obj: plist_info["build"] = plist_obj["CFBundleVersion"] if "DTSDKName" in plist_obj: plist_info["sdk"] = plist_obj["DTSDKName"] if "DTPlatformVersion" in plist_obj: plist_info["pltfm"] = plist_obj["DTPlatformVersion"] if "MinimumOSVersion" in plist_obj: plist_info["min"] = plist_obj["MinimumOSVersion"] plist_info["bundle_name"] = plist_obj.get("CFBundleName", "") plist_info["bundle_version_name"] = plist_obj.get( "CFBundleShortVersionString", "" ) plist_info["bundle_url_types"] = plist_obj.get("CFBundleURLTypes", []) plist_info["bundle_supported_platforms"] = plist_obj.get( "CFBundleSupportedPlatforms", [] ) plist_info["bundle_localizations"] = plist_obj.get( "CFBundleLocalizations", [] ) # Check possible app-permissions plist_info["permissions"] = __check_permissions(plist_obj) plist_info["inseccon"] = __check_insecure_connections(plist_obj) return plist_info except: PrintException("Reading from Info.plist")
def plist_analysis(src, is_source): """Plist Analysis""" try: logger.info("iOS Info.plist Analysis Started") plist_info = { "bin_name": "", "bin": "", "id": "", "version": "", "build": "", "sdk": "", "pltfm": "", "min": "", "plist_xml": "", "permissions": [], "inseccon": [], "bundle_name": "", "build_version_name": "", "bundle_url_types": [], "bundle_supported_platforms": [], "bundle_localizations": [], } plist_file = None if is_source: logger.info("Finding Info.plist in iOS Source") for ifile in os.listdir(src): if ifile.endswith(".xcodeproj"): app_name = ifile.replace(".xcodeproj", "") break app_plist_file = "Info.plist" for dirpath, dirnames, files in os.walk(src): for name in files: if "__MACOSX" not in dirpath and name == app_plist_file: plist_file = os.path.join(dirpath, name) break else: logger.info("Finding Info.plist in iOS Binary") dirs = os.listdir(src) dot_app_dir = "" for dir_ in dirs: if dir_.endswith(".app"): dot_app_dir = dir_ break bin_dir = os.path.join(src, dot_app_dir) # Full Dir/Payload/x.app plist_file = os.path.join(bin_dir, "Info.plist") if not isFileExists(plist_file): logger.warning("Cannot find Info.plist file. Skipping Plist Analysis.") else: # Generic Plist Analysis plist_obj = plistlib.readPlist(plist_file) plist_info["plist_xml"] = plistlib.writePlistToBytes(plist_obj).decode( "utf-8", "ignore" ) if "CFBundleDisplayName" in plist_obj: plist_info["bin_name"] = plist_obj["CFBundleDisplayName"] else: if not is_source: # For iOS IPA plist_info["bin_name"] = dot_app_dir.replace(".app", "") if "CFBundleExecutable" in plist_obj: plist_info["bin"] = plist_obj["CFBundleExecutable"] if "CFBundleIdentifier" in plist_obj: plist_info["id"] = plist_obj["CFBundleIdentifier"] # build if "CFBundleVersion" in plist_obj: plist_info["build"] = plist_obj["CFBundleVersion"] if "DTSDKName" in plist_obj: plist_info["sdk"] = plist_obj["DTSDKName"] if "DTPlatformVersion" in plist_obj: plist_info["pltfm"] = plist_obj["DTPlatformVersion"] if "MinimumOSVersion" in plist_obj: plist_info["min"] = plist_obj["MinimumOSVersion"] plist_info["bundle_name"] = plist_obj.get("CFBundleName", "") plist_info["bundle_version_name"] = plist_obj.get( "CFBundleShortVersionString", "" ) plist_info["bundle_url_types"] = plist_obj.get("CFBundleURLTypes", []) plist_info["bundle_supported_platforms"] = plist_obj.get( "CFBundleSupportedPlatforms", [] ) plist_info["bundle_localizations"] = plist_obj.get( "CFBundleLocalizations", [] ) # Check possible app-permissions plist_info["permissions"] = __check_permissions(plist_obj) plist_info["inseccon"] = __check_insecure_connections(plist_obj) return plist_info except: PrintException("[ERROR] - Reading from Info.plist")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def ios_list_files(src, md5_hash, binary_form, mode): """List iOS files""" try: logger.info("Get Files, BIN Plist -> XML, and Normalize") # Multi function, Get Files, BIN Plist -> XML, normalize + to x filez = [] certz = [] sfiles = [] database = [] plist = [] for dirname, _, files in os.walk(src): for jfile in files: if not jfile.endswith(".DS_Store"): file_path = os.path.join(src, dirname, jfile) if "+" in jfile: plus2x = os.path.join(src, dirname, jfile.replace("+", "x")) shutil.move(file_path, plus2x) file_path = plus2x fileparam = file_path.replace(src, "") filez.append(fileparam) ext = jfile.split(".")[-1] if re.search("cer|pem|cert|crt|pub|key|pfx|p12", ext): certz.append( { "file_path": escape(file_path.replace(src, "")), "type": None, "hash": None, } ) if re.search("db|sqlitedb|sqlite", ext): database.append( { "file_path": escape(fileparam), "type": mode, "hash": md5_hash, } ) if jfile.endswith(".plist"): if binary_form: convert_bin_xml(file_path) plist.append( { "file_path": escape(fileparam), "type": mode, "hash": md5_hash, } ) if len(database) > 0: sfiles.append({"issue": "SQLite Files", "files": database}) if len(plist) > 0: sfiles.append({"issue": "Plist Files", "files": plist}) if len(certz) > 0: sfiles.append( { "issue": "Certificate/Key Files Hardcoded inside the App.", "files": certz, } ) return filez, sfiles except: PrintException("iOS List Files")
def ios_list_files(src, md5_hash, binary_form, mode): """List iOS files""" try: logger.info("Get Files, BIN Plist -> XML, and Normalize") # Multi function, Get Files, BIN Plist -> XML, normalize + to x filez = [] certz = [] sfiles = [] database = [] plist = [] for dirname, _, files in os.walk(src): for jfile in files: if not jfile.endswith(".DS_Store"): file_path = os.path.join(src, dirname, jfile) if "+" in jfile: plus2x = os.path.join(src, dirname, jfile.replace("+", "x")) shutil.move(file_path, plus2x) file_path = plus2x fileparam = file_path.replace(src, "") filez.append(fileparam) ext = jfile.split(".")[-1] if re.search("cer|pem|cert|crt|pub|key|pfx|p12", ext): certz.append( { "file_path": escape(file_path.replace(src, "")), "type": None, "hash": None, } ) if re.search("db|sqlitedb|sqlite", ext): database.append( { "file_path": escape(fileparam), "type": mode, "hash": md5_hash, } ) if jfile.endswith(".plist"): if binary_form: convert_bin_xml(file_path) plist.append( { "file_path": escape(fileparam), "type": mode, "hash": md5_hash, } ) if len(database) > 0: sfiles.append({"issue": "SQLite Files", "files": database}) if len(plist) > 0: sfiles.append({"issue": "Plist Files", "files": plist}) if len(certz) > 0: sfiles.append( { "issue": "Certificate/Key Files Hardcoded inside the App.", "files": certz, } ) return filez, sfiles except: PrintException("[ERROR] iOS List Files")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def read_sqlite(sqlite_file): """Read SQlite File""" try: logger.info("Dumping SQLITE Database") data = "" con = sqlite3.connect(sqlite_file) cur = con.cursor() cur.execute("SELECT name FROM sqlite_master WHERE type='table';") tables = cur.fetchall() for table in tables: data += ( "\nTABLE: " + str(table[0]).decode("utf8", "ignore") + " \n=====================================================\n" ) cur.execute("PRAGMA table_info('%s')" % table) rows = cur.fetchall() head = "" for row in rows: head += str(row[1]).decode("utf8", "ignore") + " | " data += ( head + " \n========================================" + "=============================\n" ) cur.execute("SELECT * FROM '%s'" % table) rows = cur.fetchall() for row in rows: dat = "" for item in row: dat += str(item).decode("utf8", "ignore") + " | " data += dat + "\n" return data except: PrintException("Dumping SQLITE Database")
def read_sqlite(sqlite_file): """Read SQlite File""" try: logger.info("Dumping SQLITE Database") data = "" con = sqlite3.connect(sqlite_file) cur = con.cursor() cur.execute("SELECT name FROM sqlite_master WHERE type='table';") tables = cur.fetchall() for table in tables: data += ( "\nTABLE: " + str(table[0]).decode("utf8", "ignore") + " \n=====================================================\n" ) cur.execute("PRAGMA table_info('%s')" % table) rows = cur.fetchall() head = "" for row in rows: head += str(row[1]).decode("utf8", "ignore") + " | " data += ( head + " \n========================================" + "=============================\n" ) cur.execute("SELECT * FROM '%s'" % table) rows = cur.fetchall() for row in rows: dat = "" for item in row: dat += str(item).decode("utf8", "ignore") + " | " data += dat + "\n" return data except: PrintException("[ERROR] Dumping SQLITE Database")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def hash_gen(app_path) -> tuple: """Generate and return sha1 and sha256 as a tupel.""" try: logger.info("Generating Hashes") sha1 = hashlib.sha1() sha256 = hashlib.sha256() block_size = 65536 with io.open(app_path, mode="rb") as afile: buf = afile.read(block_size) while buf: sha1.update(buf) sha256.update(buf) buf = afile.read(block_size) sha1val = sha1.hexdigest() sha256val = sha256.hexdigest() return sha1val, sha256val except: PrintException("Generating Hashes")
def hash_gen(app_path) -> tuple: """Generate and return sha1 and sha256 as a tupel.""" try: logger.info("Generating Hashes") sha1 = hashlib.sha1() sha256 = hashlib.sha256() block_size = 65536 with io.open(app_path, mode="rb") as afile: buf = afile.read(block_size) while buf: sha1.update(buf) sha256.update(buf) buf = afile.read(block_size) sha1val = sha1.hexdigest() sha256val = sha256.hexdigest() return sha1val, sha256val except: PrintException("[ERROR] Generating Hashes")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def unzip(app_path, ext_path): logger.info("Unzipping") try: files = [] with zipfile.ZipFile(app_path, "r") as zipptr: for fileinfo in zipptr.infolist(): filename = fileinfo.filename if not isinstance(filename, str): filename = str(filename, encoding="utf-8", errors="replace") files.append(filename) zipptr.extract(filename, ext_path) return files except: PrintException("Unzipping Error") if platform.system() == "Windows": logger.info("Not yet Implemented.") else: logger.info("Using the Default OS Unzip Utility.") try: subprocess.call( ["unzip", "-o", "-I utf-8", "-q", app_path, "-d", ext_path] ) dat = subprocess.check_output(["unzip", "-qq", "-l", app_path]) dat = dat.decode("utf-8").split("\n") files_det = ["Length Date Time Name"] files_det = files_det + dat return files_det except: PrintException("Unzipping Error")
def unzip(app_path, ext_path): logger.info("Unzipping") try: files = [] with zipfile.ZipFile(app_path, "r") as zipptr: for fileinfo in zipptr.infolist(): filename = fileinfo.filename if not isinstance(filename, str): filename = str(filename, encoding="utf-8", errors="replace") files.append(filename) zipptr.extract(filename, ext_path) return files except: PrintException("[ERROR] Unzipping Error") if platform.system() == "Windows": logger.info("Not yet Implemented.") else: logger.info("Using the Default OS Unzip Utility.") try: subprocess.call( ["unzip", "-o", "-I utf-8", "-q", app_path, "-d", ext_path] ) dat = subprocess.check_output(["unzip", "-qq", "-l", app_path]) dat = dat.decode("utf-8").split("\n") files_det = ["Length Date Time Name"] files_det = files_det + dat return files_det except: PrintException("[ERROR] Unzipping Error")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def code_rule_matcher(findings, perms, data, file_path, code_rules): """Android Static Analysis Rule Matcher""" try: for rule in code_rules: # CASE CHECK if rule["input_case"] == "lower": tmp_data = data.lower() elif rule["input_case"] == "upper": tmp_data = data.upper() elif rule["input_case"] == "exact": tmp_data = data # MATCH TYPE if rule["type"] == "regex": if rule["match"] == "single_regex": if re.findall(rule["regex1"], tmp_data): add_findings(findings, rule["desc"], file_path, rule) elif rule["match"] == "regex_and": and_match_rgx = True match_list = get_list_match_items(rule) for match in match_list: if bool(re.findall(match, tmp_data)) is False: and_match_rgx = False break if and_match_rgx: add_findings(findings, rule["desc"], file_path, rule) elif rule["match"] == "regex_or": match_list = get_list_match_items(rule) for match in match_list: if re.findall(match, tmp_data): add_findings(findings, rule["desc"], file_path, rule) break elif rule["match"] == "regex_and_perm": if (rule["perm"] in perms) and ( re.findall(rule["regex1"], tmp_data) ): add_findings(findings, rule["desc"], file_path, rule) else: logger.error("Code Regex Rule Match Error\n" + rule) elif rule["type"] == "string": if rule["match"] == "single_string": if rule["string1"] in tmp_data: add_findings(findings, rule["desc"], file_path, rule) elif rule["match"] == "string_and": and_match_str = True match_list = get_list_match_items(rule) for match in match_list: if (match in tmp_data) is False: and_match_str = False break if and_match_str: add_findings(findings, rule["desc"], file_path, rule) elif rule["match"] == "string_or": match_list = get_list_match_items(rule) for match in match_list: if match in tmp_data: add_findings(findings, rule["desc"], file_path, rule) break elif rule["match"] == "string_and_or": match_list = get_list_match_items(rule) string_or_stat = False for match in match_list: if match in tmp_data: string_or_stat = True break if string_or_stat and (rule["string1"] in tmp_data): add_findings(findings, rule["desc"], file_path, rule) elif rule["match"] == "string_or_and": match_list = get_list_match_items(rule) string_and_stat = True for match in match_list: if match in tmp_data is False: string_and_stat = False break if string_and_stat or (rule["string1"] in tmp_data): add_findings(findings, rule["desc"], file_path, rule) elif rule["match"] == "string_and_perm": if (rule["perm"] in perms) and (rule["string1"] in tmp_data): add_findings(findings, rule["desc"], file_path, rule) elif rule["match"] == "string_or_and_perm": match_list = get_list_match_items(rule) string_or_ps = False for match in match_list: if match in tmp_data: string_or_ps = True break if (rule["perm"] in perms) and string_or_ps: add_findings(findings, rule["desc"], file_path, rule) else: logger.error("Code String Rule Match Error\n%s", rule) else: logger.error("Code Rule Error\n%s", rule) except: PrintException("Error in Code Rule Processing")
def code_rule_matcher(findings, perms, data, file_path, code_rules): """Android Static Analysis Rule Matcher""" try: for rule in code_rules: # CASE CHECK if rule["input_case"] == "lower": tmp_data = data.lower() elif rule["input_case"] == "upper": tmp_data = data.upper() elif rule["input_case"] == "exact": tmp_data = data # MATCH TYPE if rule["type"] == "regex": if rule["match"] == "single_regex": if re.findall(rule["regex1"], tmp_data): add_findings(findings, rule["desc"], file_path, rule) elif rule["match"] == "regex_and": and_match_rgx = True match_list = get_list_match_items(rule) for match in match_list: if bool(re.findall(match, tmp_data)) is False: and_match_rgx = False break if and_match_rgx: add_findings(findings, rule["desc"], file_path, rule) elif rule["match"] == "regex_or": match_list = get_list_match_items(rule) for match in match_list: if re.findall(match, tmp_data): add_findings(findings, rule["desc"], file_path, rule) break elif rule["match"] == "regex_and_perm": if (rule["perm"] in perms) and ( re.findall(rule["regex1"], tmp_data) ): add_findings(findings, rule["desc"], file_path, rule) else: logger.error("Code Regex Rule Match Error\n" + rule) elif rule["type"] == "string": if rule["match"] == "single_string": if rule["string1"] in tmp_data: add_findings(findings, rule["desc"], file_path, rule) elif rule["match"] == "string_and": and_match_str = True match_list = get_list_match_items(rule) for match in match_list: if (match in tmp_data) is False: and_match_str = False break if and_match_str: add_findings(findings, rule["desc"], file_path, rule) elif rule["match"] == "string_or": match_list = get_list_match_items(rule) for match in match_list: if match in tmp_data: add_findings(findings, rule["desc"], file_path, rule) break elif rule["match"] == "string_and_or": match_list = get_list_match_items(rule) string_or_stat = False for match in match_list: if match in tmp_data: string_or_stat = True break if string_or_stat and (rule["string1"] in tmp_data): add_findings(findings, rule["desc"], file_path, rule) elif rule["match"] == "string_or_and": match_list = get_list_match_items(rule) string_and_stat = True for match in match_list: if match in tmp_data is False: string_and_stat = False break if string_and_stat or (rule["string1"] in tmp_data): add_findings(findings, rule["desc"], file_path, rule) elif rule["match"] == "string_and_perm": if (rule["perm"] in perms) and (rule["string1"] in tmp_data): add_findings(findings, rule["desc"], file_path, rule) elif rule["match"] == "string_or_and_perm": match_list = get_list_match_items(rule) string_or_ps = False for match in match_list: if match in tmp_data: string_or_ps = True break if (rule["perm"] in perms) and string_or_ps: add_findings(findings, rule["desc"], file_path, rule) else: logger.error("Code String Rule Match Error\n%s", rule) else: logger.error("Code Rule Error\n%s", rule) except: PrintException("[ERROR] Error in Code Rule Processing")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def api_rule_matcher(api_findings, perms, data, file_path, api_rules): """Android API Analysis Rule Matcher""" try: for api in api_rules: # CASE CHECK if api["input_case"] == "lower": tmp_data = data.lower() elif api["input_case"] == "upper": tmp_data = data.upper() elif api["input_case"] == "exact": tmp_data = data # MATCH TYPE if api["type"] == "regex": if api["match"] == "single_regex": if re.findall(api["regex1"], tmp_data): add_apis(api_findings, api["desc"], file_path) elif api["match"] == "regex_and": and_match_rgx = True match_list = get_list_match_items(api) for match in match_list: if bool(re.findall(match, tmp_data)) is False: and_match_rgx = False break if and_match_rgx: add_apis(api_findings, api["desc"], file_path) elif api["match"] == "regex_or": match_list = get_list_match_items(api) for match in match_list: if re.findall(match, tmp_data): add_apis(api_findings, api["desc"], file_path) break elif api["match"] == "regex_and_perm": if (api["perm"] in perms) and (re.findall(api["regex1"], tmp_data)): add_apis(api_findings, api["desc"], file_path) else: logger.error("API Regex Rule Match Error\n" + api) elif api["type"] == "string": if api["match"] == "single_string": if api["string1"] in tmp_data: add_apis(api_findings, api["desc"], file_path) elif api["match"] == "string_and": and_match_str = True match_list = get_list_match_items(api) for match in match_list: if (match in tmp_data) is False: and_match_str = False break if and_match_str: add_apis(api_findings, api["desc"], file_path) elif api["match"] == "string_or": match_list = get_list_match_items(api) for match in match_list: if match in tmp_data: add_apis(api_findings, api["desc"], file_path) break elif api["match"] == "string_and_or": match_list = get_list_match_items(api) string_or_stat = False for match in match_list: if match in tmp_data: string_or_stat = True break if string_or_stat and (api["string1"] in tmp_data): add_apis(api_findings, api["desc"], file_path) elif api["match"] == "string_or_and": match_list = get_list_match_items(api) string_and_stat = True for match in match_list: if match in tmp_data is False: string_and_stat = False break if string_and_stat or (api["string1"] in tmp_data): add_apis(api_findings, api["desc"], file_path) elif api["match"] == "string_and_perm": if (api["perm"] in perms) and (api["string1"] in tmp_data): add_apis(api_findings, api["desc"], file_path) elif api["match"] == "string_or_and_perm": match_list = get_list_match_items(api) string_or_ps = False for match in match_list: if match in tmp_data: string_or_ps = True break if (api["perm"] in perms) and string_or_ps: add_apis(api_findings, api["desc"], file_path) else: logger.error("API String Rule Match Error\n%s", api) else: logger.error("API Rule Error\n%s", api) except: PrintException("Error in API Rule Processing")
def api_rule_matcher(api_findings, perms, data, file_path, api_rules): """Android API Analysis Rule Matcher""" try: for api in api_rules: # CASE CHECK if api["input_case"] == "lower": tmp_data = data.lower() elif api["input_case"] == "upper": tmp_data = data.upper() elif api["input_case"] == "exact": tmp_data = data # MATCH TYPE if api["type"] == "regex": if api["match"] == "single_regex": if re.findall(api["regex1"], tmp_data): add_apis(api_findings, api["desc"], file_path) elif api["match"] == "regex_and": and_match_rgx = True match_list = get_list_match_items(api) for match in match_list: if bool(re.findall(match, tmp_data)) is False: and_match_rgx = False break if and_match_rgx: add_apis(api_findings, api["desc"], file_path) elif api["match"] == "regex_or": match_list = get_list_match_items(api) for match in match_list: if re.findall(match, tmp_data): add_apis(api_findings, api["desc"], file_path) break elif api["match"] == "regex_and_perm": if (api["perm"] in perms) and (re.findall(api["regex1"], tmp_data)): add_apis(api_findings, api["desc"], file_path) else: logger.error("API Regex Rule Match Error\n" + api) elif api["type"] == "string": if api["match"] == "single_string": if api["string1"] in tmp_data: add_apis(api_findings, api["desc"], file_path) elif api["match"] == "string_and": and_match_str = True match_list = get_list_match_items(api) for match in match_list: if (match in tmp_data) is False: and_match_str = False break if and_match_str: add_apis(api_findings, api["desc"], file_path) elif api["match"] == "string_or": match_list = get_list_match_items(api) for match in match_list: if match in tmp_data: add_apis(api_findings, api["desc"], file_path) break elif api["match"] == "string_and_or": match_list = get_list_match_items(api) string_or_stat = False for match in match_list: if match in tmp_data: string_or_stat = True break if string_or_stat and (api["string1"] in tmp_data): add_apis(api_findings, api["desc"], file_path) elif api["match"] == "string_or_and": match_list = get_list_match_items(api) string_and_stat = True for match in match_list: if match in tmp_data is False: string_and_stat = False break if string_and_stat or (api["string1"] in tmp_data): add_apis(api_findings, api["desc"], file_path) elif api["match"] == "string_and_perm": if (api["perm"] in perms) and (api["string1"] in tmp_data): add_apis(api_findings, api["desc"], file_path) elif api["match"] == "string_or_and_perm": match_list = get_list_match_items(api) string_or_ps = False for match in match_list: if match in tmp_data: string_or_ps = True break if (api["perm"] in perms) and string_or_ps: add_apis(api_findings, api["desc"], file_path) else: logger.error("API String Rule Match Error\n%s", api) else: logger.error("API Rule Error\n%s", api) except: PrintException("[ERROR] Error in API Rule Processing")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def _binary_analysis(app_dic): """Start binary analsis.""" logger.info("Starting Binary Analysis") bin_an_dic = {} # Init optional sections to prevent None-Pointer-Errors bin_an_dic["results"] = [] bin_an_dic["warnings"] = [] # Search for exe for file_name in app_dic["files"]: if file_name.endswith(".exe"): bin_an_dic["bin"] = file_name bin_an_dic["bin_name"] = file_name.replace(".exe", "") break if not bin_an_dic["bin_name"]: PrintException("No executeable in appx.") bin_path = os.path.join(app_dic["app_dir"], bin_an_dic["bin"]) # Execute strings command bin_an_dic["strings"] = "" str_list = list( set(strings_util(bin_path)) ) # Make unique # pylint: disable-msg=R0204 str_list = [escape(s) for s in str_list] bin_an_dic["strings"] = str_list # Search for unsave function pattern = re.compile( "(alloca|gets|memcpy|printf|scanf|sprintf|sscanf|strcat|StrCat|strcpy|StrCpy|strlen|StrLen|strncat|StrNCat|strncpy|StrNCpy|strtok|swprintf|vsnprintf|vsprintf|vswprintf|wcscat|wcscpy|wcslen|wcsncat|wcsncpy|wcstok|wmemcpy)" ) for elem in str_list: if pattern.match(elem[5:-5]): result = { "rule_id": "Possible Insecure Function", "status": "Insecure", "desc": "Possible Insecure Function detected: {}".format(elem[5:-5]), } bin_an_dic["results"].append(result) # Execute binskim analysis if vm is available if platform.system() != "Windows": if settings.WINDOWS_VM_IP: logger.info("Windows VM configured.") global proxy proxy = xmlrpc.client.ServerProxy( # pylint: disable-msg=C0103 "http://{}:{}".format(settings.WINDOWS_VM_IP, settings.WINDOWS_VM_PORT) ) name = _upload_sample(bin_path) bin_an_dic = __binskim(name, bin_an_dic) bin_an_dic = __binscope(name, bin_an_dic) else: logger.warning( "Windows VM not configured in settings.py. Skipping Binskim and Binscope." ) warning = { "rule_id": "VM", "status": "Info", "info": "", "desc": "VM is not configured. Please read the readme.md in MobSF/install/windows.", } bin_an_dic["results"].append(warning) else: logger.info("Running lokal analysis.") global config config = configparser.ConfigParser() # Switch to settings definded path if available config.read(expanduser("~") + "\\MobSF\\Config\\config.txt") # Run analysis functions bin_an_dic = __binskim( bin_path, bin_an_dic, run_local=True, app_dir=app_dic["app_dir"] ) bin_an_dic = __binscope( bin_path, bin_an_dic, run_local=True, app_dir=app_dic["app_dir"] ) return bin_an_dic
def _binary_analysis(app_dic): """Start binary analsis.""" logger.info("Starting Binary Analysis") bin_an_dic = {} # Init optional sections to prevent None-Pointer-Errors bin_an_dic["results"] = [] bin_an_dic["warnings"] = [] # Search for exe for file_name in app_dic["files"]: if file_name.endswith(".exe"): bin_an_dic["bin"] = file_name bin_an_dic["bin_name"] = file_name.replace(".exe", "") break if not bin_an_dic["bin_name"]: PrintException("[ERROR] No executeable in appx.") bin_path = os.path.join(app_dic["app_dir"], bin_an_dic["bin"]) # Execute strings command bin_an_dic["strings"] = "" str_list = list( set(strings_util(bin_path)) ) # Make unique # pylint: disable-msg=R0204 str_list = [escape(s) for s in str_list] bin_an_dic["strings"] = str_list # Search for unsave function pattern = re.compile( "(alloca|gets|memcpy|printf|scanf|sprintf|sscanf|strcat|StrCat|strcpy|StrCpy|strlen|StrLen|strncat|StrNCat|strncpy|StrNCpy|strtok|swprintf|vsnprintf|vsprintf|vswprintf|wcscat|wcscpy|wcslen|wcsncat|wcsncpy|wcstok|wmemcpy)" ) for elem in str_list: if pattern.match(elem[5:-5]): result = { "rule_id": "Possible Insecure Function", "status": "Insecure", "desc": "Possible Insecure Function detected: {}".format(elem[5:-5]), } bin_an_dic["results"].append(result) # Execute binskim analysis if vm is available if platform.system() != "Windows": if settings.WINDOWS_VM_IP: logger.info("Windows VM configured.") global proxy proxy = xmlrpc.client.ServerProxy( # pylint: disable-msg=C0103 "http://{}:{}".format(settings.WINDOWS_VM_IP, settings.WINDOWS_VM_PORT) ) name = _upload_sample(bin_path) bin_an_dic = __binskim(name, bin_an_dic) bin_an_dic = __binscope(name, bin_an_dic) else: logger.warning( "Windows VM not configured in settings.py. Skipping Binskim and Binscope." ) warning = { "rule_id": "VM", "status": "Info", "info": "", "desc": "VM is not configured. Please read the readme.md in MobSF/install/windows.", } bin_an_dic["results"].append(warning) else: logger.info("Running lokal analysis.") global config config = configparser.ConfigParser() # Switch to settings definded path if available config.read(expanduser("~") + "\\MobSF\\Config\\config.txt") # Run analysis functions bin_an_dic = __binskim( bin_path, bin_an_dic, run_local=True, app_dir=app_dic["app_dir"] ) bin_an_dic = __binscope( bin_path, bin_an_dic, run_local=True, app_dir=app_dic["app_dir"] ) return bin_an_dic
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def _parse_xml(app_dir): """Parse the AppxManifest file to get basic informations.""" logger.info("Starting Binary Analysis - XML") xml_file = os.path.join(app_dir, "AppxManifest.xml") xml_dic = { "version": "", "arch": "", "app_name": "", "pub_name": "", "compiler_version": "", "visual_studio_version": "", "visual_studio_edition": "", "target_os": "", "appx_dll_version": "", "proj_guid": "", "opti_tool": "", "target_run": "", } try: logger.info("Reading AppxManifest") config = etree.XMLParser( # pylint: disable-msg=E1101 remove_blank_text=True, resolve_entities=False ) xml = etree.XML(open(xml_file, "rb").read(), config) # pylint: disable-msg=E1101 for child in xml.getchildren(): # } to prevent conflict with PhoneIdentity.. if isinstance(child.tag, str) and child.tag.endswith("}Identity"): xml_dic["version"] = child.get("Version") xml_dic["arch"] = child.get("ProcessorArchitecture") elif isinstance(child.tag, str) and child.tag.endswith("Properties"): for sub_child in child.getchildren(): if sub_child.tag.endswith("}DisplayName"): # TODO(Needed? Compare to existing app_name) xml_dic["app_name"] = sub_child.text elif sub_child.tag.endswith("}PublisherDisplayName"): xml_dic["pub_name"] = sub_child.text elif isinstance(child.tag, str) and child.tag.endswith("}Metadata"): xml_dic = __parse_xml_metadata(xml_dic, child) except: PrintException("Reading from AppxManifest.xml") return xml_dic
def _parse_xml(app_dir): """Parse the AppxManifest file to get basic informations.""" logger.info("Starting Binary Analysis - XML") xml_file = os.path.join(app_dir, "AppxManifest.xml") xml_dic = { "version": "", "arch": "", "app_name": "", "pub_name": "", "compiler_version": "", "visual_studio_version": "", "visual_studio_edition": "", "target_os": "", "appx_dll_version": "", "proj_guid": "", "opti_tool": "", "target_run": "", } try: logger.info("Reading AppxManifest") config = etree.XMLParser( # pylint: disable-msg=E1101 remove_blank_text=True, resolve_entities=False ) xml = etree.XML(open(xml_file, "rb").read(), config) # pylint: disable-msg=E1101 for child in xml.getchildren(): # } to prevent conflict with PhoneIdentity.. if isinstance(child.tag, str) and child.tag.endswith("}Identity"): xml_dic["version"] = child.get("Version") xml_dic["arch"] = child.get("ProcessorArchitecture") elif isinstance(child.tag, str) and child.tag.endswith("Properties"): for sub_child in child.getchildren(): if sub_child.tag.endswith("}DisplayName"): # TODO(Needed? Compare to existing app_name) xml_dic["app_name"] = sub_child.text elif sub_child.tag.endswith("}PublisherDisplayName"): xml_dic["pub_name"] = sub_child.text elif isinstance(child.tag, str) and child.tag.endswith("}Metadata"): xml_dic = __parse_xml_metadata(xml_dic, child) except: PrintException("[ERROR] - Reading from AppxManifest.xml") return xml_dic
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def check_config(): try: for path in [settings.AVD_EMULATOR, settings.ADB_BINARY]: if not path: logger.error( "ADB binary not configured, please refer to the official documentation" ) return False if settings.ANDROID_DYNAMIC_ANALYZER != "MobSF_AVD": logger.error( "Wrong configuration - ANDROID_DYNAMIC_ANALYZER, please refer to the official documentation" ) return False return True except: PrintException("check_config") return False
def check_config(): try: for path in [settings.AVD_EMULATOR, settings.ADB_BINARY]: if not path: logger.error( "ADB binary not configured, please refer to the official documentation" ) return False if settings.ANDROID_DYNAMIC_ANALYZER != "MobSF_AVD": logger.error( "Wrong configuration - ANDROID_DYNAMIC_ANALYZER, please refer to the official documentation" ) return False return True except: PrintException("[ERROR] check_config") return False
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def help_boot_avd(): try: emulator = get_identifier() # Wait for the adb to answer args = [settings.ADB_BINARY, "-s", emulator, "wait-for-device"] logger.info("help_boot_avd: wait-for-device") subprocess.call(args) # Make sure adb running as root logger.info("help_boot_avd: root") adb_command(["root"]) # Make sure adb running as root logger.info("help_boot_avd: remount") adb_command(["remount"]) # Make sure the system verity feature is disabled (Obviously, modified the system partition) logger.info("help_boot_avd: disable-verity") adb_command(["disable-verity"]) # Make SELinux permissive - in case SuperSu/Xposed didn't patch things right logger.info("help_boot_avd: setenforce") adb_command(["setenforce", "0"], shell=True) logger.info("help_boot_avd: finished!") return True except: PrintException("help_boot_avd") return False
def help_boot_avd(): try: emulator = get_identifier() # Wait for the adb to answer args = [settings.ADB_BINARY, "-s", emulator, "wait-for-device"] logger.info("help_boot_avd: wait-for-device") subprocess.call(args) # Make sure adb running as root logger.info("help_boot_avd: root") adb_command(["root"]) # Make sure adb running as root logger.info("help_boot_avd: remount") adb_command(["remount"]) # Make sure the system verity feature is disabled (Obviously, modified the system partition) logger.info("help_boot_avd: disable-verity") adb_command(["disable-verity"]) # Make SELinux permissive - in case SuperSu/Xposed didn't patch things right logger.info("help_boot_avd: setenforce") adb_command(["setenforce", "0"], shell=True) logger.info("help_boot_avd: finished!") return True except: PrintException("[ERROR] help_boot_avd") return False
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def start_avd(): try: if platform.system() == "Darwin": # There is a strage error in mac with the dyld one in a while.. # this should fix it.. if "DYLD_FALLBACK_LIBRARY_PATH" in list(os.environ.keys()): del os.environ["DYLD_FALLBACK_LIBRARY_PATH"] args = [ settings.AVD_EMULATOR, "-avd", settings.AVD_NAME, "-writable-system", "-no-snapshot-load", "-port", str(settings.AVD_ADB_PORT), ] logger.info("starting emulator: \r\n" + " ".join(args)) subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) return True except: PrintException("start_avd") return False
def start_avd(): try: if platform.system() == "Darwin": # There is a strage error in mac with the dyld one in a while.. # this should fix it.. if "DYLD_FALLBACK_LIBRARY_PATH" in list(os.environ.keys()): del os.environ["DYLD_FALLBACK_LIBRARY_PATH"] args = [ settings.AVD_EMULATOR, "-avd", settings.AVD_NAME, "-writable-system", "-no-snapshot-load", "-port", str(settings.AVD_ADB_PORT), ] logger.info("starting emulator: \r\n" + " ".join(args)) subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) return True except: PrintException("[ERROR] start_avd") return False
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def on_treeWidget_itemChanged(self, item, column): if item is self._get_current_treewidget_item() and column == 0: newText = str(item.text(0)) if ui_common.validate( not ui_common.EMPTY_FIELD_REGEX.match(newText), "The name can't be empty.", None, self.window(), ): self.window().app.monitor.suspend() self.stack.currentWidget().set_item_title(newText) self.stack.currentWidget().rebuild_item_path() persistGlobal = self.stack.currentWidget().save() self.window().app.monitor.unsuspend() self.window().app.config_altered(persistGlobal) self.treeWidget.sortItems(0, Qt.AscendingOrder) else: item.update()
def on_treeWidget_itemChanged(self, item, column): if item is self.treeWidget.selectedItems()[0] and column == 0: newText = str(item.text(0)) if ui_common.validate( not ui_common.EMPTY_FIELD_REGEX.match(newText), "The name can't be empty.", None, self.window(), ): self.window().app.monitor.suspend() self.stack.currentWidget().set_item_title(newText) self.stack.currentWidget().rebuild_item_path() persistGlobal = self.stack.currentWidget().save() self.window().app.monitor.unsuspend() self.window().app.config_altered(persistGlobal) self.treeWidget.sortItems(0, Qt.AscendingOrder) else: item.update()
https://github.com/autokey/autokey/issues/285
2019-05-21 21:45:48,995 DEBUG - service - Raw key: 's', modifiers: [<Key.CONTROL: '<ctrl>'>], Key: s 2019-05-21 21:45:48,995 DEBUG - root.Qt-GUI.System-tray-notifier - Show tray icon enabled in settings: True 2019-05-21 21:45:48,997 DEBUG - service - Window visible title: 'AutoKey', Window class: 'autokey-qt.autokey-qt' 2019-05-21 21:45:48,997 INFO - root.Qt-GUI.System-tray-notifier - Rebuilding model item actions, adding all items marked for access through the tray icon. 2019-05-21 21:45:48,998 DEBUG - phrase-menu - Sorting phrase menu by usage count Traceback (most recent call last): File "/usr/lib/python3/dist-packages/autokey/qtui/centralwidget.py", line 402, in on_save item = self.treeWidget.selectedItems()[0] IndexError: list index out of range Fatal Python error: Aborted
IndexError
def on_new_folder(self): parent_item = self._get_current_treewidget_item() self.__createFolder(parent_item)
def on_new_folder(self): parent_item = self.treeWidget.selectedItems()[0] self.__createFolder(parent_item)
https://github.com/autokey/autokey/issues/285
2019-05-21 21:45:48,995 DEBUG - service - Raw key: 's', modifiers: [<Key.CONTROL: '<ctrl>'>], Key: s 2019-05-21 21:45:48,995 DEBUG - root.Qt-GUI.System-tray-notifier - Show tray icon enabled in settings: True 2019-05-21 21:45:48,997 DEBUG - service - Window visible title: 'AutoKey', Window class: 'autokey-qt.autokey-qt' 2019-05-21 21:45:48,997 INFO - root.Qt-GUI.System-tray-notifier - Rebuilding model item actions, adding all items marked for access through the tray icon. 2019-05-21 21:45:48,998 DEBUG - phrase-menu - Sorting phrase menu by usage count Traceback (most recent call last): File "/usr/lib/python3/dist-packages/autokey/qtui/centralwidget.py", line 402, in on_save item = self.treeWidget.selectedItems()[0] IndexError: list index out of range Fatal Python error: Aborted
IndexError
def on_paste(self): parent_item = self._get_current_treewidget_item() parent = self.__extractData(parent_item) self.window().app.monitor.suspend() new_items = [] for item in self.cutCopiedItems: if isinstance(item, model.Folder): new_item = ak_tree.FolderWidgetItem(parent_item, item) ak_tree.WidgetItemFactory.process_folder(new_item, item) parent.add_folder(item) elif isinstance(item, model.Phrase): new_item = ak_tree.PhraseWidgetItem(parent_item, item) parent.add_item(item) else: new_item = ak_tree.ScriptWidgetItem(parent_item, item) parent.add_item(item) item.persist() new_items.append(new_item) self.treeWidget.sortItems(0, Qt.AscendingOrder) self.treeWidget.setCurrentItem(new_items[-1]) self.on_treeWidget_itemSelectionChanged() self.cutCopiedItems = [] for item in new_items: item.setSelected(True) self.window().app.monitor.unsuspend() self.window().app.config_altered(False)
def on_paste(self): parent_item = self.treeWidget.selectedItems()[0] parent = self.__extractData(parent_item) self.window().app.monitor.suspend() new_items = [] for item in self.cutCopiedItems: if isinstance(item, model.Folder): new_item = ak_tree.FolderWidgetItem(parent_item, item) ak_tree.WidgetItemFactory.process_folder(new_item, item) parent.add_folder(item) elif isinstance(item, model.Phrase): new_item = ak_tree.PhraseWidgetItem(parent_item, item) parent.add_item(item) else: new_item = ak_tree.ScriptWidgetItem(parent_item, item) parent.add_item(item) item.persist() new_items.append(new_item) self.treeWidget.sortItems(0, Qt.AscendingOrder) self.treeWidget.setCurrentItem(new_items[-1]) self.on_treeWidget_itemSelectionChanged() self.cutCopiedItems = [] for item in new_items: item.setSelected(True) self.window().app.monitor.unsuspend() self.window().app.config_altered(False)
https://github.com/autokey/autokey/issues/285
2019-05-21 21:45:48,995 DEBUG - service - Raw key: 's', modifiers: [<Key.CONTROL: '<ctrl>'>], Key: s 2019-05-21 21:45:48,995 DEBUG - root.Qt-GUI.System-tray-notifier - Show tray icon enabled in settings: True 2019-05-21 21:45:48,997 DEBUG - service - Window visible title: 'AutoKey', Window class: 'autokey-qt.autokey-qt' 2019-05-21 21:45:48,997 INFO - root.Qt-GUI.System-tray-notifier - Rebuilding model item actions, adding all items marked for access through the tray icon. 2019-05-21 21:45:48,998 DEBUG - phrase-menu - Sorting phrase menu by usage count Traceback (most recent call last): File "/usr/lib/python3/dist-packages/autokey/qtui/centralwidget.py", line 402, in on_save item = self.treeWidget.selectedItems()[0] IndexError: list index out of range Fatal Python error: Aborted
IndexError
def on_rename(self): widget_item = self._get_current_treewidget_item() self.treeWidget.editItem(widget_item, 0)
def on_rename(self): widget_item = self.treeWidget.selectedItems()[0] self.treeWidget.editItem(widget_item, 0)
https://github.com/autokey/autokey/issues/285
2019-05-21 21:45:48,995 DEBUG - service - Raw key: 's', modifiers: [<Key.CONTROL: '<ctrl>'>], Key: s 2019-05-21 21:45:48,995 DEBUG - root.Qt-GUI.System-tray-notifier - Show tray icon enabled in settings: True 2019-05-21 21:45:48,997 DEBUG - service - Window visible title: 'AutoKey', Window class: 'autokey-qt.autokey-qt' 2019-05-21 21:45:48,997 INFO - root.Qt-GUI.System-tray-notifier - Rebuilding model item actions, adding all items marked for access through the tray icon. 2019-05-21 21:45:48,998 DEBUG - phrase-menu - Sorting phrase menu by usage count Traceback (most recent call last): File "/usr/lib/python3/dist-packages/autokey/qtui/centralwidget.py", line 402, in on_save item = self.treeWidget.selectedItems()[0] IndexError: list index out of range Fatal Python error: Aborted
IndexError
def on_save(self): logger.info("User requested file save.") if self.stack.currentWidget().validate(): self.window().app.monitor.suspend() persist_global = self.stack.currentWidget().save() self.window().save_completed(persist_global) self.set_dirty(False) item = self._get_current_treewidget_item() item.update() self.treeWidget.update() self.treeWidget.sortItems(0, Qt.AscendingOrder) self.window().app.monitor.unsuspend() return False return True
def on_save(self): logger.info("User requested file save.") if self.stack.currentWidget().validate(): self.window().app.monitor.suspend() persist_global = self.stack.currentWidget().save() self.window().save_completed(persist_global) self.set_dirty(False) item = self.treeWidget.selectedItems()[0] item.update() self.treeWidget.update() self.treeWidget.sortItems(0, Qt.AscendingOrder) self.window().app.monitor.unsuspend() return False return True
https://github.com/autokey/autokey/issues/285
2019-05-21 21:45:48,995 DEBUG - service - Raw key: 's', modifiers: [<Key.CONTROL: '<ctrl>'>], Key: s 2019-05-21 21:45:48,995 DEBUG - root.Qt-GUI.System-tray-notifier - Show tray icon enabled in settings: True 2019-05-21 21:45:48,997 DEBUG - service - Window visible title: 'AutoKey', Window class: 'autokey-qt.autokey-qt' 2019-05-21 21:45:48,997 INFO - root.Qt-GUI.System-tray-notifier - Rebuilding model item actions, adding all items marked for access through the tray icon. 2019-05-21 21:45:48,998 DEBUG - phrase-menu - Sorting phrase menu by usage count Traceback (most recent call last): File "/usr/lib/python3/dist-packages/autokey/qtui/centralwidget.py", line 402, in on_save item = self.treeWidget.selectedItems()[0] IndexError: list index out of range Fatal Python error: Aborted
IndexError
def save(self, item): item.modes.append(model.TriggerMode.HOTKEY) # Build modifier list modifiers = self.build_modifiers() if self.key in self.REVERSE_KEY_MAP: key = self.REVERSE_KEY_MAP[self.key] else: key = self.key if key is None: raise RuntimeError("Attempt to set hotkey with no key") logger.info( "Item {} updated with hotkey {} and modifiers {}".format(item, key, modifiers) ) item.set_hotkey(modifiers, key)
def save(self, item): item.modes.append(model.TriggerMode.HOTKEY) # Build modifier list modifiers = self.build_modifiers() if self.key in self.REVERSE_KEY_MAP: key = self.REVERSE_KEY_MAP[self.key] else: key = self.key if key is None: raise RuntimeError("Attempt to set hotkey with no key") logger.info( "Item {} updated with hotkey {} and modifiers {}".format(item, key, modifiers) ) item.set_hot_update_key(modifiers, key)
https://github.com/autokey/autokey/issues/285
2019-05-21 21:45:48,995 DEBUG - service - Raw key: 's', modifiers: [<Key.CONTROL: '<ctrl>'>], Key: s 2019-05-21 21:45:48,995 DEBUG - root.Qt-GUI.System-tray-notifier - Show tray icon enabled in settings: True 2019-05-21 21:45:48,997 DEBUG - service - Window visible title: 'AutoKey', Window class: 'autokey-qt.autokey-qt' 2019-05-21 21:45:48,997 INFO - root.Qt-GUI.System-tray-notifier - Rebuilding model item actions, adding all items marked for access through the tray icon. 2019-05-21 21:45:48,998 DEBUG - phrase-menu - Sorting phrase menu by usage count Traceback (most recent call last): File "/usr/lib/python3/dist-packages/autokey/qtui/centralwidget.py", line 402, in on_save item = self.treeWidget.selectedItems()[0] IndexError: list index out of range Fatal Python error: Aborted
IndexError
def __init__(self): super(PhrasePage, self).__init__() self.setupUi(self) self.initialising = True self.current_phrase = None # type: model.Phrase for val in sorted(model.SEND_MODES.keys()): self.sendModeCombo.addItem(val) self.initialising = False
def __init__(self): super(PhrasePage, self).__init__() self.setupUi(self) self.initialising = True l = list(model.SEND_MODES.keys()) l.sort() for val in l: self.sendModeCombo.addItem(val) self.initialising = False
https://github.com/autokey/autokey/issues/285
2019-05-21 21:45:48,995 DEBUG - service - Raw key: 's', modifiers: [<Key.CONTROL: '<ctrl>'>], Key: s 2019-05-21 21:45:48,995 DEBUG - root.Qt-GUI.System-tray-notifier - Show tray icon enabled in settings: True 2019-05-21 21:45:48,997 DEBUG - service - Window visible title: 'AutoKey', Window class: 'autokey-qt.autokey-qt' 2019-05-21 21:45:48,997 INFO - root.Qt-GUI.System-tray-notifier - Rebuilding model item actions, adding all items marked for access through the tray icon. 2019-05-21 21:45:48,998 DEBUG - phrase-menu - Sorting phrase menu by usage count Traceback (most recent call last): File "/usr/lib/python3/dist-packages/autokey/qtui/centralwidget.py", line 402, in on_save item = self.treeWidget.selectedItems()[0] IndexError: list index out of range Fatal Python error: Aborted
IndexError
def load(self, phrase: model.Phrase): self.current_phrase = phrase self.phraseText.setPlainText(phrase.phrase) self.showInTrayCheckbox.setChecked(phrase.show_in_tray_menu) for k, v in model.SEND_MODES.items(): if v == phrase.sendMode: self.sendModeCombo.setCurrentIndex(self.sendModeCombo.findText(k)) break if self.is_new_item(): self.urlLabel.setEnabled(False) self.urlLabel.setText("(Unsaved)") # TODO: i18n else: ui_common.set_url_label(self.urlLabel, self.current_phrase.path) # TODO - re-enable me if restoring predictive functionality # self.predictCheckbox.setChecked(model.TriggerMode.PREDICTIVE in phrase.modes) self.promptCheckbox.setChecked(phrase.prompt) self.settingsWidget.load(phrase)
def load(self, phrase): self.currentPhrase = phrase self.phraseText.setPlainText(phrase.phrase) self.showInTrayCheckbox.setChecked(phrase.show_in_tray_menu) for k, v in model.SEND_MODES.items(): if v == phrase.sendMode: self.sendModeCombo.setCurrentIndex(self.sendModeCombo.findText(k)) break if self.is_new_item(): self.urlLabel.setEnabled(False) self.urlLabel.setText("(Unsaved)") # TODO: i18n else: ui_common.set_url_label(self.urlLabel, self.currentPhrase.path) # TODO - re-enable me if restoring predictive functionality # self.predictCheckbox.setChecked(model.TriggerMode.PREDICTIVE in phrase.modes) self.promptCheckbox.setChecked(phrase.prompt) self.settingsWidget.load(phrase)
https://github.com/autokey/autokey/issues/285
2019-05-21 21:45:48,995 DEBUG - service - Raw key: 's', modifiers: [<Key.CONTROL: '<ctrl>'>], Key: s 2019-05-21 21:45:48,995 DEBUG - root.Qt-GUI.System-tray-notifier - Show tray icon enabled in settings: True 2019-05-21 21:45:48,997 DEBUG - service - Window visible title: 'AutoKey', Window class: 'autokey-qt.autokey-qt' 2019-05-21 21:45:48,997 INFO - root.Qt-GUI.System-tray-notifier - Rebuilding model item actions, adding all items marked for access through the tray icon. 2019-05-21 21:45:48,998 DEBUG - phrase-menu - Sorting phrase menu by usage count Traceback (most recent call last): File "/usr/lib/python3/dist-packages/autokey/qtui/centralwidget.py", line 402, in on_save item = self.treeWidget.selectedItems()[0] IndexError: list index out of range Fatal Python error: Aborted
IndexError
def save(self): self.settingsWidget.save() self.current_phrase.phrase = str(self.phraseText.toPlainText()) self.current_phrase.show_in_tray_menu = self.showInTrayCheckbox.isChecked() self.current_phrase.sendMode = model.SEND_MODES[ str(self.sendModeCombo.currentText()) ] # TODO - re-enable me if restoring predictive functionality # if self.predictCheckbox.isChecked(): # self.currentPhrase.modes.append(model.TriggerMode.PREDICTIVE) self.current_phrase.prompt = self.promptCheckbox.isChecked() self.current_phrase.persist() ui_common.set_url_label(self.urlLabel, self.current_phrase.path) return False
def save(self): self.settingsWidget.save() self.currentPhrase.phrase = str(self.phraseText.toPlainText()) self.currentPhrase.show_in_tray_menu = self.showInTrayCheckbox.isChecked() self.currentPhrase.sendMode = model.SEND_MODES[ str(self.sendModeCombo.currentText()) ] # TODO - re-enable me if restoring predictive functionality # if self.predictCheckbox.isChecked(): # self.currentPhrase.modes.append(model.TriggerMode.PREDICTIVE) self.currentPhrase.prompt = self.promptCheckbox.isChecked() self.currentPhrase.persist() ui_common.set_url_label(self.urlLabel, self.currentPhrase.path) return False
https://github.com/autokey/autokey/issues/285
2019-05-21 21:45:48,995 DEBUG - service - Raw key: 's', modifiers: [<Key.CONTROL: '<ctrl>'>], Key: s 2019-05-21 21:45:48,995 DEBUG - root.Qt-GUI.System-tray-notifier - Show tray icon enabled in settings: True 2019-05-21 21:45:48,997 DEBUG - service - Window visible title: 'AutoKey', Window class: 'autokey-qt.autokey-qt' 2019-05-21 21:45:48,997 INFO - root.Qt-GUI.System-tray-notifier - Rebuilding model item actions, adding all items marked for access through the tray icon. 2019-05-21 21:45:48,998 DEBUG - phrase-menu - Sorting phrase menu by usage count Traceback (most recent call last): File "/usr/lib/python3/dist-packages/autokey/qtui/centralwidget.py", line 402, in on_save item = self.treeWidget.selectedItems()[0] IndexError: list index out of range Fatal Python error: Aborted
IndexError
def set_item_title(self, title): self.current_phrase.description = title
def set_item_title(self, title): self.currentPhrase.description = title
https://github.com/autokey/autokey/issues/285
2019-05-21 21:45:48,995 DEBUG - service - Raw key: 's', modifiers: [<Key.CONTROL: '<ctrl>'>], Key: s 2019-05-21 21:45:48,995 DEBUG - root.Qt-GUI.System-tray-notifier - Show tray icon enabled in settings: True 2019-05-21 21:45:48,997 DEBUG - service - Window visible title: 'AutoKey', Window class: 'autokey-qt.autokey-qt' 2019-05-21 21:45:48,997 INFO - root.Qt-GUI.System-tray-notifier - Rebuilding model item actions, adding all items marked for access through the tray icon. 2019-05-21 21:45:48,998 DEBUG - phrase-menu - Sorting phrase menu by usage count Traceback (most recent call last): File "/usr/lib/python3/dist-packages/autokey/qtui/centralwidget.py", line 402, in on_save item = self.treeWidget.selectedItems()[0] IndexError: list index out of range Fatal Python error: Aborted
IndexError
def rebuild_item_path(self): self.current_phrase.rebuild_path()
def rebuild_item_path(self): self.currentPhrase.rebuild_path()
https://github.com/autokey/autokey/issues/285
2019-05-21 21:45:48,995 DEBUG - service - Raw key: 's', modifiers: [<Key.CONTROL: '<ctrl>'>], Key: s 2019-05-21 21:45:48,995 DEBUG - root.Qt-GUI.System-tray-notifier - Show tray icon enabled in settings: True 2019-05-21 21:45:48,997 DEBUG - service - Window visible title: 'AutoKey', Window class: 'autokey-qt.autokey-qt' 2019-05-21 21:45:48,997 INFO - root.Qt-GUI.System-tray-notifier - Rebuilding model item actions, adding all items marked for access through the tray icon. 2019-05-21 21:45:48,998 DEBUG - phrase-menu - Sorting phrase menu by usage count Traceback (most recent call last): File "/usr/lib/python3/dist-packages/autokey/qtui/centralwidget.py", line 402, in on_save item = self.treeWidget.selectedItems()[0] IndexError: list index out of range Fatal Python error: Aborted
IndexError
def is_new_item(self): return self.current_phrase.path is None
def is_new_item(self): return self.currentPhrase.path is None
https://github.com/autokey/autokey/issues/285
2019-05-21 21:45:48,995 DEBUG - service - Raw key: 's', modifiers: [<Key.CONTROL: '<ctrl>'>], Key: s 2019-05-21 21:45:48,995 DEBUG - root.Qt-GUI.System-tray-notifier - Show tray icon enabled in settings: True 2019-05-21 21:45:48,997 DEBUG - service - Window visible title: 'AutoKey', Window class: 'autokey-qt.autokey-qt' 2019-05-21 21:45:48,997 INFO - root.Qt-GUI.System-tray-notifier - Rebuilding model item actions, adding all items marked for access through the tray icon. 2019-05-21 21:45:48,998 DEBUG - phrase-menu - Sorting phrase menu by usage count Traceback (most recent call last): File "/usr/lib/python3/dist-packages/autokey/qtui/centralwidget.py", line 402, in on_save item = self.treeWidget.selectedItems()[0] IndexError: list index out of range Fatal Python error: Aborted
IndexError
def reset(self): self.load(self.current_phrase)
def reset(self): self.load(self.currentPhrase)
https://github.com/autokey/autokey/issues/285
2019-05-21 21:45:48,995 DEBUG - service - Raw key: 's', modifiers: [<Key.CONTROL: '<ctrl>'>], Key: s 2019-05-21 21:45:48,995 DEBUG - root.Qt-GUI.System-tray-notifier - Show tray icon enabled in settings: True 2019-05-21 21:45:48,997 DEBUG - service - Window visible title: 'AutoKey', Window class: 'autokey-qt.autokey-qt' 2019-05-21 21:45:48,997 INFO - root.Qt-GUI.System-tray-notifier - Rebuilding model item actions, adding all items marked for access through the tray icon. 2019-05-21 21:45:48,998 DEBUG - phrase-menu - Sorting phrase menu by usage count Traceback (most recent call last): File "/usr/lib/python3/dist-packages/autokey/qtui/centralwidget.py", line 402, in on_save item = self.treeWidget.selectedItems()[0] IndexError: list index out of range Fatal Python error: Aborted
IndexError
def __init__(self, app): """ Create initial default configuration """ self.VERSION = self.__class__.CLASS_VERSION self.lock = threading.Lock() self.app = app self.folders = [] self.userCodeDir = None # type: str self.configHotkey = GlobalHotkey() self.configHotkey.set_hotkey(["<super>"], "k") self.configHotkey.enabled = True self.toggleServiceHotkey = GlobalHotkey() self.toggleServiceHotkey.set_hotkey(["<super>", "<shift>"], "k") self.toggleServiceHotkey.enabled = True # Set the attribute to the default first. Without this, AK breaks, if started for the first time. See #274 self.workAroundApps = re.compile(self.SETTINGS[WORKAROUND_APP_REGEX]) app.init_global_hotkeys(self) self.load_global_config() self.app.monitor.add_watch(CONFIG_DEFAULT_FOLDER) self.app.monitor.add_watch(common.CONFIG_DIR) if self.folders: return # --- Code below here only executed if no persisted config data provided _logger.info("No configuration found - creating new one") myPhrases = model.Folder("My Phrases") myPhrases.set_hotkey(["<ctrl>"], "<f7>") myPhrases.set_modes([model.TriggerMode.HOTKEY]) myPhrases.persist() f = model.Folder("Addresses") adr = model.Phrase("Home Address", "22 Avenue Street\nBrisbane\nQLD\n4000") adr.set_modes([model.TriggerMode.ABBREVIATION]) adr.add_abbreviation("adr") f.add_item(adr) myPhrases.add_folder(f) f.persist() adr.persist() p = model.Phrase("First phrase", "Test phrase number one!") p.set_modes([model.TriggerMode.PREDICTIVE]) p.set_window_titles(".* - gedit") myPhrases.add_item(p) myPhrases.add_item(model.Phrase("Second phrase", "Test phrase number two!")) myPhrases.add_item(model.Phrase("Third phrase", "Test phrase number three!")) self.folders.append(myPhrases) [p.persist() for p in myPhrases.items] sampleScripts = model.Folder("Sample Scripts") sampleScripts.persist() dte = model.Script("Insert Date", "") dte.code = """output = system.exec_command("date") keyboard.send_keys(output)""" sampleScripts.add_item(dte) lMenu = model.Script("List Menu", "") lMenu.code = """choices = ["something", "something else", "a third thing"] retCode, choice = dialog.list_menu(choices) if retCode == 0: keyboard.send_keys("You chose " + choice)""" sampleScripts.add_item(lMenu) sel = model.Script("Selection Test", "") sel.code = """text = clipboard.get_selection() keyboard.send_key("<delete>") keyboard.send_keys("The text %s was here previously" % text)""" sampleScripts.add_item(sel) abbrc = model.Script("Abbreviation from selection", "") abbrc.code = """import time time.sleep(0.25) contents = clipboard.get_selection() retCode, abbr = dialog.input_dialog("New Abbreviation", "Choose an abbreviation for the new phrase") if retCode == 0: if len(contents) > 20: title = contents[0:17] + "..." else: title = contents folder = engine.get_folder("My Phrases") engine.create_abbreviation(folder, title, abbr, contents)""" sampleScripts.add_item(abbrc) phrasec = model.Script("Phrase from selection", "") phrasec.code = """import time time.sleep(0.25) contents = clipboard.get_selection() if len(contents) > 20: title = contents[0:17] + "..." else: title = contents folder = engine.get_folder("My Phrases") engine.create_phrase(folder, title, contents)""" sampleScripts.add_item(phrasec) win = model.Script("Display window info", "") win.code = """# Displays the information of the next window to be left-clicked import time mouse.wait_for_click(1) time.sleep(0.2) winTitle = window.get_active_title() winClass = window.get_active_class() dialog.info_dialog("Window information", "Active window information:\\nTitle: '%s'\\nClass: '%s'" % (winTitle, winClass))""" win.show_in_tray_menu = True sampleScripts.add_item(win) self.folders.append(sampleScripts) [s.persist() for s in sampleScripts.items] # TODO - future functionality self.recentEntries = [] self.config_altered(True)
def __init__(self, app): """ Create initial default configuration """ self.VERSION = self.__class__.CLASS_VERSION self.lock = threading.Lock() self.app = app self.folders = [] self.userCodeDir = None # type: str self.configHotkey = GlobalHotkey() self.configHotkey.set_hotkey(["<super>"], "k") self.configHotkey.enabled = True self.toggleServiceHotkey = GlobalHotkey() self.toggleServiceHotkey.set_hotkey(["<super>", "<shift>"], "k") self.toggleServiceHotkey.enabled = True app.init_global_hotkeys(self) self.load_global_config() self.app.monitor.add_watch(CONFIG_DEFAULT_FOLDER) self.app.monitor.add_watch(common.CONFIG_DIR) if self.folders: return # --- Code below here only executed if no persisted config data provided _logger.info("No configuration found - creating new one") myPhrases = model.Folder("My Phrases") myPhrases.set_hotkey(["<ctrl>"], "<f7>") myPhrases.set_modes([model.TriggerMode.HOTKEY]) myPhrases.persist() f = model.Folder("Addresses") adr = model.Phrase("Home Address", "22 Avenue Street\nBrisbane\nQLD\n4000") adr.set_modes([model.TriggerMode.ABBREVIATION]) adr.add_abbreviation("adr") f.add_item(adr) myPhrases.add_folder(f) f.persist() adr.persist() p = model.Phrase("First phrase", "Test phrase number one!") p.set_modes([model.TriggerMode.PREDICTIVE]) p.set_window_titles(".* - gedit") myPhrases.add_item(p) myPhrases.add_item(model.Phrase("Second phrase", "Test phrase number two!")) myPhrases.add_item(model.Phrase("Third phrase", "Test phrase number three!")) self.folders.append(myPhrases) [p.persist() for p in myPhrases.items] sampleScripts = model.Folder("Sample Scripts") sampleScripts.persist() dte = model.Script("Insert Date", "") dte.code = """output = system.exec_command("date") keyboard.send_keys(output)""" sampleScripts.add_item(dte) lMenu = model.Script("List Menu", "") lMenu.code = """choices = ["something", "something else", "a third thing"] retCode, choice = dialog.list_menu(choices) if retCode == 0: keyboard.send_keys("You chose " + choice)""" sampleScripts.add_item(lMenu) sel = model.Script("Selection Test", "") sel.code = """text = clipboard.get_selection() keyboard.send_key("<delete>") keyboard.send_keys("The text %s was here previously" % text)""" sampleScripts.add_item(sel) abbrc = model.Script("Abbreviation from selection", "") abbrc.code = """import time time.sleep(0.25) contents = clipboard.get_selection() retCode, abbr = dialog.input_dialog("New Abbreviation", "Choose an abbreviation for the new phrase") if retCode == 0: if len(contents) > 20: title = contents[0:17] + "..." else: title = contents folder = engine.get_folder("My Phrases") engine.create_abbreviation(folder, title, abbr, contents)""" sampleScripts.add_item(abbrc) phrasec = model.Script("Phrase from selection", "") phrasec.code = """import time time.sleep(0.25) contents = clipboard.get_selection() if len(contents) > 20: title = contents[0:17] + "..." else: title = contents folder = engine.get_folder("My Phrases") engine.create_phrase(folder, title, contents)""" sampleScripts.add_item(phrasec) win = model.Script("Display window info", "") win.code = """# Displays the information of the next window to be left-clicked import time mouse.wait_for_click(1) time.sleep(0.2) winTitle = window.get_active_title() winClass = window.get_active_class() dialog.info_dialog("Window information", "Active window information:\\nTitle: '%s'\\nClass: '%s'" % (winTitle, winClass))""" win.show_in_tray_menu = True sampleScripts.add_item(win) self.folders.append(sampleScripts) [s.persist() for s in sampleScripts.items] # TODO - future functionality self.recentEntries = [] self.config_altered(True)
https://github.com/autokey/autokey/issues/274
Input stack at end of handle_keypress: deque([' ', '#', 'D'], maxlen=150) Key.SHIFT released Raw key: ' ', modifiers: [], Key: Window visible title: 'AutoKey', Window class: 'autokey-qt.autokey-qt' No phrase/script matched hotkey Script runner executing: Script('Insert Date') Send special key: [<Key.BACKSPACE: '<backspace>'>] Input stack at end of handle_keypress: deque([], maxlen=150) Ignored locking error in handle_keypress Traceback (most recent call last): File "/home/me/.local/lib/python3.7/site-packages/autokey/service.py", line 206, in __tryReleaseLock self.configManager.lock.release() RuntimeError: release unlocked lock Send special key: [<Key.BACKSPACE: '<backspace>'>] Send via event interface Send via event interface Send special key: [<Key.BACKSPACE: '<backspace>'>] Sending string: 'April, 24 2019' Error in X event loop thread Traceback (most recent call last): File "/home/me/.local/lib/python3.7/site-packages/autokey/interface.py", line 242, in __eventLoop method(*args) File "/home/me/.local/lib/python3.7/site-packages/autokey/interface.py", line 705, in __sendString self.__checkWorkaroundNeeded() File "/home/me/.local/lib/python3.7/site-packages/autokey/interface.py", line 1005, in __checkWorkaroundNeeded w = self.app.configManager.workAroundApps AttributeError: 'ConfigManager' object has no attribute 'workAroundApps'
RuntimeError
def on_show_error(self, widget, data=None): self.on_show_configure(widget, data) self.app.show_script_error(self.app.configWindow.ui) self.errorItem.hide() self.update_visible_status()
def on_show_error(self, widget, data=None): self.app.show_script_error(self.app.configWindow.ui) self.errorItem.hide() self.update_visible_status()
https://github.com/autokey/autokey/issues/222
Traceback (most recent call last): File '~/autokey/gtkui/notifier.py", line 140, in on_show_error self.app.show_script_error(self.app.configWindow.ui) AttributeError: 'NoneType' object has no attribute 'ui'
AttributeError
def _send_string_clipboard(self, string: str, paste_command: model.SendMode): """ Use the clipboard to send a string. """ backup = ( self.clipboard.text ) # Keep a backup of current content, to restore the original afterwards. if backup is None: logger.warning( "Tried to backup the X clipboard content, but got None instead of a string." ) self.clipboard.text = string try: self.mediator.send_string(paste_command.value) finally: self.ungrab_keyboard() # Because send_string is queued, also enqueue the clipboard restore, to keep the proper action ordering. self.__enqueue(self._restore_clipboard_text, backup)
def _send_string_clipboard(self, string: str, paste_command: model.SendMode): """Use the clipboard to send a string.""" backup = ( self.clipboard.text ) # Keep a backup of current content, to restore the original afterwards. self.clipboard.text = string self.mediator.send_string(paste_command.value) # Because send_string is queued, also enqueue the clipboard restore, to keep the proper action ordering. self.__enqueue(self._restore_clipboard_text, backup)
https://github.com/autokey/autokey/issues/226
2018-12-05 07:02:31,958 DEBUG - service - Raw key: 'b', modifiers: [], Key: b 2018-12-05 07:02:31,958 DEBUG - service - Window visible title: '*Unbenannt 1 - Mousepad', Window class: 'mousepad.Mousepad' 2018-12-05 07:02:31,958 DEBUG - service - No phrase/script matched hotkey 2018-12-05 07:02:31,958 DEBUG - service - Input stack at end of handle_keypress: deque(['b'], maxlen=150) 2018-12-05 07:02:32,127 DEBUG - service - Raw key: ' ', modifiers: [], Key: 2018-12-05 07:02:32,128 DEBUG - service - Window visible title: '*Unbenannt 1 - Mousepad', Window class: 'mousepad.Mousepad' 2018-12-05 07:02:32,128 DEBUG - service - No phrase/script matched hotkey 2018-12-05 07:02:32,132 DEBUG - iomediator - Send via clipboard 2018-12-05 07:02:32,133 DEBUG - service - Input stack at end of handle_keypress: deque([], maxlen=150) 2018-12-05 07:02:32,133 DEBUG - interface - Sending string via clipboard: a 2018-12-05 07:02:32,133 ERROR - service - Ignored locking error in handle_keypress Traceback (most recent call last): File "/usr/lib/python3.7/site-packages/autokey/service.py", line 207, in __tryReleaseLock self.configManager.lock.release() RuntimeError: release unlocked lock 2018-12-05 07:02:32,135 DEBUG - interface - Sending via clipboard enqueued. 2018-12-05 07:02:32,135 DEBUG - interface - Send special key: [<Key.BACKSPACE: '<backspace>'>] 2018-12-05 07:02:32,137 DEBUG - interface - Send special key: [<Key.BACKSPACE: '<backspace>'>] 2018-12-05 07:02:32,139 DEBUG - iomediator - Send via event interface 2018-12-05 07:02:32,139 DEBUG - interface - Send modified key: modifiers: ['<shift>'] key: <insert> 2018-12-05 07:02:32,242 ERROR - interface - Error in X event loop thread Traceback (most recent call last): File "/usr/lib/python3.7/site-packages/autokey/interface.py", line 230, in __eventLoop method(*args) File "/usr/lib/python3.7/site-packages/autokey/interface.py", line 626, in _restore_clipboard_text self.clipboard.text = backup File "/usr/lib/python3.7/site-packages/autokey/interface.py", line 161, in text self._clipboard.set_text(new_content, -1) TypeError: Argument 1 does not allow None as a value 2018-12-05 07:02:33,039 DEBUG - service - Raw key: 'b', modifiers: [], Key: b 2018-12-05 07:02:33,040 DEBUG - service - Window visible title: '*Unbenannt 1 - Mousepad', Window class: 'mousepad.Mousepad' 2018-12-05 07:02:33,040 DEBUG - service - No phrase/script matched hotkey 2018-12-05 07:02:33,041 DEBUG - service - Input stack at end of handle_keypress: deque(['b'], maxlen=150) 2018-12-05 07:02:33,318 DEBUG - service - Raw key: ' ', modifiers: [], Key: 2018-12-05 07:02:33,319 DEBUG - service - Window visible title: '*Unbenannt 1 - Mousepad', Window class: 'mousepad.Mousepad' 2018-12-05 07:02:33,319 DEBUG - service - No phrase/script matched hotkey 2018-12-05 07:02:33,322 DEBUG - iomediator - Send via clipboard 2018-12-05 07:02:33,323 DEBUG - service - Input stack at end of handle_keypress: deque([], maxlen=150) 2018-12-05 07:02:33,325 DEBUG - interface - Sending string via clipboard: a 2018-12-05 07:02:33,327 ERROR - service - Ignored locking error in handle_keypress Traceback (most recent call last): File "/usr/lib/python3.7/site-packages/autokey/service.py", line 207, in __tryReleaseLock self.configManager.lock.release() RuntimeError: release unlocked lock 2018-12-05 07:02:33,328 DEBUG - interface - Sending via clipboard enqueued. 2018-12-05 07:02:33,329 DEBUG - interface - Send special key: [<Key.BACKSPACE: '<backspace>'>] 2018-12-05 07:02:33,333 DEBUG - interface - Send special key: [<Key.BACKSPACE: '<backspace>'>]
RuntimeError
def _restore_clipboard_text(self, backup: str): """Restore the clipboard content.""" # Pasting takes some time, so wait a bit before restoring the content. Otherwise the restore is done before # the pasting happens, causing the backup to be pasted instead of the desired clipboard content. time.sleep(0.2) self.clipboard.text = backup if backup is not None else ""
def _restore_clipboard_text(self, backup: str): """Restore the clipboard content.""" # Pasting takes some time, so wait a bit before restoring the content. Otherwise the restore is done before # the pasting happens, causing the backup to be pasted instead of the desired clipboard content. time.sleep(0.1) self.clipboard.text = backup
https://github.com/autokey/autokey/issues/226
2018-12-05 07:02:31,958 DEBUG - service - Raw key: 'b', modifiers: [], Key: b 2018-12-05 07:02:31,958 DEBUG - service - Window visible title: '*Unbenannt 1 - Mousepad', Window class: 'mousepad.Mousepad' 2018-12-05 07:02:31,958 DEBUG - service - No phrase/script matched hotkey 2018-12-05 07:02:31,958 DEBUG - service - Input stack at end of handle_keypress: deque(['b'], maxlen=150) 2018-12-05 07:02:32,127 DEBUG - service - Raw key: ' ', modifiers: [], Key: 2018-12-05 07:02:32,128 DEBUG - service - Window visible title: '*Unbenannt 1 - Mousepad', Window class: 'mousepad.Mousepad' 2018-12-05 07:02:32,128 DEBUG - service - No phrase/script matched hotkey 2018-12-05 07:02:32,132 DEBUG - iomediator - Send via clipboard 2018-12-05 07:02:32,133 DEBUG - service - Input stack at end of handle_keypress: deque([], maxlen=150) 2018-12-05 07:02:32,133 DEBUG - interface - Sending string via clipboard: a 2018-12-05 07:02:32,133 ERROR - service - Ignored locking error in handle_keypress Traceback (most recent call last): File "/usr/lib/python3.7/site-packages/autokey/service.py", line 207, in __tryReleaseLock self.configManager.lock.release() RuntimeError: release unlocked lock 2018-12-05 07:02:32,135 DEBUG - interface - Sending via clipboard enqueued. 2018-12-05 07:02:32,135 DEBUG - interface - Send special key: [<Key.BACKSPACE: '<backspace>'>] 2018-12-05 07:02:32,137 DEBUG - interface - Send special key: [<Key.BACKSPACE: '<backspace>'>] 2018-12-05 07:02:32,139 DEBUG - iomediator - Send via event interface 2018-12-05 07:02:32,139 DEBUG - interface - Send modified key: modifiers: ['<shift>'] key: <insert> 2018-12-05 07:02:32,242 ERROR - interface - Error in X event loop thread Traceback (most recent call last): File "/usr/lib/python3.7/site-packages/autokey/interface.py", line 230, in __eventLoop method(*args) File "/usr/lib/python3.7/site-packages/autokey/interface.py", line 626, in _restore_clipboard_text self.clipboard.text = backup File "/usr/lib/python3.7/site-packages/autokey/interface.py", line 161, in text self._clipboard.set_text(new_content, -1) TypeError: Argument 1 does not allow None as a value 2018-12-05 07:02:33,039 DEBUG - service - Raw key: 'b', modifiers: [], Key: b 2018-12-05 07:02:33,040 DEBUG - service - Window visible title: '*Unbenannt 1 - Mousepad', Window class: 'mousepad.Mousepad' 2018-12-05 07:02:33,040 DEBUG - service - No phrase/script matched hotkey 2018-12-05 07:02:33,041 DEBUG - service - Input stack at end of handle_keypress: deque(['b'], maxlen=150) 2018-12-05 07:02:33,318 DEBUG - service - Raw key: ' ', modifiers: [], Key: 2018-12-05 07:02:33,319 DEBUG - service - Window visible title: '*Unbenannt 1 - Mousepad', Window class: 'mousepad.Mousepad' 2018-12-05 07:02:33,319 DEBUG - service - No phrase/script matched hotkey 2018-12-05 07:02:33,322 DEBUG - iomediator - Send via clipboard 2018-12-05 07:02:33,323 DEBUG - service - Input stack at end of handle_keypress: deque([], maxlen=150) 2018-12-05 07:02:33,325 DEBUG - interface - Sending string via clipboard: a 2018-12-05 07:02:33,327 ERROR - service - Ignored locking error in handle_keypress Traceback (most recent call last): File "/usr/lib/python3.7/site-packages/autokey/service.py", line 207, in __tryReleaseLock self.configManager.lock.release() RuntimeError: release unlocked lock 2018-12-05 07:02:33,328 DEBUG - interface - Sending via clipboard enqueued. 2018-12-05 07:02:33,329 DEBUG - interface - Send special key: [<Key.BACKSPACE: '<backspace>'>] 2018-12-05 07:02:33,333 DEBUG - interface - Send special key: [<Key.BACKSPACE: '<backspace>'>]
RuntimeError
def _send_string_selection(self, string: str): """Use the mouse selection clipboard to send a string.""" backup = ( self.clipboard.selection ) # Keep a backup of current content, to restore the original afterwards. if backup is None: logger.warning( "Tried to backup the X PRIMARY selection content, but got None instead of a string." ) self.clipboard.selection = string self.__enqueue(self._paste_using_mouse_button_2) self.__enqueue(self._restore_clipboard_selection, backup)
def _send_string_selection(self, string: str): """Use the mouse selection clipboard to send a string.""" backup = ( self.clipboard.selection ) # Keep a backup of current content, to restore the original afterwards. self.clipboard.selection = string self.__enqueue(self._paste_using_mouse_button_2) self.__enqueue(self._restore_clipboard_selection, backup)
https://github.com/autokey/autokey/issues/226
2018-12-05 07:02:31,958 DEBUG - service - Raw key: 'b', modifiers: [], Key: b 2018-12-05 07:02:31,958 DEBUG - service - Window visible title: '*Unbenannt 1 - Mousepad', Window class: 'mousepad.Mousepad' 2018-12-05 07:02:31,958 DEBUG - service - No phrase/script matched hotkey 2018-12-05 07:02:31,958 DEBUG - service - Input stack at end of handle_keypress: deque(['b'], maxlen=150) 2018-12-05 07:02:32,127 DEBUG - service - Raw key: ' ', modifiers: [], Key: 2018-12-05 07:02:32,128 DEBUG - service - Window visible title: '*Unbenannt 1 - Mousepad', Window class: 'mousepad.Mousepad' 2018-12-05 07:02:32,128 DEBUG - service - No phrase/script matched hotkey 2018-12-05 07:02:32,132 DEBUG - iomediator - Send via clipboard 2018-12-05 07:02:32,133 DEBUG - service - Input stack at end of handle_keypress: deque([], maxlen=150) 2018-12-05 07:02:32,133 DEBUG - interface - Sending string via clipboard: a 2018-12-05 07:02:32,133 ERROR - service - Ignored locking error in handle_keypress Traceback (most recent call last): File "/usr/lib/python3.7/site-packages/autokey/service.py", line 207, in __tryReleaseLock self.configManager.lock.release() RuntimeError: release unlocked lock 2018-12-05 07:02:32,135 DEBUG - interface - Sending via clipboard enqueued. 2018-12-05 07:02:32,135 DEBUG - interface - Send special key: [<Key.BACKSPACE: '<backspace>'>] 2018-12-05 07:02:32,137 DEBUG - interface - Send special key: [<Key.BACKSPACE: '<backspace>'>] 2018-12-05 07:02:32,139 DEBUG - iomediator - Send via event interface 2018-12-05 07:02:32,139 DEBUG - interface - Send modified key: modifiers: ['<shift>'] key: <insert> 2018-12-05 07:02:32,242 ERROR - interface - Error in X event loop thread Traceback (most recent call last): File "/usr/lib/python3.7/site-packages/autokey/interface.py", line 230, in __eventLoop method(*args) File "/usr/lib/python3.7/site-packages/autokey/interface.py", line 626, in _restore_clipboard_text self.clipboard.text = backup File "/usr/lib/python3.7/site-packages/autokey/interface.py", line 161, in text self._clipboard.set_text(new_content, -1) TypeError: Argument 1 does not allow None as a value 2018-12-05 07:02:33,039 DEBUG - service - Raw key: 'b', modifiers: [], Key: b 2018-12-05 07:02:33,040 DEBUG - service - Window visible title: '*Unbenannt 1 - Mousepad', Window class: 'mousepad.Mousepad' 2018-12-05 07:02:33,040 DEBUG - service - No phrase/script matched hotkey 2018-12-05 07:02:33,041 DEBUG - service - Input stack at end of handle_keypress: deque(['b'], maxlen=150) 2018-12-05 07:02:33,318 DEBUG - service - Raw key: ' ', modifiers: [], Key: 2018-12-05 07:02:33,319 DEBUG - service - Window visible title: '*Unbenannt 1 - Mousepad', Window class: 'mousepad.Mousepad' 2018-12-05 07:02:33,319 DEBUG - service - No phrase/script matched hotkey 2018-12-05 07:02:33,322 DEBUG - iomediator - Send via clipboard 2018-12-05 07:02:33,323 DEBUG - service - Input stack at end of handle_keypress: deque([], maxlen=150) 2018-12-05 07:02:33,325 DEBUG - interface - Sending string via clipboard: a 2018-12-05 07:02:33,327 ERROR - service - Ignored locking error in handle_keypress Traceback (most recent call last): File "/usr/lib/python3.7/site-packages/autokey/service.py", line 207, in __tryReleaseLock self.configManager.lock.release() RuntimeError: release unlocked lock 2018-12-05 07:02:33,328 DEBUG - interface - Sending via clipboard enqueued. 2018-12-05 07:02:33,329 DEBUG - interface - Send special key: [<Key.BACKSPACE: '<backspace>'>] 2018-12-05 07:02:33,333 DEBUG - interface - Send special key: [<Key.BACKSPACE: '<backspace>'>]
RuntimeError
def _restore_clipboard_selection(self, backup: str): """Restore the selection clipboard content.""" # Pasting takes some time, so wait a bit before restoring the content. Otherwise the restore is done before # the pasting happens, causing the backup to be pasted instead of the desired clipboard content. # Programmatically pressing the middle mouse button seems VERY slow, so wait rather long. # It might be a good idea to make this delay configurable. There might be systems that need even longer. time.sleep(1) self.clipboard.selection = backup if backup is not None else ""
def _restore_clipboard_selection(self, backup: str): """Restore the selection clipboard content.""" # Pasting takes some time, so wait a bit before restoring the content. Otherwise the restore is done before # the pasting happens, causing the backup to be pasted instead of the desired clipboard content. # Programmatically pressing the middle mouse button seems VERY slow, so wait rather long. # It might be a good idea to make this delay configurable. There might be systems that need even longer. time.sleep(1) self.clipboard.selection = backup
https://github.com/autokey/autokey/issues/226
2018-12-05 07:02:31,958 DEBUG - service - Raw key: 'b', modifiers: [], Key: b 2018-12-05 07:02:31,958 DEBUG - service - Window visible title: '*Unbenannt 1 - Mousepad', Window class: 'mousepad.Mousepad' 2018-12-05 07:02:31,958 DEBUG - service - No phrase/script matched hotkey 2018-12-05 07:02:31,958 DEBUG - service - Input stack at end of handle_keypress: deque(['b'], maxlen=150) 2018-12-05 07:02:32,127 DEBUG - service - Raw key: ' ', modifiers: [], Key: 2018-12-05 07:02:32,128 DEBUG - service - Window visible title: '*Unbenannt 1 - Mousepad', Window class: 'mousepad.Mousepad' 2018-12-05 07:02:32,128 DEBUG - service - No phrase/script matched hotkey 2018-12-05 07:02:32,132 DEBUG - iomediator - Send via clipboard 2018-12-05 07:02:32,133 DEBUG - service - Input stack at end of handle_keypress: deque([], maxlen=150) 2018-12-05 07:02:32,133 DEBUG - interface - Sending string via clipboard: a 2018-12-05 07:02:32,133 ERROR - service - Ignored locking error in handle_keypress Traceback (most recent call last): File "/usr/lib/python3.7/site-packages/autokey/service.py", line 207, in __tryReleaseLock self.configManager.lock.release() RuntimeError: release unlocked lock 2018-12-05 07:02:32,135 DEBUG - interface - Sending via clipboard enqueued. 2018-12-05 07:02:32,135 DEBUG - interface - Send special key: [<Key.BACKSPACE: '<backspace>'>] 2018-12-05 07:02:32,137 DEBUG - interface - Send special key: [<Key.BACKSPACE: '<backspace>'>] 2018-12-05 07:02:32,139 DEBUG - iomediator - Send via event interface 2018-12-05 07:02:32,139 DEBUG - interface - Send modified key: modifiers: ['<shift>'] key: <insert> 2018-12-05 07:02:32,242 ERROR - interface - Error in X event loop thread Traceback (most recent call last): File "/usr/lib/python3.7/site-packages/autokey/interface.py", line 230, in __eventLoop method(*args) File "/usr/lib/python3.7/site-packages/autokey/interface.py", line 626, in _restore_clipboard_text self.clipboard.text = backup File "/usr/lib/python3.7/site-packages/autokey/interface.py", line 161, in text self._clipboard.set_text(new_content, -1) TypeError: Argument 1 does not allow None as a value 2018-12-05 07:02:33,039 DEBUG - service - Raw key: 'b', modifiers: [], Key: b 2018-12-05 07:02:33,040 DEBUG - service - Window visible title: '*Unbenannt 1 - Mousepad', Window class: 'mousepad.Mousepad' 2018-12-05 07:02:33,040 DEBUG - service - No phrase/script matched hotkey 2018-12-05 07:02:33,041 DEBUG - service - Input stack at end of handle_keypress: deque(['b'], maxlen=150) 2018-12-05 07:02:33,318 DEBUG - service - Raw key: ' ', modifiers: [], Key: 2018-12-05 07:02:33,319 DEBUG - service - Window visible title: '*Unbenannt 1 - Mousepad', Window class: 'mousepad.Mousepad' 2018-12-05 07:02:33,319 DEBUG - service - No phrase/script matched hotkey 2018-12-05 07:02:33,322 DEBUG - iomediator - Send via clipboard 2018-12-05 07:02:33,323 DEBUG - service - Input stack at end of handle_keypress: deque([], maxlen=150) 2018-12-05 07:02:33,325 DEBUG - interface - Sending string via clipboard: a 2018-12-05 07:02:33,327 ERROR - service - Ignored locking error in handle_keypress Traceback (most recent call last): File "/usr/lib/python3.7/site-packages/autokey/service.py", line 207, in __tryReleaseLock self.configManager.lock.release() RuntimeError: release unlocked lock 2018-12-05 07:02:33,328 DEBUG - interface - Sending via clipboard enqueued. 2018-12-05 07:02:33,329 DEBUG - interface - Send special key: [<Key.BACKSPACE: '<backspace>'>] 2018-12-05 07:02:33,333 DEBUG - interface - Send special key: [<Key.BACKSPACE: '<backspace>'>]
RuntimeError
def text(self, new_content: str): Gdk.threads_enter() try: # This call might fail and raise an Exception. # If it does, make sure to release the mutex and not deadlock AutoKey. self._clipboard.set_text(new_content, -1) finally: Gdk.threads_leave()
def text(self, new_content: str): Gdk.threads_enter() self._clipboard.set_text(new_content, -1) Gdk.threads_leave()
https://github.com/autokey/autokey/issues/226
2018-12-05 07:02:31,958 DEBUG - service - Raw key: 'b', modifiers: [], Key: b 2018-12-05 07:02:31,958 DEBUG - service - Window visible title: '*Unbenannt 1 - Mousepad', Window class: 'mousepad.Mousepad' 2018-12-05 07:02:31,958 DEBUG - service - No phrase/script matched hotkey 2018-12-05 07:02:31,958 DEBUG - service - Input stack at end of handle_keypress: deque(['b'], maxlen=150) 2018-12-05 07:02:32,127 DEBUG - service - Raw key: ' ', modifiers: [], Key: 2018-12-05 07:02:32,128 DEBUG - service - Window visible title: '*Unbenannt 1 - Mousepad', Window class: 'mousepad.Mousepad' 2018-12-05 07:02:32,128 DEBUG - service - No phrase/script matched hotkey 2018-12-05 07:02:32,132 DEBUG - iomediator - Send via clipboard 2018-12-05 07:02:32,133 DEBUG - service - Input stack at end of handle_keypress: deque([], maxlen=150) 2018-12-05 07:02:32,133 DEBUG - interface - Sending string via clipboard: a 2018-12-05 07:02:32,133 ERROR - service - Ignored locking error in handle_keypress Traceback (most recent call last): File "/usr/lib/python3.7/site-packages/autokey/service.py", line 207, in __tryReleaseLock self.configManager.lock.release() RuntimeError: release unlocked lock 2018-12-05 07:02:32,135 DEBUG - interface - Sending via clipboard enqueued. 2018-12-05 07:02:32,135 DEBUG - interface - Send special key: [<Key.BACKSPACE: '<backspace>'>] 2018-12-05 07:02:32,137 DEBUG - interface - Send special key: [<Key.BACKSPACE: '<backspace>'>] 2018-12-05 07:02:32,139 DEBUG - iomediator - Send via event interface 2018-12-05 07:02:32,139 DEBUG - interface - Send modified key: modifiers: ['<shift>'] key: <insert> 2018-12-05 07:02:32,242 ERROR - interface - Error in X event loop thread Traceback (most recent call last): File "/usr/lib/python3.7/site-packages/autokey/interface.py", line 230, in __eventLoop method(*args) File "/usr/lib/python3.7/site-packages/autokey/interface.py", line 626, in _restore_clipboard_text self.clipboard.text = backup File "/usr/lib/python3.7/site-packages/autokey/interface.py", line 161, in text self._clipboard.set_text(new_content, -1) TypeError: Argument 1 does not allow None as a value 2018-12-05 07:02:33,039 DEBUG - service - Raw key: 'b', modifiers: [], Key: b 2018-12-05 07:02:33,040 DEBUG - service - Window visible title: '*Unbenannt 1 - Mousepad', Window class: 'mousepad.Mousepad' 2018-12-05 07:02:33,040 DEBUG - service - No phrase/script matched hotkey 2018-12-05 07:02:33,041 DEBUG - service - Input stack at end of handle_keypress: deque(['b'], maxlen=150) 2018-12-05 07:02:33,318 DEBUG - service - Raw key: ' ', modifiers: [], Key: 2018-12-05 07:02:33,319 DEBUG - service - Window visible title: '*Unbenannt 1 - Mousepad', Window class: 'mousepad.Mousepad' 2018-12-05 07:02:33,319 DEBUG - service - No phrase/script matched hotkey 2018-12-05 07:02:33,322 DEBUG - iomediator - Send via clipboard 2018-12-05 07:02:33,323 DEBUG - service - Input stack at end of handle_keypress: deque([], maxlen=150) 2018-12-05 07:02:33,325 DEBUG - interface - Sending string via clipboard: a 2018-12-05 07:02:33,327 ERROR - service - Ignored locking error in handle_keypress Traceback (most recent call last): File "/usr/lib/python3.7/site-packages/autokey/service.py", line 207, in __tryReleaseLock self.configManager.lock.release() RuntimeError: release unlocked lock 2018-12-05 07:02:33,328 DEBUG - interface - Sending via clipboard enqueued. 2018-12-05 07:02:33,329 DEBUG - interface - Send special key: [<Key.BACKSPACE: '<backspace>'>] 2018-12-05 07:02:33,333 DEBUG - interface - Send special key: [<Key.BACKSPACE: '<backspace>'>]
RuntimeError
def selection(self, new_content: str): Gdk.threads_enter() try: # This call might fail and raise an Exception. # If it does, make sure to release the mutex and not deadlock AutoKey. self._selection.set_text(new_content, -1) finally: Gdk.threads_leave()
def selection(self, new_content: str): Gdk.threads_enter() self._selection.set_text(new_content, -1) Gdk.threads_leave()
https://github.com/autokey/autokey/issues/226
2018-12-05 07:02:31,958 DEBUG - service - Raw key: 'b', modifiers: [], Key: b 2018-12-05 07:02:31,958 DEBUG - service - Window visible title: '*Unbenannt 1 - Mousepad', Window class: 'mousepad.Mousepad' 2018-12-05 07:02:31,958 DEBUG - service - No phrase/script matched hotkey 2018-12-05 07:02:31,958 DEBUG - service - Input stack at end of handle_keypress: deque(['b'], maxlen=150) 2018-12-05 07:02:32,127 DEBUG - service - Raw key: ' ', modifiers: [], Key: 2018-12-05 07:02:32,128 DEBUG - service - Window visible title: '*Unbenannt 1 - Mousepad', Window class: 'mousepad.Mousepad' 2018-12-05 07:02:32,128 DEBUG - service - No phrase/script matched hotkey 2018-12-05 07:02:32,132 DEBUG - iomediator - Send via clipboard 2018-12-05 07:02:32,133 DEBUG - service - Input stack at end of handle_keypress: deque([], maxlen=150) 2018-12-05 07:02:32,133 DEBUG - interface - Sending string via clipboard: a 2018-12-05 07:02:32,133 ERROR - service - Ignored locking error in handle_keypress Traceback (most recent call last): File "/usr/lib/python3.7/site-packages/autokey/service.py", line 207, in __tryReleaseLock self.configManager.lock.release() RuntimeError: release unlocked lock 2018-12-05 07:02:32,135 DEBUG - interface - Sending via clipboard enqueued. 2018-12-05 07:02:32,135 DEBUG - interface - Send special key: [<Key.BACKSPACE: '<backspace>'>] 2018-12-05 07:02:32,137 DEBUG - interface - Send special key: [<Key.BACKSPACE: '<backspace>'>] 2018-12-05 07:02:32,139 DEBUG - iomediator - Send via event interface 2018-12-05 07:02:32,139 DEBUG - interface - Send modified key: modifiers: ['<shift>'] key: <insert> 2018-12-05 07:02:32,242 ERROR - interface - Error in X event loop thread Traceback (most recent call last): File "/usr/lib/python3.7/site-packages/autokey/interface.py", line 230, in __eventLoop method(*args) File "/usr/lib/python3.7/site-packages/autokey/interface.py", line 626, in _restore_clipboard_text self.clipboard.text = backup File "/usr/lib/python3.7/site-packages/autokey/interface.py", line 161, in text self._clipboard.set_text(new_content, -1) TypeError: Argument 1 does not allow None as a value 2018-12-05 07:02:33,039 DEBUG - service - Raw key: 'b', modifiers: [], Key: b 2018-12-05 07:02:33,040 DEBUG - service - Window visible title: '*Unbenannt 1 - Mousepad', Window class: 'mousepad.Mousepad' 2018-12-05 07:02:33,040 DEBUG - service - No phrase/script matched hotkey 2018-12-05 07:02:33,041 DEBUG - service - Input stack at end of handle_keypress: deque(['b'], maxlen=150) 2018-12-05 07:02:33,318 DEBUG - service - Raw key: ' ', modifiers: [], Key: 2018-12-05 07:02:33,319 DEBUG - service - Window visible title: '*Unbenannt 1 - Mousepad', Window class: 'mousepad.Mousepad' 2018-12-05 07:02:33,319 DEBUG - service - No phrase/script matched hotkey 2018-12-05 07:02:33,322 DEBUG - iomediator - Send via clipboard 2018-12-05 07:02:33,323 DEBUG - service - Input stack at end of handle_keypress: deque([], maxlen=150) 2018-12-05 07:02:33,325 DEBUG - interface - Sending string via clipboard: a 2018-12-05 07:02:33,327 ERROR - service - Ignored locking error in handle_keypress Traceback (most recent call last): File "/usr/lib/python3.7/site-packages/autokey/service.py", line 207, in __tryReleaseLock self.configManager.lock.release() RuntimeError: release unlocked lock 2018-12-05 07:02:33,328 DEBUG - interface - Sending via clipboard enqueued. 2018-12-05 07:02:33,329 DEBUG - interface - Send special key: [<Key.BACKSPACE: '<backspace>'>] 2018-12-05 07:02:33,333 DEBUG - interface - Send special key: [<Key.BACKSPACE: '<backspace>'>]
RuntimeError
def __init__( self, *, output_filename: str, internal_only: bool, requirements: PexRequirements = PexRequirements(), interpreter_constraints=PexInterpreterConstraints(), platforms=PexPlatforms(), sources: Optional[Digest] = None, additional_inputs: Optional[Digest] = None, entry_point: Optional[str] = None, additional_args: Iterable[str] = (), description: Optional[str] = None, ) -> None: """A request to create a PEX from its inputs. :param output_filename: The name of the built Pex file, which typically should end in `.pex`. :param internal_only: Whether we ever materialize the Pex and distribute it directly to end users, such as with the `binary` goal. Typically, instead, the user never directly uses the Pex, e.g. with `lint` and `test`. If True, we will use a Pex setting that results in faster build time but compatibility with fewer interpreters at runtime. :param requirements: The requirements to install. :param interpreter_constraints: Any constraints on which Python versions may be used. :param platforms: Which platforms should be supported. Setting this value will cause interpreter constraints to not be used because platforms already constrain the valid Python versions, e.g. by including `cp36m` in the platform string. :param sources: Any source files that should be included in the Pex. :param additional_inputs: Any inputs that are not source files and should not be included directly in the Pex, but should be present in the environment when building the Pex. :param entry_point: The entry-point for the built Pex, equivalent to Pex's `-m` flag. If left off, the Pex will open up as a REPL. :param additional_args: Any additional Pex flags. :param description: A human-readable description to render in the dynamic UI when building the Pex. """ self.output_filename = output_filename self.internal_only = internal_only self.requirements = requirements self.interpreter_constraints = interpreter_constraints self.platforms = platforms self.sources = sources self.additional_inputs = additional_inputs self.entry_point = entry_point self.additional_args = tuple(additional_args) self.description = description self.__post_init__()
def __init__( self, *, output_filename: str, internal_only: bool, requirements: PexRequirements = PexRequirements(), interpreter_constraints=PexInterpreterConstraints(), platforms=PexPlatforms(), sources: Optional[Digest] = None, additional_inputs: Optional[Digest] = None, entry_point: Optional[str] = None, additional_args: Iterable[str] = (), description: Optional[str] = None, ) -> None: """A request to create a PEX from its inputs. :param output_filename: The name of the built Pex file, which typically should end in `.pex`. :param internal_only: Whether we ever materialize the Pex and distribute it directly to end users, such as with the `binary` goal. Typically, instead, the user never directly uses the Pex, e.g. with `lint` and `test`. If True, we will use a Pex setting that results in faster build time but compatibility with fewer interpreters at runtime. :param requirements: The requirements to install. :param interpreter_constraints: Any constraints on which Python versions may be used. :param platforms: Which platforms should be supported. Setting this value will cause interpreter constraints to not be used because platforms already constrain the valid Python versions, e.g. by including `cp36m` in the platform string. :param sources: Any source files that should be included in the Pex. :param additional_inputs: Any inputs that are not source files and should not be included directly in the Pex, but should be present in the environment when building the Pex. :param entry_point: The entry-point for the built Pex, equivalent to Pex's `-m` flag. If left off, the Pex will open up as a REPL. :param additional_args: Any additional Pex flags. :param description: A human-readable description to render in the dynamic UI when building the Pex. """ self.output_filename = output_filename self.internal_only = internal_only self.requirements = requirements self.interpreter_constraints = interpreter_constraints self.platforms = platforms self.sources = sources self.additional_inputs = additional_inputs self.entry_point = entry_point self.additional_args = tuple(additional_args) self.description = description
https://github.com/pantsbuild/pants/issues/10648
$ ./pants fmt src/python/pants:: Compiling engine v0.0.1 (XXX) Finished release [optimized + debuginfo] target(s) in 2m 49s 12:11:49 [INFO] initializing pantsd... 12:12:00 [INFO] pantsd initialized. 12:12:08.46 [INFO] Completed: Building black.pex with 2 requirements: black==19.10b0, setuptools 12:12:08 [WARN] /Users/tdyas/TC/pants/src/python/pants/base/exception_sink.py:359: DeprecationWarning: PY_SSIZE_T_CLEAN will be required for '#' formats process_title=setproctitle.getproctitle(), 12:12:08 [ERROR] 1 Exception encountered: Engine traceback: in select in `fmt` goal in pants.backend.python.lint.python_fmt.format_python_target in Format with Black in pants.engine.process.fallible_to_exec_result_or_raise Traceback (most recent call last): File "XXX/pants/src/python/pants/engine/process.py", line 229, in fallible_to_exec_result_or_raise raise ProcessExecutionFailure( pants.engine.process.ProcessExecutionFailure: Process 'Run Black on 413 files.' failed with exit code 127. stdout: stderr: env: python3.7: No such file or directory Traceback (most recent call last): File "XXX/pants/src/python/pants/bin/local_pants_runner.py", line 255, in run engine_result = self._run_v2() File "XXX/pants/src/python/pants/bin/local_pants_runner.py", line 166, in _run_v2 return self._maybe_run_v2_body(goals, poll=False) File "XXX/pants/src/python/pants/bin/local_pants_runner.py", line 183, in _maybe_run_v2_body return self.graph_session.run_goal_rules( File "XXX/pants/src/python/pants/init/engine_initializer.py", line 117, in run_goal_rules exit_code = self.scheduler_session.run_goal_rule( File "XXX/pants/src/python/pants/engine/internals/scheduler.py", line 552, in run_goal_rule self._raise_on_error([t for _, t in throws]) File "XXX/pants/src/python/pants/engine/internals/scheduler.py", line 511, in _raise_on_error raise ExecutionError( pants.engine.internals.scheduler.ExecutionError: 1 Exception encountered: Engine traceback: in select in `fmt` goal in pants.backend.python.lint.python_fmt.format_python_target in Format with Black in pants.engine.process.fallible_to_exec_result_or_raise Traceback (most recent call last): File "XXX/pants/src/python/pants/engine/process.py", line 229, in fallible_to_exec_result_or_raise raise ProcessExecutionFailure( pants.engine.process.ProcessExecutionFailure: Process 'Run Black on 413 files.' failed with exit code 127. stdout: stderr: env: python3.7: No such file or directory
pants.engine.internals.scheduler.ExecutionError
async def create_pex( request: PexRequest, python_setup: PythonSetup, python_repos: PythonRepos, platform: Platform, pex_runtime_environment: PexRuntimeEnvironment, ) -> Pex: """Returns a PEX with the given settings.""" argv = [ "--output-file", request.output_filename, # NB: In setting `--no-pypi`, we rely on the default value of `--python-repos-indexes` # including PyPI, which will override `--no-pypi` and result in using PyPI in the default # case. Why set `--no-pypi`, then? We need to do this so that # `--python-repos-repos=['custom_url']` will only point to that index and not include PyPI. "--no-pypi", *(f"--index={index}" for index in python_repos.indexes), *(f"--repo={repo}" for repo in python_repos.repos), *request.additional_args, ] python: Optional[PythonExecutable] = None # NB: If `--platform` is specified, this signals that the PEX should not be built locally. # `--interpreter-constraint` only makes sense in the context of building locally. These two # flags are mutually exclusive. See https://github.com/pantsbuild/pex/issues/957. if request.platforms: # TODO(#9560): consider validating that these platforms are valid with the interpreter # constraints. argv.extend(request.platforms.generate_pex_arg_list()) else: argv.extend(request.interpreter_constraints.generate_pex_arg_list()) # N.B: An internal-only PexRequest is validated to never have platforms set so we only need # perform interpreter lookup in this branch. if request.internal_only: python = await Get( PythonExecutable, PexInterpreterConstraints, request.interpreter_constraints, ) argv.append("--no-emit-warnings") verbosity = pex_runtime_environment.verbosity if verbosity > 0: argv.append(f"-{'v' * verbosity}") if python_setup.resolver_jobs: argv.extend(["--jobs", str(python_setup.resolver_jobs)]) if python_setup.manylinux: argv.extend(["--manylinux", python_setup.manylinux]) else: argv.append("--no-manylinux") if request.entry_point is not None: argv.extend(["--entry-point", request.entry_point]) if python_setup.requirement_constraints is not None: argv.extend(["--constraints", python_setup.requirement_constraints]) source_dir_name = "source_files" argv.append(f"--sources-directory={source_dir_name}") argv.extend(request.requirements) constraint_file_digest = EMPTY_DIGEST if python_setup.requirement_constraints is not None: constraint_file_digest = await Get( Digest, PathGlobs( [python_setup.requirement_constraints], glob_match_error_behavior=GlobMatchErrorBehavior.error, conjunction=GlobExpansionConjunction.all_match, description_of_origin="the option `--python-setup-requirement-constraints`", ), ) sources_digest_as_subdir = await Get( Digest, AddPrefix(request.sources or EMPTY_DIGEST, source_dir_name) ) additional_inputs_digest = request.additional_inputs or EMPTY_DIGEST merged_digest = await Get( Digest, MergeDigests( ( sources_digest_as_subdir, additional_inputs_digest, constraint_file_digest, ) ), ) description = request.description if description is None: if request.requirements: description = ( f"Building {request.output_filename} with " f"{pluralize(len(request.requirements), 'requirement')}: " f"{', '.join(request.requirements)}" ) else: description = f"Building {request.output_filename}" process = await Get( Process, PexCliProcess( python=python, argv=argv, additional_input_digest=merged_digest, description=description, output_files=[request.output_filename], ), ) # NB: Building a Pex is platform dependent, so in order to get a PEX that we can use locally # without cross-building, we specify that our PEX command should be run on the current local # platform. result = await Get( ProcessResult, MultiPlatformProcess( { ( PlatformConstraint(platform.value), PlatformConstraint(platform.value), ): process } ), ) if verbosity > 0: log_output = result.stderr.decode() if log_output: logger.info("%s", log_output) return Pex(digest=result.output_digest, name=request.output_filename, python=python)
async def create_pex( request: PexRequest, python_setup: PythonSetup, python_repos: PythonRepos, platform: Platform, pex_runtime_environment: PexRuntimeEnvironment, ) -> Pex: """Returns a PEX with the given settings.""" argv = [ "--output-file", request.output_filename, # NB: In setting `--no-pypi`, we rely on the default value of `--python-repos-indexes` # including PyPI, which will override `--no-pypi` and result in using PyPI in the default # case. Why set `--no-pypi`, then? We need to do this so that # `--python-repos-repos=['custom_url']` will only point to that index and not include PyPI. "--no-pypi", *(f"--index={index}" for index in python_repos.indexes), *(f"--repo={repo}" for repo in python_repos.repos), *request.additional_args, ] if request.internal_only: # This will result in a faster build, but worse compatibility at runtime. argv.append("--use-first-matching-interpreter") # NB: If `--platform` is specified, this signals that the PEX should not be built locally. # `--interpreter-constraint` only makes sense in the context of building locally. These two # flags are mutually exclusive. See https://github.com/pantsbuild/pex/issues/957. if request.platforms: # TODO(#9560): consider validating that these platforms are valid with the interpreter # constraints. argv.extend(request.platforms.generate_pex_arg_list()) else: argv.extend(request.interpreter_constraints.generate_pex_arg_list()) argv.append("--no-emit-warnings") verbosity = pex_runtime_environment.verbosity if verbosity > 0: argv.append(f"-{'v' * verbosity}") if python_setup.resolver_jobs: argv.extend(["--jobs", str(python_setup.resolver_jobs)]) if python_setup.manylinux: argv.extend(["--manylinux", python_setup.manylinux]) else: argv.append("--no-manylinux") if request.entry_point is not None: argv.extend(["--entry-point", request.entry_point]) if python_setup.requirement_constraints is not None: argv.extend(["--constraints", python_setup.requirement_constraints]) source_dir_name = "source_files" argv.append(f"--sources-directory={source_dir_name}") argv.extend(request.requirements) constraint_file_digest = EMPTY_DIGEST if python_setup.requirement_constraints is not None: constraint_file_digest = await Get( Digest, PathGlobs( [python_setup.requirement_constraints], glob_match_error_behavior=GlobMatchErrorBehavior.error, conjunction=GlobExpansionConjunction.all_match, description_of_origin="the option `--python-setup-requirement-constraints`", ), ) sources_digest_as_subdir = await Get( Digest, AddPrefix(request.sources or EMPTY_DIGEST, source_dir_name) ) additional_inputs_digest = request.additional_inputs or EMPTY_DIGEST merged_digest = await Get( Digest, MergeDigests( ( sources_digest_as_subdir, additional_inputs_digest, constraint_file_digest, ) ), ) description = request.description if description is None: if request.requirements: description = ( f"Building {request.output_filename} with " f"{pluralize(len(request.requirements), 'requirement')}: " f"{', '.join(request.requirements)}" ) else: description = f"Building {request.output_filename}" process = await Get( Process, PexCliProcess( argv=argv, additional_input_digest=merged_digest, description=description, output_files=[request.output_filename], ), ) # NB: Building a Pex is platform dependent, so in order to get a PEX that we can use locally # without cross-building, we specify that our PEX command should be run on the current local # platform. result = await Get( ProcessResult, MultiPlatformProcess( { ( PlatformConstraint(platform.value), PlatformConstraint(platform.value), ): process } ), ) if verbosity > 0: log_output = result.stderr.decode() if log_output: logger.info("%s", log_output) return Pex( digest=result.output_digest, name=request.output_filename, internal_only=request.internal_only, )
https://github.com/pantsbuild/pants/issues/10648
$ ./pants fmt src/python/pants:: Compiling engine v0.0.1 (XXX) Finished release [optimized + debuginfo] target(s) in 2m 49s 12:11:49 [INFO] initializing pantsd... 12:12:00 [INFO] pantsd initialized. 12:12:08.46 [INFO] Completed: Building black.pex with 2 requirements: black==19.10b0, setuptools 12:12:08 [WARN] /Users/tdyas/TC/pants/src/python/pants/base/exception_sink.py:359: DeprecationWarning: PY_SSIZE_T_CLEAN will be required for '#' formats process_title=setproctitle.getproctitle(), 12:12:08 [ERROR] 1 Exception encountered: Engine traceback: in select in `fmt` goal in pants.backend.python.lint.python_fmt.format_python_target in Format with Black in pants.engine.process.fallible_to_exec_result_or_raise Traceback (most recent call last): File "XXX/pants/src/python/pants/engine/process.py", line 229, in fallible_to_exec_result_or_raise raise ProcessExecutionFailure( pants.engine.process.ProcessExecutionFailure: Process 'Run Black on 413 files.' failed with exit code 127. stdout: stderr: env: python3.7: No such file or directory Traceback (most recent call last): File "XXX/pants/src/python/pants/bin/local_pants_runner.py", line 255, in run engine_result = self._run_v2() File "XXX/pants/src/python/pants/bin/local_pants_runner.py", line 166, in _run_v2 return self._maybe_run_v2_body(goals, poll=False) File "XXX/pants/src/python/pants/bin/local_pants_runner.py", line 183, in _maybe_run_v2_body return self.graph_session.run_goal_rules( File "XXX/pants/src/python/pants/init/engine_initializer.py", line 117, in run_goal_rules exit_code = self.scheduler_session.run_goal_rule( File "XXX/pants/src/python/pants/engine/internals/scheduler.py", line 552, in run_goal_rule self._raise_on_error([t for _, t in throws]) File "XXX/pants/src/python/pants/engine/internals/scheduler.py", line 511, in _raise_on_error raise ExecutionError( pants.engine.internals.scheduler.ExecutionError: 1 Exception encountered: Engine traceback: in select in `fmt` goal in pants.backend.python.lint.python_fmt.format_python_target in Format with Black in pants.engine.process.fallible_to_exec_result_or_raise Traceback (most recent call last): File "XXX/pants/src/python/pants/engine/process.py", line 229, in fallible_to_exec_result_or_raise raise ProcessExecutionFailure( pants.engine.process.ProcessExecutionFailure: Process 'Run Black on 413 files.' failed with exit code 127. stdout: stderr: env: python3.7: No such file or directory
pants.engine.internals.scheduler.ExecutionError
async def setup_pex_process( request: PexProcess, pex_environment: PexEnvironment ) -> Process: argv = pex_environment.create_argv( f"./{request.pex.name}", *request.argv, python=request.pex.python, ) env = {**pex_environment.environment_dict, **(request.extra_env or {})} process = Process( argv, description=request.description, level=request.level, input_digest=request.input_digest, env=env, output_files=request.output_files, output_directories=request.output_directories, timeout_seconds=request.timeout_seconds, execution_slot_variable=request.execution_slot_variable, ) return ( await Get(Process, UncacheableProcess(process)) if request.uncacheable else process )
async def setup_pex_process( request: PexProcess, pex_environment: PexEnvironment ) -> Process: argv = pex_environment.create_argv( f"./{request.pex.name}", *request.argv, # If the Pex isn't distributed to users, then we must use the shebang because we will have # used the flag `--use-first-matching-interpreter`, which requires running via shebang. always_use_shebang=request.pex.internal_only, ) env = {**pex_environment.environment_dict, **(request.extra_env or {})} process = Process( argv, description=request.description, level=request.level, input_digest=request.input_digest, env=env, output_files=request.output_files, output_directories=request.output_directories, timeout_seconds=request.timeout_seconds, execution_slot_variable=request.execution_slot_variable, ) return ( await Get(Process, UncacheableProcess(process)) if request.uncacheable else process )
https://github.com/pantsbuild/pants/issues/10648
$ ./pants fmt src/python/pants:: Compiling engine v0.0.1 (XXX) Finished release [optimized + debuginfo] target(s) in 2m 49s 12:11:49 [INFO] initializing pantsd... 12:12:00 [INFO] pantsd initialized. 12:12:08.46 [INFO] Completed: Building black.pex with 2 requirements: black==19.10b0, setuptools 12:12:08 [WARN] /Users/tdyas/TC/pants/src/python/pants/base/exception_sink.py:359: DeprecationWarning: PY_SSIZE_T_CLEAN will be required for '#' formats process_title=setproctitle.getproctitle(), 12:12:08 [ERROR] 1 Exception encountered: Engine traceback: in select in `fmt` goal in pants.backend.python.lint.python_fmt.format_python_target in Format with Black in pants.engine.process.fallible_to_exec_result_or_raise Traceback (most recent call last): File "XXX/pants/src/python/pants/engine/process.py", line 229, in fallible_to_exec_result_or_raise raise ProcessExecutionFailure( pants.engine.process.ProcessExecutionFailure: Process 'Run Black on 413 files.' failed with exit code 127. stdout: stderr: env: python3.7: No such file or directory Traceback (most recent call last): File "XXX/pants/src/python/pants/bin/local_pants_runner.py", line 255, in run engine_result = self._run_v2() File "XXX/pants/src/python/pants/bin/local_pants_runner.py", line 166, in _run_v2 return self._maybe_run_v2_body(goals, poll=False) File "XXX/pants/src/python/pants/bin/local_pants_runner.py", line 183, in _maybe_run_v2_body return self.graph_session.run_goal_rules( File "XXX/pants/src/python/pants/init/engine_initializer.py", line 117, in run_goal_rules exit_code = self.scheduler_session.run_goal_rule( File "XXX/pants/src/python/pants/engine/internals/scheduler.py", line 552, in run_goal_rule self._raise_on_error([t for _, t in throws]) File "XXX/pants/src/python/pants/engine/internals/scheduler.py", line 511, in _raise_on_error raise ExecutionError( pants.engine.internals.scheduler.ExecutionError: 1 Exception encountered: Engine traceback: in select in `fmt` goal in pants.backend.python.lint.python_fmt.format_python_target in Format with Black in pants.engine.process.fallible_to_exec_result_or_raise Traceback (most recent call last): File "XXX/pants/src/python/pants/engine/process.py", line 229, in fallible_to_exec_result_or_raise raise ProcessExecutionFailure( pants.engine.process.ProcessExecutionFailure: Process 'Run Black on 413 files.' failed with exit code 127. stdout: stderr: env: python3.7: No such file or directory
pants.engine.internals.scheduler.ExecutionError
def __init__( self, *, argv: Iterable[str], description: str, additional_input_digest: Optional[Digest] = None, extra_env: Optional[Mapping[str, str]] = None, output_files: Optional[Iterable[str]] = None, output_directories: Optional[Iterable[str]] = None, python: Optional[PythonExecutable] = None, ) -> None: self.argv = tuple(argv) self.description = description self.additional_input_digest = additional_input_digest self.extra_env = FrozenDict(extra_env) if extra_env else None self.output_files = tuple(output_files) if output_files else None self.output_directories = tuple(output_directories) if output_directories else None self.python = python self.__post_init__()
def __init__( self, *, argv: Iterable[str], description: str, additional_input_digest: Optional[Digest] = None, extra_env: Optional[Mapping[str, str]] = None, output_files: Optional[Iterable[str]] = None, output_directories: Optional[Iterable[str]] = None, ) -> None: self.argv = tuple(argv) self.description = description self.additional_input_digest = additional_input_digest self.extra_env = FrozenDict(extra_env) if extra_env else None self.output_files = tuple(output_files) if output_files else None self.output_directories = tuple(output_directories) if output_directories else None self.__post_init__()
https://github.com/pantsbuild/pants/issues/10648
$ ./pants fmt src/python/pants:: Compiling engine v0.0.1 (XXX) Finished release [optimized + debuginfo] target(s) in 2m 49s 12:11:49 [INFO] initializing pantsd... 12:12:00 [INFO] pantsd initialized. 12:12:08.46 [INFO] Completed: Building black.pex with 2 requirements: black==19.10b0, setuptools 12:12:08 [WARN] /Users/tdyas/TC/pants/src/python/pants/base/exception_sink.py:359: DeprecationWarning: PY_SSIZE_T_CLEAN will be required for '#' formats process_title=setproctitle.getproctitle(), 12:12:08 [ERROR] 1 Exception encountered: Engine traceback: in select in `fmt` goal in pants.backend.python.lint.python_fmt.format_python_target in Format with Black in pants.engine.process.fallible_to_exec_result_or_raise Traceback (most recent call last): File "XXX/pants/src/python/pants/engine/process.py", line 229, in fallible_to_exec_result_or_raise raise ProcessExecutionFailure( pants.engine.process.ProcessExecutionFailure: Process 'Run Black on 413 files.' failed with exit code 127. stdout: stderr: env: python3.7: No such file or directory Traceback (most recent call last): File "XXX/pants/src/python/pants/bin/local_pants_runner.py", line 255, in run engine_result = self._run_v2() File "XXX/pants/src/python/pants/bin/local_pants_runner.py", line 166, in _run_v2 return self._maybe_run_v2_body(goals, poll=False) File "XXX/pants/src/python/pants/bin/local_pants_runner.py", line 183, in _maybe_run_v2_body return self.graph_session.run_goal_rules( File "XXX/pants/src/python/pants/init/engine_initializer.py", line 117, in run_goal_rules exit_code = self.scheduler_session.run_goal_rule( File "XXX/pants/src/python/pants/engine/internals/scheduler.py", line 552, in run_goal_rule self._raise_on_error([t for _, t in throws]) File "XXX/pants/src/python/pants/engine/internals/scheduler.py", line 511, in _raise_on_error raise ExecutionError( pants.engine.internals.scheduler.ExecutionError: 1 Exception encountered: Engine traceback: in select in `fmt` goal in pants.backend.python.lint.python_fmt.format_python_target in Format with Black in pants.engine.process.fallible_to_exec_result_or_raise Traceback (most recent call last): File "XXX/pants/src/python/pants/engine/process.py", line 229, in fallible_to_exec_result_or_raise raise ProcessExecutionFailure( pants.engine.process.ProcessExecutionFailure: Process 'Run Black on 413 files.' failed with exit code 127. stdout: stderr: env: python3.7: No such file or directory
pants.engine.internals.scheduler.ExecutionError
async def setup_pex_cli_process( request: PexCliProcess, pex_binary: PexBinary, pex_env: PexEnvironment, python_native_code: PythonNativeCode, ) -> Process: tmpdir = ".tmp" downloaded_pex_bin, tmp_dir_digest = await MultiGet( Get( DownloadedExternalTool, ExternalToolRequest, pex_binary.get_request(Platform.current), ), # TODO(John Sirois): Use a Directory instead of this FileContent hack when a fix for # https://github.com/pantsbuild/pants/issues/9650 lands. Get(Digest, CreateDigest([FileContent(f"{tmpdir}/.reserve", b"")])), ) digests_to_merge = [downloaded_pex_bin.digest, tmp_dir_digest] if request.additional_input_digest: digests_to_merge.append(request.additional_input_digest) input_digest = await Get(Digest, MergeDigests(digests_to_merge)) pex_root_path = ".cache/pex_root" argv = pex_env.create_argv( downloaded_pex_bin.exe, *request.argv, "--pex-root", pex_root_path, python=request.python, ) env = { # Ensure Pex and its subprocesses create temporary files in the the process execution # sandbox. It may make sense to do this generally for Processes, but in the short term we # have known use cases where /tmp is too small to hold large wheel downloads Pex is asked to # perform. Making the TMPDIR local to the sandbox allows control via # --local-execution-root-dir for the local case and should work well with remote cases where # a remoting implementation has to allow for processes producing large binaries in a # sandbox to support reasonable workloads. "TMPDIR": tmpdir, **pex_env.environment_dict, **python_native_code.environment_dict, **(request.extra_env or {}), } return Process( argv, description=request.description, input_digest=input_digest, env=env, output_files=request.output_files, output_directories=request.output_directories, append_only_caches={"pex_root": pex_root_path}, )
async def setup_pex_cli_process( request: PexCliProcess, pex_binary: PexBinary, pex_env: PexEnvironment, python_native_code: PythonNativeCode, ) -> Process: tmpdir = ".tmp" downloaded_pex_bin, tmp_dir_digest = await MultiGet( Get( DownloadedExternalTool, ExternalToolRequest, pex_binary.get_request(Platform.current), ), # TODO(John Sirois): Use a Directory instead of this FileContent hack when a fix for # https://github.com/pantsbuild/pants/issues/9650 lands. Get(Digest, CreateDigest([FileContent(f"{tmpdir}/.reserve", b"")])), ) digests_to_merge = [downloaded_pex_bin.digest, tmp_dir_digest] if request.additional_input_digest: digests_to_merge.append(request.additional_input_digest) input_digest = await Get(Digest, MergeDigests(digests_to_merge)) pex_root_path = ".cache/pex_root" argv = pex_env.create_argv( downloaded_pex_bin.exe, *request.argv, "--pex-root", pex_root_path ) env = { # Ensure Pex and its subprocesses create temporary files in the the process execution # sandbox. It may make sense to do this generally for Processes, but in the short term we # have known use cases where /tmp is too small to hold large wheel downloads Pex is asked to # perform. Making the TMPDIR local to the sandbox allows control via # --local-execution-root-dir for the local case and should work well with remote cases where # a remoting implementation has to allow for processes producing large binaries in a # sandbox to support reasonable workloads. "TMPDIR": tmpdir, **pex_env.environment_dict, **python_native_code.environment_dict, **(request.extra_env or {}), } return Process( argv, description=request.description, input_digest=input_digest, env=env, output_files=request.output_files, output_directories=request.output_directories, append_only_caches={"pex_root": pex_root_path}, )
https://github.com/pantsbuild/pants/issues/10648
$ ./pants fmt src/python/pants:: Compiling engine v0.0.1 (XXX) Finished release [optimized + debuginfo] target(s) in 2m 49s 12:11:49 [INFO] initializing pantsd... 12:12:00 [INFO] pantsd initialized. 12:12:08.46 [INFO] Completed: Building black.pex with 2 requirements: black==19.10b0, setuptools 12:12:08 [WARN] /Users/tdyas/TC/pants/src/python/pants/base/exception_sink.py:359: DeprecationWarning: PY_SSIZE_T_CLEAN will be required for '#' formats process_title=setproctitle.getproctitle(), 12:12:08 [ERROR] 1 Exception encountered: Engine traceback: in select in `fmt` goal in pants.backend.python.lint.python_fmt.format_python_target in Format with Black in pants.engine.process.fallible_to_exec_result_or_raise Traceback (most recent call last): File "XXX/pants/src/python/pants/engine/process.py", line 229, in fallible_to_exec_result_or_raise raise ProcessExecutionFailure( pants.engine.process.ProcessExecutionFailure: Process 'Run Black on 413 files.' failed with exit code 127. stdout: stderr: env: python3.7: No such file or directory Traceback (most recent call last): File "XXX/pants/src/python/pants/bin/local_pants_runner.py", line 255, in run engine_result = self._run_v2() File "XXX/pants/src/python/pants/bin/local_pants_runner.py", line 166, in _run_v2 return self._maybe_run_v2_body(goals, poll=False) File "XXX/pants/src/python/pants/bin/local_pants_runner.py", line 183, in _maybe_run_v2_body return self.graph_session.run_goal_rules( File "XXX/pants/src/python/pants/init/engine_initializer.py", line 117, in run_goal_rules exit_code = self.scheduler_session.run_goal_rule( File "XXX/pants/src/python/pants/engine/internals/scheduler.py", line 552, in run_goal_rule self._raise_on_error([t for _, t in throws]) File "XXX/pants/src/python/pants/engine/internals/scheduler.py", line 511, in _raise_on_error raise ExecutionError( pants.engine.internals.scheduler.ExecutionError: 1 Exception encountered: Engine traceback: in select in `fmt` goal in pants.backend.python.lint.python_fmt.format_python_target in Format with Black in pants.engine.process.fallible_to_exec_result_or_raise Traceback (most recent call last): File "XXX/pants/src/python/pants/engine/process.py", line 229, in fallible_to_exec_result_or_raise raise ProcessExecutionFailure( pants.engine.process.ProcessExecutionFailure: Process 'Run Black on 413 files.' failed with exit code 127. stdout: stderr: env: python3.7: No such file or directory
pants.engine.internals.scheduler.ExecutionError
def create_argv( self, pex_path: str, *args: str, python: Optional[PythonExecutable] = None ) -> Iterable[str]: python = python or self.bootstrap_python argv = [python.path] if python else [] argv.extend((pex_path, *args)) return argv
def create_argv( self, pex_path: str, *args: str, always_use_shebang: bool = False ) -> Iterable[str]: argv = ( [self.bootstrap_python] if self.bootstrap_python and not always_use_shebang else [] ) argv.extend((pex_path, *args)) return argv
https://github.com/pantsbuild/pants/issues/10648
$ ./pants fmt src/python/pants:: Compiling engine v0.0.1 (XXX) Finished release [optimized + debuginfo] target(s) in 2m 49s 12:11:49 [INFO] initializing pantsd... 12:12:00 [INFO] pantsd initialized. 12:12:08.46 [INFO] Completed: Building black.pex with 2 requirements: black==19.10b0, setuptools 12:12:08 [WARN] /Users/tdyas/TC/pants/src/python/pants/base/exception_sink.py:359: DeprecationWarning: PY_SSIZE_T_CLEAN will be required for '#' formats process_title=setproctitle.getproctitle(), 12:12:08 [ERROR] 1 Exception encountered: Engine traceback: in select in `fmt` goal in pants.backend.python.lint.python_fmt.format_python_target in Format with Black in pants.engine.process.fallible_to_exec_result_or_raise Traceback (most recent call last): File "XXX/pants/src/python/pants/engine/process.py", line 229, in fallible_to_exec_result_or_raise raise ProcessExecutionFailure( pants.engine.process.ProcessExecutionFailure: Process 'Run Black on 413 files.' failed with exit code 127. stdout: stderr: env: python3.7: No such file or directory Traceback (most recent call last): File "XXX/pants/src/python/pants/bin/local_pants_runner.py", line 255, in run engine_result = self._run_v2() File "XXX/pants/src/python/pants/bin/local_pants_runner.py", line 166, in _run_v2 return self._maybe_run_v2_body(goals, poll=False) File "XXX/pants/src/python/pants/bin/local_pants_runner.py", line 183, in _maybe_run_v2_body return self.graph_session.run_goal_rules( File "XXX/pants/src/python/pants/init/engine_initializer.py", line 117, in run_goal_rules exit_code = self.scheduler_session.run_goal_rule( File "XXX/pants/src/python/pants/engine/internals/scheduler.py", line 552, in run_goal_rule self._raise_on_error([t for _, t in throws]) File "XXX/pants/src/python/pants/engine/internals/scheduler.py", line 511, in _raise_on_error raise ExecutionError( pants.engine.internals.scheduler.ExecutionError: 1 Exception encountered: Engine traceback: in select in `fmt` goal in pants.backend.python.lint.python_fmt.format_python_target in Format with Black in pants.engine.process.fallible_to_exec_result_or_raise Traceback (most recent call last): File "XXX/pants/src/python/pants/engine/process.py", line 229, in fallible_to_exec_result_or_raise raise ProcessExecutionFailure( pants.engine.process.ProcessExecutionFailure: Process 'Run Black on 413 files.' failed with exit code 127. stdout: stderr: env: python3.7: No such file or directory
pants.engine.internals.scheduler.ExecutionError
async def find_pex_python( python_setup: PythonSetup, pex_runtime_env: PexRuntimeEnvironment, subprocess_env_vars: SubprocessEnvironmentVars, ) -> PexEnvironment: # PEX files are compatible with bootstrapping via Python 2.7 or Python 3.5+. The bootstrap # code will then re-exec itself if the underlying PEX user code needs a more specific python # interpreter. As such, we look for many Pythons usable by the PEX bootstrap code here for # maximum flexibility. all_python_binary_paths = await MultiGet( Get( BinaryPaths, BinaryPathRequest( search_path=python_setup.interpreter_search_paths, binary_name=binary_name, test=BinaryPathTest( args=[ "-c", # N.B.: The following code snippet must be compatible with Python 2.7 and # Python 3.5+. dedent( """\ import sys major, minor = sys.version_info[:2] if (major, minor) == (2, 7) or (major == 3 and minor >= 5): # Here we hash the underlying python interpreter executable to # ensure we detect changes in the real interpreter that might # otherwise be masked by pyenv shim scripts found on the search # path. Naively, just printing out the full version_info would be # enough, but that does not account for supported abi changes (e.g.: # a pyenv switch from a py27mu interpreter to a py27m interpreter. import hashlib hasher = hashlib.sha256() with open(sys.executable, "rb") as fp: # We pick 8192 for efficiency of reads and fingerprint updates # (writes) since it's a common OS buffer size and an even # multiple of the hash block size. for chunk in iter(lambda: fp.read(8192), b""): hasher.update(chunk) sys.stdout.write(hasher.hexdigest()) sys.exit(0) else: sys.exit(1) """ ), ], fingerprint_stdout=False, # We already emit a usable fingerprint to stdout. ), ), ) for binary_name in pex_runtime_env.bootstrap_interpreter_names ) def first_python_binary() -> Optional[PythonExecutable]: for binary_paths in all_python_binary_paths: if binary_paths.first_path: return PythonExecutable( path=binary_paths.first_path.path, fingerprint=binary_paths.first_path.fingerprint, ) return None return PexEnvironment( path=pex_runtime_env.path, interpreter_search_paths=tuple(python_setup.interpreter_search_paths), subprocess_environment_dict=subprocess_env_vars.vars, bootstrap_python=first_python_binary(), )
async def find_pex_python( python_setup: PythonSetup, pex_runtime_env: PexRuntimeEnvironment, subprocess_env_vars: SubprocessEnvironmentVars, ) -> PexEnvironment: # PEX files are compatible with bootstrapping via Python 2.7 or Python 3.5+. The bootstrap # code will then re-exec itself if the underlying PEX user code needs a more specific python # interpreter. As such, we look for many Pythons usable by the PEX bootstrap code here for # maximum flexibility. all_python_binary_paths = await MultiGet( [ Get( BinaryPaths, BinaryPathRequest( search_path=python_setup.interpreter_search_paths, binary_name=binary_name, test_args=[ "-c", # N.B.: The following code snippet must be compatible with Python 2.7 and # Python 3.5+. dedent( """\ import sys major, minor = sys.version_info[:2] if (major, minor) == (2, 7) or (major == 3 and minor >= 5): # Here we hash the underlying python interpreter executable to # ensure we detect changes in the real interpreter that might # otherwise be masked by pyenv shim scripts found on the search # path. Naively, just printing out the full version_info would be # enough, but that does not account for supported abi changes (e.g.: # a pyenv switch from a py27mu interpreter to a py27m interpreter. import hashlib hasher = hashlib.sha256() with open(sys.executable, "rb") as fp: # We pick 8192 for efficiency of reads and fingerprint updates # (writes) since it's a common OS buffer size and an even # multiple of the hash block size. for chunk in iter(lambda: fp.read(8192), b""): hasher.update(chunk) sys.stdout.write(hasher.hexdigest()) sys.exit(0) else: sys.exit(1) """ ), ], ), ) for binary_name in pex_runtime_env.bootstrap_interpreter_names ] ) def first_python_binary() -> Optional[str]: for binary_paths in all_python_binary_paths: if binary_paths.first_path: return binary_paths.first_path.path return None return PexEnvironment( path=pex_runtime_env.path, interpreter_search_paths=tuple(python_setup.interpreter_search_paths), subprocess_environment_dict=subprocess_env_vars.vars, bootstrap_python=first_python_binary(), )
https://github.com/pantsbuild/pants/issues/10648
$ ./pants fmt src/python/pants:: Compiling engine v0.0.1 (XXX) Finished release [optimized + debuginfo] target(s) in 2m 49s 12:11:49 [INFO] initializing pantsd... 12:12:00 [INFO] pantsd initialized. 12:12:08.46 [INFO] Completed: Building black.pex with 2 requirements: black==19.10b0, setuptools 12:12:08 [WARN] /Users/tdyas/TC/pants/src/python/pants/base/exception_sink.py:359: DeprecationWarning: PY_SSIZE_T_CLEAN will be required for '#' formats process_title=setproctitle.getproctitle(), 12:12:08 [ERROR] 1 Exception encountered: Engine traceback: in select in `fmt` goal in pants.backend.python.lint.python_fmt.format_python_target in Format with Black in pants.engine.process.fallible_to_exec_result_or_raise Traceback (most recent call last): File "XXX/pants/src/python/pants/engine/process.py", line 229, in fallible_to_exec_result_or_raise raise ProcessExecutionFailure( pants.engine.process.ProcessExecutionFailure: Process 'Run Black on 413 files.' failed with exit code 127. stdout: stderr: env: python3.7: No such file or directory Traceback (most recent call last): File "XXX/pants/src/python/pants/bin/local_pants_runner.py", line 255, in run engine_result = self._run_v2() File "XXX/pants/src/python/pants/bin/local_pants_runner.py", line 166, in _run_v2 return self._maybe_run_v2_body(goals, poll=False) File "XXX/pants/src/python/pants/bin/local_pants_runner.py", line 183, in _maybe_run_v2_body return self.graph_session.run_goal_rules( File "XXX/pants/src/python/pants/init/engine_initializer.py", line 117, in run_goal_rules exit_code = self.scheduler_session.run_goal_rule( File "XXX/pants/src/python/pants/engine/internals/scheduler.py", line 552, in run_goal_rule self._raise_on_error([t for _, t in throws]) File "XXX/pants/src/python/pants/engine/internals/scheduler.py", line 511, in _raise_on_error raise ExecutionError( pants.engine.internals.scheduler.ExecutionError: 1 Exception encountered: Engine traceback: in select in `fmt` goal in pants.backend.python.lint.python_fmt.format_python_target in Format with Black in pants.engine.process.fallible_to_exec_result_or_raise Traceback (most recent call last): File "XXX/pants/src/python/pants/engine/process.py", line 229, in fallible_to_exec_result_or_raise raise ProcessExecutionFailure( pants.engine.process.ProcessExecutionFailure: Process 'Run Black on 413 files.' failed with exit code 127. stdout: stderr: env: python3.7: No such file or directory
pants.engine.internals.scheduler.ExecutionError
def first_python_binary() -> Optional[PythonExecutable]: for binary_paths in all_python_binary_paths: if binary_paths.first_path: return PythonExecutable( path=binary_paths.first_path.path, fingerprint=binary_paths.first_path.fingerprint, ) return None
def first_python_binary() -> Optional[str]: for binary_paths in all_python_binary_paths: if binary_paths.first_path: return binary_paths.first_path.path return None
https://github.com/pantsbuild/pants/issues/10648
$ ./pants fmt src/python/pants:: Compiling engine v0.0.1 (XXX) Finished release [optimized + debuginfo] target(s) in 2m 49s 12:11:49 [INFO] initializing pantsd... 12:12:00 [INFO] pantsd initialized. 12:12:08.46 [INFO] Completed: Building black.pex with 2 requirements: black==19.10b0, setuptools 12:12:08 [WARN] /Users/tdyas/TC/pants/src/python/pants/base/exception_sink.py:359: DeprecationWarning: PY_SSIZE_T_CLEAN will be required for '#' formats process_title=setproctitle.getproctitle(), 12:12:08 [ERROR] 1 Exception encountered: Engine traceback: in select in `fmt` goal in pants.backend.python.lint.python_fmt.format_python_target in Format with Black in pants.engine.process.fallible_to_exec_result_or_raise Traceback (most recent call last): File "XXX/pants/src/python/pants/engine/process.py", line 229, in fallible_to_exec_result_or_raise raise ProcessExecutionFailure( pants.engine.process.ProcessExecutionFailure: Process 'Run Black on 413 files.' failed with exit code 127. stdout: stderr: env: python3.7: No such file or directory Traceback (most recent call last): File "XXX/pants/src/python/pants/bin/local_pants_runner.py", line 255, in run engine_result = self._run_v2() File "XXX/pants/src/python/pants/bin/local_pants_runner.py", line 166, in _run_v2 return self._maybe_run_v2_body(goals, poll=False) File "XXX/pants/src/python/pants/bin/local_pants_runner.py", line 183, in _maybe_run_v2_body return self.graph_session.run_goal_rules( File "XXX/pants/src/python/pants/init/engine_initializer.py", line 117, in run_goal_rules exit_code = self.scheduler_session.run_goal_rule( File "XXX/pants/src/python/pants/engine/internals/scheduler.py", line 552, in run_goal_rule self._raise_on_error([t for _, t in throws]) File "XXX/pants/src/python/pants/engine/internals/scheduler.py", line 511, in _raise_on_error raise ExecutionError( pants.engine.internals.scheduler.ExecutionError: 1 Exception encountered: Engine traceback: in select in `fmt` goal in pants.backend.python.lint.python_fmt.format_python_target in Format with Black in pants.engine.process.fallible_to_exec_result_or_raise Traceback (most recent call last): File "XXX/pants/src/python/pants/engine/process.py", line 229, in fallible_to_exec_result_or_raise raise ProcessExecutionFailure( pants.engine.process.ProcessExecutionFailure: Process 'Run Black on 413 files.' failed with exit code 127. stdout: stderr: env: python3.7: No such file or directory
pants.engine.internals.scheduler.ExecutionError
def __init__( self, *, search_path: Iterable[str], binary_name: str, test: Optional[BinaryPathTest] = None, ) -> None: self.search_path = tuple(OrderedSet(search_path)) self.binary_name = binary_name self.test = test
def __init__( self, *, search_path: Iterable[str], binary_name: str, test_args: Optional[Iterable[str]] = None, ) -> None: self.search_path = tuple(OrderedSet(search_path)) self.binary_name = binary_name self.test_args = tuple(test_args or ())
https://github.com/pantsbuild/pants/issues/10648
$ ./pants fmt src/python/pants:: Compiling engine v0.0.1 (XXX) Finished release [optimized + debuginfo] target(s) in 2m 49s 12:11:49 [INFO] initializing pantsd... 12:12:00 [INFO] pantsd initialized. 12:12:08.46 [INFO] Completed: Building black.pex with 2 requirements: black==19.10b0, setuptools 12:12:08 [WARN] /Users/tdyas/TC/pants/src/python/pants/base/exception_sink.py:359: DeprecationWarning: PY_SSIZE_T_CLEAN will be required for '#' formats process_title=setproctitle.getproctitle(), 12:12:08 [ERROR] 1 Exception encountered: Engine traceback: in select in `fmt` goal in pants.backend.python.lint.python_fmt.format_python_target in Format with Black in pants.engine.process.fallible_to_exec_result_or_raise Traceback (most recent call last): File "XXX/pants/src/python/pants/engine/process.py", line 229, in fallible_to_exec_result_or_raise raise ProcessExecutionFailure( pants.engine.process.ProcessExecutionFailure: Process 'Run Black on 413 files.' failed with exit code 127. stdout: stderr: env: python3.7: No such file or directory Traceback (most recent call last): File "XXX/pants/src/python/pants/bin/local_pants_runner.py", line 255, in run engine_result = self._run_v2() File "XXX/pants/src/python/pants/bin/local_pants_runner.py", line 166, in _run_v2 return self._maybe_run_v2_body(goals, poll=False) File "XXX/pants/src/python/pants/bin/local_pants_runner.py", line 183, in _maybe_run_v2_body return self.graph_session.run_goal_rules( File "XXX/pants/src/python/pants/init/engine_initializer.py", line 117, in run_goal_rules exit_code = self.scheduler_session.run_goal_rule( File "XXX/pants/src/python/pants/engine/internals/scheduler.py", line 552, in run_goal_rule self._raise_on_error([t for _, t in throws]) File "XXX/pants/src/python/pants/engine/internals/scheduler.py", line 511, in _raise_on_error raise ExecutionError( pants.engine.internals.scheduler.ExecutionError: 1 Exception encountered: Engine traceback: in select in `fmt` goal in pants.backend.python.lint.python_fmt.format_python_target in Format with Black in pants.engine.process.fallible_to_exec_result_or_raise Traceback (most recent call last): File "XXX/pants/src/python/pants/engine/process.py", line 229, in fallible_to_exec_result_or_raise raise ProcessExecutionFailure( pants.engine.process.ProcessExecutionFailure: Process 'Run Black on 413 files.' failed with exit code 127. stdout: stderr: env: python3.7: No such file or directory
pants.engine.internals.scheduler.ExecutionError
async def make_process_uncacheable(uncacheable_process: UncacheableProcess) -> Process: uuid = await Get( UUID, UUIDRequest, UUIDRequest.scoped(cast(UUIDScope, uncacheable_process.scope.value)), ) process = uncacheable_process.process env = dict(process.env) # This is a slightly hacky way to force the process to run: since the env var # value is unique, this input combination will never have been seen before, # and therefore never cached. The two downsides are: # 1. This leaks into the process' environment, albeit with a funky var name that is # unlikely to cause problems in practice. # 2. This run will be cached even though it can never be re-used. # TODO: A more principled way of forcing rules to run? env["__PANTS_FORCE_PROCESS_RUN__"] = str(uuid) return dataclasses.replace(process, env=FrozenDict(env))
async def make_process_uncacheable(uncacheable_process: UncacheableProcess) -> Process: uuid = await Get(UUID, UUIDRequest()) process = uncacheable_process.process env = dict(process.env) # This is a slightly hacky way to force the process to run: since the env var # value is unique, this input combination will never have been seen before, # and therefore never cached. The two downsides are: # 1. This leaks into the process' environment, albeit with a funky var name that is # unlikely to cause problems in practice. # 2. This run will be cached even though it can never be re-used. # TODO: A more principled way of forcing rules to run? env["__PANTS_FORCE_PROCESS_RUN__"] = str(uuid) return dataclasses.replace(process, env=FrozenDict(env))
https://github.com/pantsbuild/pants/issues/10648
$ ./pants fmt src/python/pants:: Compiling engine v0.0.1 (XXX) Finished release [optimized + debuginfo] target(s) in 2m 49s 12:11:49 [INFO] initializing pantsd... 12:12:00 [INFO] pantsd initialized. 12:12:08.46 [INFO] Completed: Building black.pex with 2 requirements: black==19.10b0, setuptools 12:12:08 [WARN] /Users/tdyas/TC/pants/src/python/pants/base/exception_sink.py:359: DeprecationWarning: PY_SSIZE_T_CLEAN will be required for '#' formats process_title=setproctitle.getproctitle(), 12:12:08 [ERROR] 1 Exception encountered: Engine traceback: in select in `fmt` goal in pants.backend.python.lint.python_fmt.format_python_target in Format with Black in pants.engine.process.fallible_to_exec_result_or_raise Traceback (most recent call last): File "XXX/pants/src/python/pants/engine/process.py", line 229, in fallible_to_exec_result_or_raise raise ProcessExecutionFailure( pants.engine.process.ProcessExecutionFailure: Process 'Run Black on 413 files.' failed with exit code 127. stdout: stderr: env: python3.7: No such file or directory Traceback (most recent call last): File "XXX/pants/src/python/pants/bin/local_pants_runner.py", line 255, in run engine_result = self._run_v2() File "XXX/pants/src/python/pants/bin/local_pants_runner.py", line 166, in _run_v2 return self._maybe_run_v2_body(goals, poll=False) File "XXX/pants/src/python/pants/bin/local_pants_runner.py", line 183, in _maybe_run_v2_body return self.graph_session.run_goal_rules( File "XXX/pants/src/python/pants/init/engine_initializer.py", line 117, in run_goal_rules exit_code = self.scheduler_session.run_goal_rule( File "XXX/pants/src/python/pants/engine/internals/scheduler.py", line 552, in run_goal_rule self._raise_on_error([t for _, t in throws]) File "XXX/pants/src/python/pants/engine/internals/scheduler.py", line 511, in _raise_on_error raise ExecutionError( pants.engine.internals.scheduler.ExecutionError: 1 Exception encountered: Engine traceback: in select in `fmt` goal in pants.backend.python.lint.python_fmt.format_python_target in Format with Black in pants.engine.process.fallible_to_exec_result_or_raise Traceback (most recent call last): File "XXX/pants/src/python/pants/engine/process.py", line 229, in fallible_to_exec_result_or_raise raise ProcessExecutionFailure( pants.engine.process.ProcessExecutionFailure: Process 'Run Black on 413 files.' failed with exit code 127. stdout: stderr: env: python3.7: No such file or directory
pants.engine.internals.scheduler.ExecutionError
async def find_binary(request: BinaryPathRequest) -> BinaryPaths: # TODO(John Sirois): Replace this script with a statically linked native binary so we don't # depend on either /bin/bash being available on the Process host. # Note: the backslash after the """ marker ensures that the shebang is at the start of the # script file. Many OSs will not see the shebang if there is intervening whitespace. script_path = "./script.sh" script_content = dedent( """\ #!/usr/bin/env bash set -euo pipefail if command -v which > /dev/null; then command which -a $1 else command -v $1 fi """ ) script_digest = await Get( Digest, CreateDigest( [FileContent(script_path, script_content.encode(), is_executable=True)] ), ) search_path = create_path_env_var(request.search_path) result = await Get( FallibleProcessResult, # We use a volatile process to force re-run since any binary found on the host system today # could be gone tomorrow. Ideally we'd only do this for local processes since all known # remoting configurations include a static container image as part of their cache key which # automatically avoids this problem. UncacheableProcess( Process( description=f"Searching for `{request.binary_name}` on PATH={search_path}", level=LogLevel.DEBUG, input_digest=script_digest, argv=[script_path, request.binary_name], env={"PATH": search_path}, ), scope=ProcessScope.PER_SESSION, ), ) binary_paths = BinaryPaths(binary_name=request.binary_name) if result.exit_code != 0: return binary_paths found_paths = result.stdout.decode().splitlines() if not request.test: return dataclasses.replace( binary_paths, paths=[BinaryPath(path) for path in found_paths] ) results = await MultiGet( Get( FallibleProcessResult, UncacheableProcess( Process( description=f"Test binary {path}.", level=LogLevel.DEBUG, argv=[path, *request.test.args], ), scope=ProcessScope.PER_SESSION, ), ) for path in found_paths ) return dataclasses.replace( binary_paths, paths=[ BinaryPath.fingerprinted(path, result.stdout) if request.test.fingerprint_stdout else BinaryPath(path, result.stdout.decode()) for path, result in zip(found_paths, results) if result.exit_code == 0 ], )
async def find_binary(request: BinaryPathRequest) -> BinaryPaths: # TODO(John Sirois): Replace this script with a statically linked native binary so we don't # depend on either /bin/bash being available on the Process host. # Note: the backslash after the """ marker ensures that the shebang is at the start of the # script file. Many OSs will not see the shebang if there is intervening whitespace. script_path = "./script.sh" script_content = dedent( """\ #!/usr/bin/env bash set -euo pipefail if command -v which > /dev/null; then command which -a $1 else command -v $1 fi """ ) script_digest = await Get( Digest, CreateDigest( [FileContent(script_path, script_content.encode(), is_executable=True)] ), ) search_path = create_path_env_var(request.search_path) result = await Get( FallibleProcessResult, # We use a volatile process to force re-run since any binary found on the host system today # could be gone tomorrow. Ideally we'd only do this for local processes since all known # remoting configurations include a static container image as part of their cache key which # automatically avoids this problem. UncacheableProcess( Process( description=f"Searching for `{request.binary_name}` on PATH={search_path}", level=LogLevel.DEBUG, input_digest=script_digest, argv=[script_path, request.binary_name], env={"PATH": search_path}, ) ), ) binary_paths = BinaryPaths(binary_name=request.binary_name) if result.exit_code != 0: return binary_paths found_paths = result.stdout.decode().splitlines() if not request.test_args: return dataclasses.replace( binary_paths, paths=[BinaryPath(path) for path in found_paths] ) results = await MultiGet( Get( FallibleProcessResult, UncacheableProcess( Process( description=f"Test binary {path}.", level=LogLevel.DEBUG, argv=[path, *request.test_args], ) ), ) for path in found_paths ) return dataclasses.replace( binary_paths, paths=[ BinaryPath.fingerprinted(path, result.stdout) for path, result in zip(found_paths, results) if result.exit_code == 0 ], )
https://github.com/pantsbuild/pants/issues/10648
$ ./pants fmt src/python/pants:: Compiling engine v0.0.1 (XXX) Finished release [optimized + debuginfo] target(s) in 2m 49s 12:11:49 [INFO] initializing pantsd... 12:12:00 [INFO] pantsd initialized. 12:12:08.46 [INFO] Completed: Building black.pex with 2 requirements: black==19.10b0, setuptools 12:12:08 [WARN] /Users/tdyas/TC/pants/src/python/pants/base/exception_sink.py:359: DeprecationWarning: PY_SSIZE_T_CLEAN will be required for '#' formats process_title=setproctitle.getproctitle(), 12:12:08 [ERROR] 1 Exception encountered: Engine traceback: in select in `fmt` goal in pants.backend.python.lint.python_fmt.format_python_target in Format with Black in pants.engine.process.fallible_to_exec_result_or_raise Traceback (most recent call last): File "XXX/pants/src/python/pants/engine/process.py", line 229, in fallible_to_exec_result_or_raise raise ProcessExecutionFailure( pants.engine.process.ProcessExecutionFailure: Process 'Run Black on 413 files.' failed with exit code 127. stdout: stderr: env: python3.7: No such file or directory Traceback (most recent call last): File "XXX/pants/src/python/pants/bin/local_pants_runner.py", line 255, in run engine_result = self._run_v2() File "XXX/pants/src/python/pants/bin/local_pants_runner.py", line 166, in _run_v2 return self._maybe_run_v2_body(goals, poll=False) File "XXX/pants/src/python/pants/bin/local_pants_runner.py", line 183, in _maybe_run_v2_body return self.graph_session.run_goal_rules( File "XXX/pants/src/python/pants/init/engine_initializer.py", line 117, in run_goal_rules exit_code = self.scheduler_session.run_goal_rule( File "XXX/pants/src/python/pants/engine/internals/scheduler.py", line 552, in run_goal_rule self._raise_on_error([t for _, t in throws]) File "XXX/pants/src/python/pants/engine/internals/scheduler.py", line 511, in _raise_on_error raise ExecutionError( pants.engine.internals.scheduler.ExecutionError: 1 Exception encountered: Engine traceback: in select in `fmt` goal in pants.backend.python.lint.python_fmt.format_python_target in Format with Black in pants.engine.process.fallible_to_exec_result_or_raise Traceback (most recent call last): File "XXX/pants/src/python/pants/engine/process.py", line 229, in fallible_to_exec_result_or_raise raise ProcessExecutionFailure( pants.engine.process.ProcessExecutionFailure: Process 'Run Black on 413 files.' failed with exit code 127. stdout: stderr: env: python3.7: No such file or directory
pants.engine.internals.scheduler.ExecutionError
def garbage_collect_store(self, target_size_bytes: int) -> None: self._native.lib.garbage_collect_store(self._scheduler, target_size_bytes)
def garbage_collect_store(self): self._native.lib.garbage_collect_store(self._scheduler)
https://github.com/pantsbuild/pants/issues/10719
18:08:49.83 [WARN] <unknown>:882: DeprecationWarning: invalid escape sequence \d 18:08:52.21 [WARN] Completed: Find PEX Python - No bootstrap Python executable could be found from the option `interpreter_search_paths` in the `[python-setup]` scope. Will attempt to run PEXes directly. 18:08:53.11 [WARN] /data/home/asher/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0a1_py38/lib/python3.8/site-packages/pants/base/exception_sink.py:359: DeprecationWarning: PY_SSIZE_T_CLEAN will be required for '#' formats process_title=setproctitle.getproctitle(), 18:08:53.11 [ERROR] 1 Exception encountered: Engine traceback: in select in `binary` goal in pants.backend.python.rules.create_python_binary.create_python_binary in pants.backend.python.rules.pex.two_step_create_pex in pants.backend.python.rules.pex.create_pex Traceback (no traceback): <pants native internals> Exception: String("Digest Digest(Fingerprint<97adba2ad1bfef3ba1b37d6b119e15498ed2a60392241b5ea7c28c602826dd6c>, 97) did not exist in the Store.") Traceback (most recent call last): File "/data/home/asher/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0a1_py38/lib/python3.8/site-packages/pants/bin/local_pants_runner.py", line 255, in run engine_result = self._run_v2() File "/data/home/asher/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0a1_py38/lib/python3.8/site-packages/pants/bin/local_pants_runner.py", line 166, in _run_v2 return self._maybe_run_v2_body(goals, poll=False) File "/data/home/asher/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0a1_py38/lib/python3.8/site-packages/pants/bin/local_pants_runner.py", line 183, in _maybe_run_v2_body return self.graph_session.run_goal_rules( File "/data/home/asher/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0a1_py38/lib/python3.8/site-packages/pants/init/engine_initializer.py", line 130, in run_goal_rules exit_code = self.scheduler_session.run_goal_rule( File "/data/home/asher/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0a1_py38/lib/python3.8/site-packages/pants/engine/internals/scheduler.py", line 561, in run_goal_rule self._raise_on_error([t for _, t in throws]) File "/data/home/asher/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0a1_py38/lib/python3.8/site-packages/pants/engine/internals/scheduler.py", line 520, in _raise_on_error raise ExecutionError( pants.engine.internals.scheduler.ExecutionError: 1 Exception encountered: Engine traceback: in select in `binary` goal in pants.backend.python.rules.create_python_binary.create_python_binary in pants.backend.python.rules.pex.two_step_create_pex in pants.backend.python.rules.pex.create_pex Traceback (no traceback): <pants native internals> Exception: String("Digest Digest(Fingerprint<97adba2ad1bfef3ba1b37d6b119e15498ed2a60392241b5ea7c28c602826dd6c>, 97) did not exist in the Store.")
pants.engine.internals.scheduler.ExecutionError
def garbage_collect_store(self, target_size_bytes: int) -> None: self._scheduler.garbage_collect_store(target_size_bytes)
def garbage_collect_store(self): self._scheduler.garbage_collect_store()
https://github.com/pantsbuild/pants/issues/10719
18:08:49.83 [WARN] <unknown>:882: DeprecationWarning: invalid escape sequence \d 18:08:52.21 [WARN] Completed: Find PEX Python - No bootstrap Python executable could be found from the option `interpreter_search_paths` in the `[python-setup]` scope. Will attempt to run PEXes directly. 18:08:53.11 [WARN] /data/home/asher/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0a1_py38/lib/python3.8/site-packages/pants/base/exception_sink.py:359: DeprecationWarning: PY_SSIZE_T_CLEAN will be required for '#' formats process_title=setproctitle.getproctitle(), 18:08:53.11 [ERROR] 1 Exception encountered: Engine traceback: in select in `binary` goal in pants.backend.python.rules.create_python_binary.create_python_binary in pants.backend.python.rules.pex.two_step_create_pex in pants.backend.python.rules.pex.create_pex Traceback (no traceback): <pants native internals> Exception: String("Digest Digest(Fingerprint<97adba2ad1bfef3ba1b37d6b119e15498ed2a60392241b5ea7c28c602826dd6c>, 97) did not exist in the Store.") Traceback (most recent call last): File "/data/home/asher/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0a1_py38/lib/python3.8/site-packages/pants/bin/local_pants_runner.py", line 255, in run engine_result = self._run_v2() File "/data/home/asher/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0a1_py38/lib/python3.8/site-packages/pants/bin/local_pants_runner.py", line 166, in _run_v2 return self._maybe_run_v2_body(goals, poll=False) File "/data/home/asher/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0a1_py38/lib/python3.8/site-packages/pants/bin/local_pants_runner.py", line 183, in _maybe_run_v2_body return self.graph_session.run_goal_rules( File "/data/home/asher/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0a1_py38/lib/python3.8/site-packages/pants/init/engine_initializer.py", line 130, in run_goal_rules exit_code = self.scheduler_session.run_goal_rule( File "/data/home/asher/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0a1_py38/lib/python3.8/site-packages/pants/engine/internals/scheduler.py", line 561, in run_goal_rule self._raise_on_error([t for _, t in throws]) File "/data/home/asher/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0a1_py38/lib/python3.8/site-packages/pants/engine/internals/scheduler.py", line 520, in _raise_on_error raise ExecutionError( pants.engine.internals.scheduler.ExecutionError: 1 Exception encountered: Engine traceback: in select in `binary` goal in pants.backend.python.rules.create_python_binary.create_python_binary in pants.backend.python.rules.pex.two_step_create_pex in pants.backend.python.rules.pex.create_pex Traceback (no traceback): <pants native internals> Exception: String("Digest Digest(Fingerprint<97adba2ad1bfef3ba1b37d6b119e15498ed2a60392241b5ea7c28c602826dd6c>, 97) did not exist in the Store.")
pants.engine.internals.scheduler.ExecutionError
def __init__( self, scheduler: Scheduler, period_secs=10, lease_extension_interval_secs=(15 * 60), gc_interval_secs=(1 * 60 * 60), target_size_bytes=(4 * 1024 * 1024 * 1024), ): super().__init__() self._scheduler_session = scheduler.new_session(build_id="store_gc_service_session") self._logger = logging.getLogger(__name__) self._period_secs = period_secs self._lease_extension_interval_secs = lease_extension_interval_secs self._gc_interval_secs = gc_interval_secs self._target_size_bytes = target_size_bytes self._set_next_gc() self._set_next_lease_extension()
def __init__( self, scheduler: Scheduler, period_secs=10, lease_extension_interval_secs=(30 * 60), gc_interval_secs=(4 * 60 * 60), ): super().__init__() self._scheduler_session = scheduler.new_session(build_id="store_gc_service_session") self._logger = logging.getLogger(__name__) self._period_secs = period_secs self._lease_extension_interval_secs = lease_extension_interval_secs self._gc_interval_secs = gc_interval_secs self._set_next_gc() self._set_next_lease_extension()
https://github.com/pantsbuild/pants/issues/10719
18:08:49.83 [WARN] <unknown>:882: DeprecationWarning: invalid escape sequence \d 18:08:52.21 [WARN] Completed: Find PEX Python - No bootstrap Python executable could be found from the option `interpreter_search_paths` in the `[python-setup]` scope. Will attempt to run PEXes directly. 18:08:53.11 [WARN] /data/home/asher/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0a1_py38/lib/python3.8/site-packages/pants/base/exception_sink.py:359: DeprecationWarning: PY_SSIZE_T_CLEAN will be required for '#' formats process_title=setproctitle.getproctitle(), 18:08:53.11 [ERROR] 1 Exception encountered: Engine traceback: in select in `binary` goal in pants.backend.python.rules.create_python_binary.create_python_binary in pants.backend.python.rules.pex.two_step_create_pex in pants.backend.python.rules.pex.create_pex Traceback (no traceback): <pants native internals> Exception: String("Digest Digest(Fingerprint<97adba2ad1bfef3ba1b37d6b119e15498ed2a60392241b5ea7c28c602826dd6c>, 97) did not exist in the Store.") Traceback (most recent call last): File "/data/home/asher/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0a1_py38/lib/python3.8/site-packages/pants/bin/local_pants_runner.py", line 255, in run engine_result = self._run_v2() File "/data/home/asher/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0a1_py38/lib/python3.8/site-packages/pants/bin/local_pants_runner.py", line 166, in _run_v2 return self._maybe_run_v2_body(goals, poll=False) File "/data/home/asher/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0a1_py38/lib/python3.8/site-packages/pants/bin/local_pants_runner.py", line 183, in _maybe_run_v2_body return self.graph_session.run_goal_rules( File "/data/home/asher/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0a1_py38/lib/python3.8/site-packages/pants/init/engine_initializer.py", line 130, in run_goal_rules exit_code = self.scheduler_session.run_goal_rule( File "/data/home/asher/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0a1_py38/lib/python3.8/site-packages/pants/engine/internals/scheduler.py", line 561, in run_goal_rule self._raise_on_error([t for _, t in throws]) File "/data/home/asher/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0a1_py38/lib/python3.8/site-packages/pants/engine/internals/scheduler.py", line 520, in _raise_on_error raise ExecutionError( pants.engine.internals.scheduler.ExecutionError: 1 Exception encountered: Engine traceback: in select in `binary` goal in pants.backend.python.rules.create_python_binary.create_python_binary in pants.backend.python.rules.pex.two_step_create_pex in pants.backend.python.rules.pex.create_pex Traceback (no traceback): <pants native internals> Exception: String("Digest Digest(Fingerprint<97adba2ad1bfef3ba1b37d6b119e15498ed2a60392241b5ea7c28c602826dd6c>, 97) did not exist in the Store.")
pants.engine.internals.scheduler.ExecutionError
def _maybe_garbage_collect(self): if time.time() < self._next_gc: return self._logger.info("Garbage collecting store") self._scheduler_session.garbage_collect_store(self._target_size_bytes) self._logger.info("Done garbage collecting store") self._set_next_gc()
def _maybe_garbage_collect(self): if time.time() < self._next_gc: return self._logger.info("Garbage collecting store") self._scheduler_session.garbage_collect_store() self._logger.info("Done garbage collecting store") self._set_next_gc()
https://github.com/pantsbuild/pants/issues/10719
18:08:49.83 [WARN] <unknown>:882: DeprecationWarning: invalid escape sequence \d 18:08:52.21 [WARN] Completed: Find PEX Python - No bootstrap Python executable could be found from the option `interpreter_search_paths` in the `[python-setup]` scope. Will attempt to run PEXes directly. 18:08:53.11 [WARN] /data/home/asher/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0a1_py38/lib/python3.8/site-packages/pants/base/exception_sink.py:359: DeprecationWarning: PY_SSIZE_T_CLEAN will be required for '#' formats process_title=setproctitle.getproctitle(), 18:08:53.11 [ERROR] 1 Exception encountered: Engine traceback: in select in `binary` goal in pants.backend.python.rules.create_python_binary.create_python_binary in pants.backend.python.rules.pex.two_step_create_pex in pants.backend.python.rules.pex.create_pex Traceback (no traceback): <pants native internals> Exception: String("Digest Digest(Fingerprint<97adba2ad1bfef3ba1b37d6b119e15498ed2a60392241b5ea7c28c602826dd6c>, 97) did not exist in the Store.") Traceback (most recent call last): File "/data/home/asher/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0a1_py38/lib/python3.8/site-packages/pants/bin/local_pants_runner.py", line 255, in run engine_result = self._run_v2() File "/data/home/asher/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0a1_py38/lib/python3.8/site-packages/pants/bin/local_pants_runner.py", line 166, in _run_v2 return self._maybe_run_v2_body(goals, poll=False) File "/data/home/asher/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0a1_py38/lib/python3.8/site-packages/pants/bin/local_pants_runner.py", line 183, in _maybe_run_v2_body return self.graph_session.run_goal_rules( File "/data/home/asher/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0a1_py38/lib/python3.8/site-packages/pants/init/engine_initializer.py", line 130, in run_goal_rules exit_code = self.scheduler_session.run_goal_rule( File "/data/home/asher/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0a1_py38/lib/python3.8/site-packages/pants/engine/internals/scheduler.py", line 561, in run_goal_rule self._raise_on_error([t for _, t in throws]) File "/data/home/asher/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0a1_py38/lib/python3.8/site-packages/pants/engine/internals/scheduler.py", line 520, in _raise_on_error raise ExecutionError( pants.engine.internals.scheduler.ExecutionError: 1 Exception encountered: Engine traceback: in select in `binary` goal in pants.backend.python.rules.create_python_binary.create_python_binary in pants.backend.python.rules.pex.two_step_create_pex in pants.backend.python.rules.pex.create_pex Traceback (no traceback): <pants native internals> Exception: String("Digest Digest(Fingerprint<97adba2ad1bfef3ba1b37d6b119e15498ed2a60392241b5ea7c28c602826dd6c>, 97) did not exist in the Store.")
pants.engine.internals.scheduler.ExecutionError
def __init__( self, scheduler: Scheduler, period_secs=10, lease_extension_interval_secs=(15 * 60), gc_interval_secs=(1 * 60 * 60), target_size_bytes=(4 * 1024 * 1024 * 1024), ): super().__init__() self._scheduler_session = scheduler.new_session( zipkin_trace_v2=False, build_id="store_gc_service_session" ) self._logger = logging.getLogger(__name__) self._period_secs = period_secs self._lease_extension_interval_secs = lease_extension_interval_secs self._gc_interval_secs = gc_interval_secs self._target_size_bytes = target_size_bytes self._set_next_gc() self._set_next_lease_extension()
def __init__( self, scheduler: Scheduler, period_secs=10, lease_extension_interval_secs=(30 * 60), gc_interval_secs=(4 * 60 * 60), ): super().__init__() self._scheduler_session = scheduler.new_session( zipkin_trace_v2=False, build_id="store_gc_service_session" ) self._logger = logging.getLogger(__name__) self._period_secs = period_secs self._lease_extension_interval_secs = lease_extension_interval_secs self._gc_interval_secs = gc_interval_secs self._set_next_gc() self._set_next_lease_extension()
https://github.com/pantsbuild/pants/issues/10719
18:08:49.83 [WARN] <unknown>:882: DeprecationWarning: invalid escape sequence \d 18:08:52.21 [WARN] Completed: Find PEX Python - No bootstrap Python executable could be found from the option `interpreter_search_paths` in the `[python-setup]` scope. Will attempt to run PEXes directly. 18:08:53.11 [WARN] /data/home/asher/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0a1_py38/lib/python3.8/site-packages/pants/base/exception_sink.py:359: DeprecationWarning: PY_SSIZE_T_CLEAN will be required for '#' formats process_title=setproctitle.getproctitle(), 18:08:53.11 [ERROR] 1 Exception encountered: Engine traceback: in select in `binary` goal in pants.backend.python.rules.create_python_binary.create_python_binary in pants.backend.python.rules.pex.two_step_create_pex in pants.backend.python.rules.pex.create_pex Traceback (no traceback): <pants native internals> Exception: String("Digest Digest(Fingerprint<97adba2ad1bfef3ba1b37d6b119e15498ed2a60392241b5ea7c28c602826dd6c>, 97) did not exist in the Store.") Traceback (most recent call last): File "/data/home/asher/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0a1_py38/lib/python3.8/site-packages/pants/bin/local_pants_runner.py", line 255, in run engine_result = self._run_v2() File "/data/home/asher/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0a1_py38/lib/python3.8/site-packages/pants/bin/local_pants_runner.py", line 166, in _run_v2 return self._maybe_run_v2_body(goals, poll=False) File "/data/home/asher/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0a1_py38/lib/python3.8/site-packages/pants/bin/local_pants_runner.py", line 183, in _maybe_run_v2_body return self.graph_session.run_goal_rules( File "/data/home/asher/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0a1_py38/lib/python3.8/site-packages/pants/init/engine_initializer.py", line 130, in run_goal_rules exit_code = self.scheduler_session.run_goal_rule( File "/data/home/asher/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0a1_py38/lib/python3.8/site-packages/pants/engine/internals/scheduler.py", line 561, in run_goal_rule self._raise_on_error([t for _, t in throws]) File "/data/home/asher/.cache/pants/setup/bootstrap-Linux-x86_64/2.0.0a1_py38/lib/python3.8/site-packages/pants/engine/internals/scheduler.py", line 520, in _raise_on_error raise ExecutionError( pants.engine.internals.scheduler.ExecutionError: 1 Exception encountered: Engine traceback: in select in `binary` goal in pants.backend.python.rules.create_python_binary.create_python_binary in pants.backend.python.rules.pex.two_step_create_pex in pants.backend.python.rules.pex.create_pex Traceback (no traceback): <pants native internals> Exception: String("Digest Digest(Fingerprint<97adba2ad1bfef3ba1b37d6b119e15498ed2a60392241b5ea7c28c602826dd6c>, 97) did not exist in the Store.")
pants.engine.internals.scheduler.ExecutionError
def _get_frame_info(stacklevel: int) -> inspect.FrameInfo: """Get a Traceback for the given `stacklevel`. For example: `stacklevel=0` means this function's frame (_get_frame_info()). `stacklevel=1` means the calling function's frame. See https://docs.python.org/3/library/inspect.html#inspect.getouterframes for more info. NB: If `stacklevel` is greater than the number of actual frames, the outermost frame is used instead. """ frame_list = inspect.getouterframes(inspect.currentframe()) frame_stack_index = ( stacklevel if stacklevel < len(frame_list) else len(frame_list) - 1 ) return frame_list[frame_stack_index]
def _get_frame_info(stacklevel: int, context: int = 1) -> inspect.FrameInfo: """Get a Traceback for the given `stacklevel`. For example: `stacklevel=0` means this function's frame (_get_frame_info()). `stacklevel=1` means the calling function's frame. See https://docs.python.org/2/library/inspect.html#inspect.getouterframes for more info. NB: If `stacklevel` is greater than the number of actual frames, the outermost frame is used instead. """ frame_list = inspect.getouterframes(inspect.currentframe(), context=context) frame_stack_index = ( stacklevel if stacklevel < len(frame_list) else len(frame_list) - 1 ) return frame_list[frame_stack_index]
https://github.com/pantsbuild/pants/issues/9057
Traceback (most recent call last): File "<example>/pantsbuild.pants-1.25.0.dev3+git951fbda1-cp36-abi3-macosx_10_11_x86_64.whl/pants/engine/mapper.py", line 55, in parse objects = parser.parse(filepath, filecontent) File "<example>/pantsbuild.pants-1.25.0.dev3+git951fbda1-cp36-abi3-macosx_10_11_x86_64.whl/pants/engine/legacy/parser.py", line 177, in parse self.check_for_deprecated_globs_usage(token_str, filepath, lineno) File "<example>/pantsbuild.pants-1.25.0.dev3+git951fbda1-cp36-abi3-macosx_10_11_x86_64.whl/pants/engine/legacy/parser.py", line 152, in check_for_deprecated_globs_usage hint=warning, File "<example>/pantsbuild.pants-1.25.0.dev3+git951fbda1-cp36-abi3-macosx_10_11_x86_64.whl/pants/base/deprecated.py", line 211, in warn_or_error lineno=line_number) File "<python_dist>/lib/python3.6/warnings.py", line 99, in _showwarnmsg msg.file, msg.line) File "<example>/pantsbuild.pants-1.25.0.dev3+git951fbda1-cp36-abi3-macosx_10_11_x86_64.whl/pants/base/deprecated.py", line 127, in wrapped line=(line or context_lines_string)) File "<example>/pantsbuild.pants-1.25.0.dev3+git951fbda1-cp36-abi3-macosx_10_11_x86_64.whl/pants/base/deprecated.py", line 127, in wrapped line=(line or context_lines_string)) File "<example>/pantsbuild.pants-1.25.0.dev3+git951fbda1-cp36-abi3-macosx_10_11_x86_64.whl/pants/base/deprecated.py", line 127, in wrapped line=(line or context_lines_string)) [Previous line repeated 968 more times] File "<python_dist>/lib/python3.6/logging/__init__.py", line 2003, in _showwarning logger.warning("%s", s) File "<python_dist>/lib/python3.6/logging/__init__.py", line 1318, in warning self._log(WARNING, msg, args, **kwargs) File "<python_dist>/lib/python3.6/logging/__init__.py", line 1441, in _log exc_info, func, extra, sinfo) File "<python_dist>/lib/python3.6/logging/__init__.py", line 1411, in makeRecord sinfo) File "<python_dist>/lib/python3.6/logging/__init__.py", line 277, in __init__ if (args and len(args) == 1 and isinstance(args[0], collections.Mapping) File "<python_dist>/lib/python3.6/abc.py", line 188, in __instancecheck__ subclass in cls._abc_negative_cache): File "<python_dist>/lib/python3.6/_weakrefset.py", line 75, in __contains__ return wr in self.data RecursionError: maximum recursion depth exceeded in comparison
RecursionError
def warn_or_error( removal_version: str, deprecated_entity_description: str, hint: Optional[str] = None, deprecation_start_version: Optional[str] = None, stacklevel: int = 3, frame_info: Optional[inspect.FrameInfo] = None, ensure_stderr: bool = False, print_warning: bool = True, ) -> None: """Check the removal_version against the current pants version. Issues a warning if the removal version is > current pants version, or an error otherwise. :param removal_version: The pantsbuild.pants version at which the deprecated entity will be/was removed. :param deprecated_entity_description: A short description of the deprecated entity, that we can embed in warning/error messages. :param hint: A message describing how to migrate from the removed entity. :param deprecation_start_version: The pantsbuild.pants version at which the entity will begin to display a deprecation warning. This must be less than the `removal_version`. If not provided, the deprecation warning is always displayed. :param stacklevel: The stacklevel to pass to warnings.warn, which determines the file name and line number of the error message. :param frame_info: If provided, use this frame info instead of getting one from `stacklevel`. :param ensure_stderr: Whether use warnings.warn, or use warnings.showwarning to print directly to stderr. :param print_warning: Whether to print a warning for deprecations *before* their removal. If this flag is off, an exception will still be raised for options past their deprecation date. :raises DeprecationApplicationError: if the removal_version parameter is invalid. :raises CodeRemovedError: if the current version is later than the version marked for removal. """ removal_semver = validate_deprecation_semver(removal_version, "removal version") if deprecation_start_version: deprecation_start_semver = validate_deprecation_semver( deprecation_start_version, "deprecation start version" ) if deprecation_start_semver >= removal_semver: raise InvalidSemanticVersionOrderingError( "The deprecation start version {} must be less than the end version {}.".format( deprecation_start_version, removal_version ) ) elif PANTS_SEMVER < deprecation_start_semver: return msg = "DEPRECATED: {} {} removed in version {}.".format( deprecated_entity_description, get_deprecated_tense(removal_version), removal_version, ) if hint: msg += "\n {}".format(hint) # We need to have filename and line_number for warnings.formatwarning, which appears to be the only # way to get a warning message to display to stderr. We get that from frame_info. if frame_info is None: frame_info = _get_frame_info(stacklevel) _, filename, line_number, _, _, _ = frame_info if removal_semver > PANTS_SEMVER: if ensure_stderr: # No warning filters can stop us from printing this message directly to stderr. warning_msg = warnings.formatwarning( msg, DeprecationWarning, filename, line_number, ) print(warning_msg, file=sys.stderr) elif print_warning: # This output is filtered by warning filters. warnings.warn_explicit( message=msg, category=DeprecationWarning, filename=filename, lineno=line_number, ) return else: raise CodeRemovedError(msg)
def warn_or_error( removal_version: str, deprecated_entity_description: str, hint: Optional[str] = None, deprecation_start_version: Optional[str] = None, stacklevel: int = 3, frame_info: Optional[inspect.FrameInfo] = None, context: int = 1, ensure_stderr: bool = False, print_warning: bool = True, ) -> None: """Check the removal_version against the current pants version. Issues a warning if the removal version is > current pants version, or an error otherwise. :param removal_version: The pantsbuild.pants version at which the deprecated entity will be/was removed. :param deprecated_entity_description: A short description of the deprecated entity, that we can embed in warning/error messages. :param hint: A message describing how to migrate from the removed entity. :param deprecation_start_version: The pantsbuild.pants version at which the entity will begin to display a deprecation warning. This must be less than the `removal_version`. If not provided, the deprecation warning is always displayed. :param stacklevel: The stacklevel to pass to warnings.warn. :param frame_info: If provided, use this frame info instead of getting one from `stacklevel`. :param context: The number of lines of source code surrounding the selected frame to display in a warning message. :param ensure_stderr: Whether use warnings.warn, or use warnings.showwarning to print directly to stderr. :param print_warning: Whether to print a warning for deprecations *before* their removal. If this flag is off, an exception will still be raised for options past their deprecation date. :raises DeprecationApplicationError: if the removal_version parameter is invalid. :raises CodeRemovedError: if the current version is later than the version marked for removal. """ removal_semver = validate_deprecation_semver(removal_version, "removal version") if deprecation_start_version: deprecation_start_semver = validate_deprecation_semver( deprecation_start_version, "deprecation start version" ) if deprecation_start_semver >= removal_semver: raise InvalidSemanticVersionOrderingError( "The deprecation start version {} must be less than the end version {}.".format( deprecation_start_version, removal_version ) ) elif PANTS_SEMVER < deprecation_start_semver: return msg = "DEPRECATED: {} {} removed in version {}.".format( deprecated_entity_description, get_deprecated_tense(removal_version), removal_version, ) if hint: msg += "\n {}".format(hint) # We need to have filename and line_number for warnings.formatwarning, which appears to be the only # way to get a warning message to display to stderr. We get that from frame_info -- it's too bad # we have to reconstruct the `stacklevel` logic ourselves, but we do also gain the ability to have # multiple lines of context, which is neat. if frame_info is None: frame_info = _get_frame_info(stacklevel, context=context) _, filename, line_number, _, code_context, _ = frame_info if code_context: context_lines = "".join(code_context) else: context_lines = "<no code context available>" if removal_semver > PANTS_SEMVER: if ensure_stderr: # No warning filters can stop us from printing this message directly to stderr. warning_msg = warnings.formatwarning( msg, DeprecationWarning, filename, line_number, line=context_lines ) print(warning_msg, file=sys.stderr) elif print_warning: # This output is filtered by warning filters. with _greater_warnings_context(context_lines): warnings.warn_explicit( message=msg, category=DeprecationWarning, filename=filename, lineno=line_number, ) return else: raise CodeRemovedError(msg)
https://github.com/pantsbuild/pants/issues/9057
Traceback (most recent call last): File "<example>/pantsbuild.pants-1.25.0.dev3+git951fbda1-cp36-abi3-macosx_10_11_x86_64.whl/pants/engine/mapper.py", line 55, in parse objects = parser.parse(filepath, filecontent) File "<example>/pantsbuild.pants-1.25.0.dev3+git951fbda1-cp36-abi3-macosx_10_11_x86_64.whl/pants/engine/legacy/parser.py", line 177, in parse self.check_for_deprecated_globs_usage(token_str, filepath, lineno) File "<example>/pantsbuild.pants-1.25.0.dev3+git951fbda1-cp36-abi3-macosx_10_11_x86_64.whl/pants/engine/legacy/parser.py", line 152, in check_for_deprecated_globs_usage hint=warning, File "<example>/pantsbuild.pants-1.25.0.dev3+git951fbda1-cp36-abi3-macosx_10_11_x86_64.whl/pants/base/deprecated.py", line 211, in warn_or_error lineno=line_number) File "<python_dist>/lib/python3.6/warnings.py", line 99, in _showwarnmsg msg.file, msg.line) File "<example>/pantsbuild.pants-1.25.0.dev3+git951fbda1-cp36-abi3-macosx_10_11_x86_64.whl/pants/base/deprecated.py", line 127, in wrapped line=(line or context_lines_string)) File "<example>/pantsbuild.pants-1.25.0.dev3+git951fbda1-cp36-abi3-macosx_10_11_x86_64.whl/pants/base/deprecated.py", line 127, in wrapped line=(line or context_lines_string)) File "<example>/pantsbuild.pants-1.25.0.dev3+git951fbda1-cp36-abi3-macosx_10_11_x86_64.whl/pants/base/deprecated.py", line 127, in wrapped line=(line or context_lines_string)) [Previous line repeated 968 more times] File "<python_dist>/lib/python3.6/logging/__init__.py", line 2003, in _showwarning logger.warning("%s", s) File "<python_dist>/lib/python3.6/logging/__init__.py", line 1318, in warning self._log(WARNING, msg, args, **kwargs) File "<python_dist>/lib/python3.6/logging/__init__.py", line 1441, in _log exc_info, func, extra, sinfo) File "<python_dist>/lib/python3.6/logging/__init__.py", line 1411, in makeRecord sinfo) File "<python_dist>/lib/python3.6/logging/__init__.py", line 277, in __init__ if (args and len(args) == 1 and isinstance(args[0], collections.Mapping) File "<python_dist>/lib/python3.6/abc.py", line 188, in __instancecheck__ subclass in cls._abc_negative_cache): File "<python_dist>/lib/python3.6/_weakrefset.py", line 75, in __contains__ return wr in self.data RecursionError: maximum recursion depth exceeded in comparison
RecursionError
def datatype(field_decls, superclass_name=None, **kwargs): """A wrapper for `namedtuple` that accounts for the type of the object in equality. Field declarations can be a string, which declares a field with that name and no type checking. Field declarations can also be a tuple `('field_name', field_type)`, which declares a field named `field_name` which is type-checked at construction. If a type is given, the value provided to the constructor for that field must be exactly that type (i.e. `type(x) == field_type`), and not e.g. a subclass. :param field_decls: Iterable of field declarations. :return: A type object which can then be subclassed. :raises: :class:`TypeError` """ field_names = [] fields_with_constraints = OrderedDict() for maybe_decl in field_decls: # ('field_name', type) if isinstance(maybe_decl, tuple): field_name, type_spec = maybe_decl if isinstance(type_spec, type): type_constraint = Exactly(type_spec) elif isinstance(type_spec, TypeConstraint): type_constraint = type_spec else: raise TypeError( "type spec for field '{}' was not a type or TypeConstraint: was {!r} (type {!r}).".format( field_name, type_spec, type(type_spec).__name__ ) ) fields_with_constraints[field_name] = type_constraint else: # interpret it as a field name without a type to check field_name = maybe_decl # namedtuple() already checks field uniqueness field_names.append(field_name) if not superclass_name: superclass_name = "_anonymous_namedtuple_subclass" namedtuple_cls = namedtuple(superclass_name, field_names, **kwargs) class DataType(namedtuple_cls): @classproperty def type_check_error_type(cls): """The exception type to use in make_type_error().""" return TypedDatatypeInstanceConstructionError @classmethod def make_type_error(cls, msg, *args, **kwargs): """A helper method to generate an exception type for type checking errors. This method uses `cls.type_check_error_type` to ensure that type checking errors can be caught with a reliable exception type. The type returned by `cls.type_check_error_type` should ensure that the exception messages are prefixed with enough context to be useful and *not* confusing. """ return cls.type_check_error_type(cls.__name__, msg, *args, **kwargs) def __new__(cls, *args, **kwargs): # TODO: Ideally we could execute this exactly once per `cls` but it should be a # relatively cheap check. if not hasattr(cls.__eq__, "_eq_override_canary"): raise cls.make_type_error("Should not override __eq__.") try: this_object = super(DataType, cls).__new__(cls, *args, **kwargs) except TypeError as e: raise cls.make_type_error( "error in namedtuple() base constructor: {}".format(e) ) # TODO: Make this kind of exception pattern (filter for errors then display them all at once) # more ergonomic. type_failure_msgs = [] for field_name, field_constraint in fields_with_constraints.items(): field_value = getattr(this_object, field_name) try: field_constraint.validate_satisfied_by(field_value) except TypeConstraintError as e: type_failure_msgs.append( "field '{}' was invalid: {}".format(field_name, e) ) if type_failure_msgs: raise cls.make_type_error( "errors type checking constructor arguments:\n{}".format( "\n".join(type_failure_msgs) ) ) return this_object def __eq__(self, other): if self is other: return True # Compare types and fields. if type(self) != type(other): return False # Explicitly return super.__eq__'s value in case super returns NotImplemented return super(DataType, self).__eq__(other) # We define an attribute on the `cls` level definition of `__eq__` that will allow us to detect # that it has been overridden. __eq__._eq_override_canary = None def __ne__(self, other): return not (self == other) # NB: in Python 3, whenever __eq__ is overridden, __hash__() must also be # explicitly implemented, otherwise Python will raise "unhashable type". See # https://docs.python.org/3/reference/datamodel.html#object.__hash__. def __hash__(self): return super(DataType, self).__hash__() # NB: As datatype is not iterable, we need to override both __iter__ and all of the # namedtuple methods that expect self to be iterable. def __iter__(self): raise self.make_type_error("datatype object is not iterable") def _super_iter(self): return super(DataType, self).__iter__() def _asdict(self): """Return a new OrderedDict which maps field names to their values""" return OrderedDict(zip(self._fields, self._super_iter())) def _replace(_self, **kwds): """Return a new datatype object replacing specified fields with new values""" field_dict = _self._asdict() field_dict.update(**kwds) return type(_self)(**field_dict) copy = _replace # NB: it is *not* recommended to rely on the ordering of the tuple returned by this method. def __getnewargs__(self): """Return self as a plain tuple. Used by copy and pickle.""" return tuple(self._super_iter()) def __repr__(self): args_formatted = [] for field_name in field_names: field_value = getattr(self, field_name) args_formatted.append("{}={!r}".format(field_name, field_value)) return "{class_name}({args_joined})".format( class_name=type(self).__name__, args_joined=", ".join(args_formatted) ) def __str__(self): elements_formatted = [] for field_name in field_names: constraint_for_field = fields_with_constraints.get(field_name, None) field_value = getattr(self, field_name) if not constraint_for_field: elements_formatted.append( # TODO: consider using the repr of arguments in this method. "{field_name}={field_value}".format( field_name=field_name, field_value=field_value ) ) else: elements_formatted.append( "{field_name}<{type_constraint}>={field_value}".format( field_name=field_name, type_constraint=constraint_for_field, field_value=field_value, ) ) return "{class_name}({typed_tagged_elements})".format( class_name=type(self).__name__, typed_tagged_elements=", ".join(elements_formatted), ) # Return a new type with the given name, inheriting from the DataType class # just defined, with an empty class body. try: # Python3 return type(superclass_name, (DataType,), {}) except TypeError: # Python2 return type(superclass_name.encode("utf-8"), (DataType,), {})
def datatype(field_decls, superclass_name=None, **kwargs): """A wrapper for `namedtuple` that accounts for the type of the object in equality. Field declarations can be a string, which declares a field with that name and no type checking. Field declarations can also be a tuple `('field_name', field_type)`, which declares a field named `field_name` which is type-checked at construction. If a type is given, the value provided to the constructor for that field must be exactly that type (i.e. `type(x) == field_type`), and not e.g. a subclass. :param field_decls: Iterable of field declarations. :return: A type object which can then be subclassed. :raises: :class:`TypeError` """ field_names = [] fields_with_constraints = OrderedDict() for maybe_decl in field_decls: # ('field_name', type) if isinstance(maybe_decl, tuple): field_name, type_spec = maybe_decl if isinstance(type_spec, type): type_constraint = Exactly(type_spec) elif isinstance(type_spec, TypeConstraint): type_constraint = type_spec else: raise TypeError( "type spec for field '{}' was not a type or TypeConstraint: was {!r} (type {!r}).".format( field_name, type_spec, type(type_spec).__name__ ) ) fields_with_constraints[field_name] = type_constraint else: # interpret it as a field name without a type to check field_name = maybe_decl # namedtuple() already checks field uniqueness field_names.append(field_name) if not superclass_name: superclass_name = "_anonymous_namedtuple_subclass" namedtuple_cls = namedtuple(superclass_name, field_names, **kwargs) class DataType(namedtuple_cls): @classproperty def type_check_error_type(cls): """The exception type to use in make_type_error().""" return TypedDatatypeInstanceConstructionError @classmethod def make_type_error(cls, msg, *args, **kwargs): """A helper method to generate an exception type for type checking errors. This method uses `cls.type_check_error_type` to ensure that type checking errors can be caught with a reliable exception type. The type returned by `cls.type_check_error_type` should ensure that the exception messages are prefixed with enough context to be useful and *not* confusing. """ return cls.type_check_error_type(cls.__name__, msg, *args, **kwargs) def __new__(cls, *args, **kwargs): # TODO: Ideally we could execute this exactly once per `cls` but it should be a # relatively cheap check. if not hasattr(cls.__eq__, "_eq_override_canary"): raise cls.make_type_error("Should not override __eq__.") try: this_object = super(DataType, cls).__new__(cls, *args, **kwargs) except TypeError as e: raise cls.make_type_error( "error in namedtuple() base constructor: {}".format(e) ) # TODO: Make this kind of exception pattern (filter for errors then display them all at once) # more ergonomic. type_failure_msgs = [] for field_name, field_constraint in fields_with_constraints.items(): field_value = getattr(this_object, field_name) try: field_constraint.validate_satisfied_by(field_value) except TypeConstraintError as e: type_failure_msgs.append( "field '{}' was invalid: {}".format(field_name, e) ) if type_failure_msgs: raise cls.make_type_error( "errors type checking constructor arguments:\n{}".format( "\n".join(type_failure_msgs) ) ) return this_object def __eq__(self, other): if self is other: return True # Compare types and fields. if type(self) != type(other): return False # Explicitly return super.__eq__'s value in case super returns NotImplemented return super(DataType, self).__eq__(other) # We define an attribute on the `cls` level definition of `__eq__` that will allow us to detect # that it has been overridden. __eq__._eq_override_canary = None def __ne__(self, other): return not (self == other) def __hash__(self): return super(DataType, self).__hash__() # NB: As datatype is not iterable, we need to override both __iter__ and all of the # namedtuple methods that expect self to be iterable. def __iter__(self): raise TypeError("'{}' object is not iterable".format(type(self).__name__)) def _super_iter(self): return super(DataType, self).__iter__() def _asdict(self): """Return a new OrderedDict which maps field names to their values""" return OrderedDict(zip(self._fields, self._super_iter())) def _replace(_self, **kwds): """Return a new datatype object replacing specified fields with new values""" field_dict = _self._asdict() field_dict.update(**kwds) return type(_self)(**field_dict) copy = _replace # NB: it is *not* recommended to rely on the ordering of the tuple returned by this method. def __getnewargs__(self): """Return self as a plain tuple. Used by copy and pickle.""" return tuple(self._super_iter()) def __repr__(self): args_formatted = [] for field_name in field_names: field_value = getattr(self, field_name) args_formatted.append("{}={!r}".format(field_name, field_value)) return "{class_name}({args_joined})".format( class_name=type(self).__name__, args_joined=", ".join(args_formatted) ) def __str__(self): elements_formatted = [] for field_name in field_names: constraint_for_field = fields_with_constraints.get(field_name, None) field_value = getattr(self, field_name) if not constraint_for_field: elements_formatted.append( # TODO: consider using the repr of arguments in this method. "{field_name}={field_value}".format( field_name=field_name, field_value=field_value ) ) else: elements_formatted.append( "{field_name}<{type_constraint}>={field_value}".format( field_name=field_name, type_constraint=constraint_for_field, field_value=field_value, ) ) return "{class_name}({typed_tagged_elements})".format( class_name=type(self).__name__, typed_tagged_elements=", ".join(elements_formatted), ) # Return a new type with the given name, inheriting from the DataType class # just defined, with an empty class body. try: # Python3 return type(superclass_name, (DataType,), {}) except TypeError: # Python2 return type(superclass_name.encode("utf-8"), (DataType,), {})
https://github.com/pantsbuild/pants/issues/7247
==================== FAILURES ==================== CTypesIntegrationTest.test_ctypes_third_party_integration args = (<pants_test.backend.python.tasks.native.test_ctypes_integration.CTypesIntegrationTest testMethod=test_ctypes_third_party_integration>,) kwargs = {} variant = ToolchainVariant(value=u'gnu') @wraps(func) def wrapper(*args, **kwargs): for variant in ToolchainVariant.iterate_enum_variants(): > func(*args, toolchain_variant=variant, **kwargs) .pants.d/pyprep/sources/68db53b799a649f3f92cbd3d3e740d9a1a47be07/pants_test/backend/python/tasks/native/test_ctypes_integration.py:32: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ .pants.d/pyprep/sources/68db53b799a649f3f92cbd3d3e740d9a1a47be07/pants_test/backend/python/tasks/native/test_ctypes_integration.py:195: in test_ctypes_third_party_integration self.assert_success(pants_run) .pants.d/pyprep/sources/68db53b799a649f3f92cbd3d3e740d9a1a47be07/pants_test/pants_run_integration_test.py:452: in assert_success self.assert_result(pants_run, self.PANTS_SUCCESS_CODE, expected=True, msg=msg) .pants.d/pyprep/sources/68db53b799a649f3f92cbd3d3e740d9a1a47be07/pants_test/pants_run_integration_test.py:473: in assert_result assertion(value, pants_run.returncode, error_msg) E AssertionError: /Users/travis/build/pantsbuild/pants/pants --no-pantsrc --pants-workdir=/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d --kill-nailguns --print-exception-stacktrace=True --pants-config-files=/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/pants.ini -q run testprojects/src/python/python_distribution/ctypes_with_third_party:bin_with_third_party E returncode: 1 E stdout: E E FAILURE: /usr/bin/python /Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/run/py/CPython-2.7.10/a8a8db2fdd4fae99b02f6010a93d6f6dc4f9f3dc ... exited non-zero (1) E E stderr: E Traceback (most recent call last): E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/run/py/CPython-2.7.10/a8a8db2fdd4fae99b02f6010a93d6f6dc4f9f3dc/.bootstrap/_pex/pex.py", line 349, in execute E exit_code = self._wrap_coverage(self._wrap_profiling, self._execute) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/run/py/CPython-2.7.10/a8a8db2fdd4fae99b02f6010a93d6f6dc4f9f3dc/.bootstrap/_pex/pex.py", line 281, in _wrap_coverage E return runner(*args) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/run/py/CPython-2.7.10/a8a8db2fdd4fae99b02f6010a93d6f6dc4f9f3dc/.bootstrap/_pex/pex.py", line 312, in _wrap_profiling E return runner(*args) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/run/py/CPython-2.7.10/a8a8db2fdd4fae99b02f6010a93d6f6dc4f9f3dc/.bootstrap/_pex/pex.py", line 394, in _execute E return self.execute_entry(self._pex_info.entry_point) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/run/py/CPython-2.7.10/a8a8db2fdd4fae99b02f6010a93d6f6dc4f9f3dc/.bootstrap/_pex/pex.py", line 506, in execute_entry E return runner(entry_point) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/run/py/CPython-2.7.10/a8a8db2fdd4fae99b02f6010a93d6f6dc4f9f3dc/.bootstrap/_pex/pex.py", line 513, in execute_module E runpy.run_module(module_name, run_name='__main__') E File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 180, in run_module E fname, loader, pkg_name) E File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 72, in _run_code E exec code in run_globals E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/pyprep/sources/46bc27ffbe03ecfe648c4d677289275aa6a6a93c-DefaultFingerprintStrategy_1b8903baa709/python_distribution/ctypes_with_third_party/main.py", line 7, in <module> E from ctypes_python_pkg.ctypes_wrapper import f E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/pyprep/requirements/CPython-2.7.10/dbfa0d2bb6877c576abca571691b6e7c8432a15a-DefaultFingerprintStrategy_25eb7243d755/.deps/ctypes_third_party_test-0.0.1+20865c6b4968b7f61c37fdc3ed80306ee2ca4a3e.defaultfingerprintstrategy.174c3658bd6c.8f03fa43ba4e-py2-none-macosx_10_13_x86_64.whl/ctypes_python_pkg/ctypes_wrapper.py", line 20, in <module> E asdf_cpp_lib = ctypes.CDLL(asdf_cpp_lib_path) E File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ctypes/__init__.py", line 365, in __init__ E self._handle = _dlopen(self._name, mode) E OSError: dlopen(/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/pyprep/requirements/CPython-2.7.10/dbfa0d2bb6877c576abca571691b6e7c8432a15a-DefaultFingerprintStrategy_25eb7243d755/.deps/ctypes_third_party_test-0.0.1+20865c6b4968b7f61c37fdc3ed80306ee2ca4a3e.defaultfingerprintstrategy.174c3658bd6c.8f03fa43ba4e-py2-none-macosx_10_13_x86_64.whl/libasdf-cpp_ctypes-with-third-party.so, 6): Library not loaded: /Users/stuhood/src/pantsbuild-binaries/build-support/bin/gcc/mac/10.13/7.3.0/gcc-7.3.0-osx/gcc-install/lib/libstdc++.6.dylib E Referenced from: /Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/pyprep/requirements/CPython-2.7.10/dbfa0d2bb6877c576abca571691b6e7c8432a15a-DefaultFingerprintStrategy_25eb7243d755/.deps/ctypes_third_party_test-0.0.1+20865c6b4968b7f61c37fdc3ed80306ee2ca4a3e.defaultfingerprintstrategy.174c3658bd6c.8f03fa43ba4e-py2-none-macosx_10_13_x86_64.whl/libasdf-cpp_ctypes-with-third-party.so E Reason: image not found E E FAILURE -------------- Captured stdout call -------------- logs/exceptions.4006.log +++ logs/exceptions.4006.log --- logs/exceptions.log +++ logs/exceptions.log --- CTypesIntegrationTest.test_native_compiler_option_sets_integration args = (<pants_test.backend.python.tasks.native.test_ctypes_integration.CTypesIntegrationTest testMethod=test_native_compiler_option_sets_integration>,) kwargs = {} variant = ToolchainVariant(value=u'gnu') @wraps(func) def wrapper(*args, **kwargs): for variant in ToolchainVariant.iterate_enum_variants(): > func(*args, toolchain_variant=variant, **kwargs) .pants.d/pyprep/sources/68db53b799a649f3f92cbd3d3e740d9a1a47be07/pants_test/backend/python/tasks/native/test_ctypes_integration.py:32: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ .pants.d/pyprep/sources/68db53b799a649f3f92cbd3d3e740d9a1a47be07/pants_test/backend/python/tasks/native/test_ctypes_integration.py:246: in test_native_compiler_option_sets_integration self.assert_success(pants_run) .pants.d/pyprep/sources/68db53b799a649f3f92cbd3d3e740d9a1a47be07/pants_test/pants_run_integration_test.py:452: in assert_success self.assert_result(pants_run, self.PANTS_SUCCESS_CODE, expected=True, msg=msg) .pants.d/pyprep/sources/68db53b799a649f3f92cbd3d3e740d9a1a47be07/pants_test/pants_run_integration_test.py:473: in assert_result assertion(value, pants_run.returncode, error_msg) E AssertionError: /Users/travis/build/pantsbuild/pants/pants --no-pantsrc --pants-workdir=/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d --kill-nailguns --print-exception-stacktrace=True --pants-config-files=/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/pants.ini run testprojects/src/python/python_distribution/ctypes_with_extra_compiler_flags:bin E returncode: 1 E stdout: E E 16:40:21 00:00 [main] E (To run a reporting server: ./pants server) E 16:40:22 00:01 [setup] E 16:40:22 00:01 [parse] E Executing tasks in goals: bootstrap -> imports -> unpack-jars -> unpack-wheels -> deferred-sources -> native-compile -> link -> jvm-platform-validate -> gen -> pyprep -> resolve -> resources -> compile -> binary -> run E 16:40:23 00:02 [bootstrap] E 16:40:23 00:02 [substitute-aliased-targets] E 16:40:23 00:02 [jar-dependency-management] E 16:40:23 00:02 [bootstrap-jvm-tools] E 16:40:23 00:02 [provide-tools-jar] E 16:40:24 00:03 [imports] E 16:40:24 00:03 [ivy-imports] E 16:40:24 00:03 [unpack-jars] E 16:40:24 00:03 [unpack-jars] E 16:40:24 00:03 [unpack-wheels] E 16:40:24 00:03 [unpack-wheels] E 16:40:24 00:03 [deferred-sources] E 16:40:24 00:03 [deferred-sources] E 16:40:24 00:03 [native-compile] E 16:40:24 00:03 [conan-prep] E 16:40:24 00:03 [create-conan-pex] E 16:40:32 00:11 [conan-fetch] E 16:40:32 00:11 [c-for-ctypes] E 16:40:32 00:11 [cpp-for-ctypes] E Invalidated 1 target. E selected compiler exe name: 'g++' E 16:40:32 00:11 [cpp-compile] E E 16:40:33 00:12 [link] E 16:40:33 00:12 [shared-libraries] E Invalidated 1 target. E selected linker exe name: 'g++' E 16:40:33 00:12 [link-shared-libraries] E 16:40:33 00:12 [jvm-platform-validate] E 16:40:33 00:12 [jvm-platform-validate] E 16:40:33 00:12 [gen] E 16:40:33 00:12 [antlr-java] E 16:40:33 00:12 [antlr-py] E 16:40:33 00:12 [jaxb] E 16:40:33 00:12 [protoc] E 16:40:33 00:12 [ragel] E 16:40:33 00:12 [thrift-java] E 16:40:33 00:12 [thrift-py] E 16:40:33 00:12 [grpcio-prep] E 16:40:33 00:12 [grpcio-run] E 16:40:33 00:12 [wire] E 16:40:33 00:12 [avro-java] E 16:40:33 00:12 [go-thrift] E 16:40:33 00:12 [go-protobuf] E 16:40:33 00:12 [jax-ws] E 16:40:33 00:12 [scrooge] E 16:40:33 00:12 [thrifty] E 16:40:33 00:12 [pyprep] E 16:40:33 00:12 [interpreter] E 16:40:33 00:12 [build-local-dists] E Invalidated 1 target. E 16:40:35 00:14 [setup.py] E 16:40:35 00:14 [requirements] E Invalidated 1 target. E 16:40:36 00:15 [sources] E Invalidated 1 target. E 16:40:36 00:15 [resolve] E 16:40:36 00:15 [ivy] E 16:40:36 00:15 [coursier] E 16:40:36 00:15 [go] E 16:40:36 00:15 [scala-js-compile] E 16:40:36 00:15 [scala-js-link] E 16:40:37 00:16 [node] E 16:40:37 00:16 [resources] E 16:40:37 00:16 [prepare] E 16:40:37 00:16 [services] E 16:40:37 00:16 [compile] E 16:40:37 00:16 [node] E 16:40:37 00:16 [compile-jvm-prep-command] E 16:40:37 00:16 [jvm_prep_command] E 16:40:37 00:16 [compile-prep-command] E 16:40:37 00:16 [compile] E 16:40:37 00:16 [rsc] E 16:40:37 00:16 [zinc] E 16:40:37 00:16 [javac] E 16:40:37 00:16 [cpp] E 16:40:37 00:16 [errorprone] E 16:40:37 00:16 [findbugs] E 16:40:37 00:16 [go] E 16:40:37 00:16 [binary] E 16:40:37 00:16 [binary-jvm-prep-command] E 16:40:37 00:16 [jvm_prep_command] E 16:40:37 00:16 [binary-prep-command] E 16:40:37 00:16 [py] E Invalidated 1 target. E created pex dist/bin.pex E 16:40:38 00:17 [py-wheels] E created wheel dist/ctypes_test-0.0.1+74173b5ce60ddd85088b1fed70c8b071f2679604.defaultfingerprintstrategy.12652e89be0f.8f03fa43ba4e-py2-none-macosx_10_13_x86_64.whl E 16:40:38 00:17 [jvm] E 16:40:38 00:17 [dup] E 16:40:38 00:17 [cpplib] E 16:40:38 00:17 [cpp-library] E 16:40:38 00:17 [cpp] E 16:40:38 00:17 [cpp-binary] E 16:40:38 00:17 [go] E 16:40:38 00:17 [run] E 16:40:38 00:17 [py] E Invalidated 3 targets. E 16:40:39 00:18 [run] E E FAILURE: /usr/bin/python /Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/run/py/CPython-2.7.10/3784d4150334a9a89ddceb31bdb13969e94f73b2 ... exited non-zero (1) E E E Waiting for background workers to finish. E 16:40:39 00:18 [complete] E FAILURE E stderr: E Traceback (most recent call last): E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/run/py/CPython-2.7.10/3784d4150334a9a89ddceb31bdb13969e94f73b2/.bootstrap/_pex/pex.py", line 349, in execute E exit_code = self._wrap_coverage(self._wrap_profiling, self._execute) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/run/py/CPython-2.7.10/3784d4150334a9a89ddceb31bdb13969e94f73b2/.bootstrap/_pex/pex.py", line 281, in _wrap_coverage E return runner(*args) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/run/py/CPython-2.7.10/3784d4150334a9a89ddceb31bdb13969e94f73b2/.bootstrap/_pex/pex.py", line 312, in _wrap_profiling E return runner(*args) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/run/py/CPython-2.7.10/3784d4150334a9a89ddceb31bdb13969e94f73b2/.bootstrap/_pex/pex.py", line 394, in _execute E return self.execute_entry(self._pex_info.entry_point) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/run/py/CPython-2.7.10/3784d4150334a9a89ddceb31bdb13969e94f73b2/.bootstrap/_pex/pex.py", line 506, in execute_entry E return runner(entry_point) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/run/py/CPython-2.7.10/3784d4150334a9a89ddceb31bdb13969e94f73b2/.bootstrap/_pex/pex.py", line 513, in execute_module E runpy.run_module(module_name, run_name='__main__') E File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 180, in run_module E fname, loader, pkg_name) E File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 72, in _run_code E exec code in run_globals E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/pyprep/sources/be29db057705cafb8edc0e69942013e74ccffbe3-DefaultFingerprintStrategy_1b8903baa709/python_distribution/ctypes_with_extra_compiler_flags/main.py", line 7, in <module> E from ctypes_python_pkg.ctypes_wrapper import f E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/pyprep/requirements/CPython-2.7.10/2122a483545750a790ffdd2c65a8039affd3f167-DefaultFingerprintStrategy_25eb7243d755/.deps/ctypes_test-0.0.1+74173b5ce60ddd85088b1fed70c8b071f2679604.defaultfingerprintstrategy.12652e89be0f.8f03fa43ba4e-py2-none-macosx_10_13_x86_64.whl/ctypes_python_pkg/ctypes_wrapper.py", line 20, in <module> E asdf_cpp_lib = ctypes.CDLL(asdf_cpp_lib_path) E File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ctypes/__init__.py", line 365, in __init__ E self._handle = _dlopen(self._name, mode) E OSError: dlopen(/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/pyprep/requirements/CPython-2.7.10/2122a483545750a790ffdd2c65a8039affd3f167-DefaultFingerprintStrategy_25eb7243d755/.deps/ctypes_test-0.0.1+74173b5ce60ddd85088b1fed70c8b071f2679604.defaultfingerprintstrategy.12652e89be0f.8f03fa43ba4e-py2-none-macosx_10_13_x86_64.whl/libasdf-cpp_ctypes-with-extra-compiler-flags.so, 6): Library not loaded: /Users/stuhood/src/pantsbuild-binaries/build-support/bin/gcc/mac/10.13/7.3.0/gcc-7.3.0-osx/gcc-install/lib/libstdc++.6.dylib E Referenced from: /Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/pyprep/requirements/CPython-2.7.10/2122a483545750a790ffdd2c65a8039affd3f167-DefaultFingerprintStrategy_25eb7243d755/.deps/ctypes_test-0.0.1+74173b5ce60ddd85088b1fed70c8b071f2679604.defaultfingerprintstrategy.12652e89be0f.8f03fa43ba4e-py2-none-macosx_10_13_x86_64.whl/libasdf-cpp_ctypes-with-extra-compiler-flags.so E Reason: image not found -------------- Captured stdout call -------------- logs/exceptions.4063.log +++ logs/exceptions.4063.log --- logs/exceptions.log +++ logs/exceptions.log --- ====== 2 failed, 3 passed in 199.95 seconds ======
AssertionError
def __iter__(self): raise self.make_type_error("datatype object is not iterable")
def __iter__(self): raise TypeError("'{}' object is not iterable".format(type(self).__name__))
https://github.com/pantsbuild/pants/issues/7247
==================== FAILURES ==================== CTypesIntegrationTest.test_ctypes_third_party_integration args = (<pants_test.backend.python.tasks.native.test_ctypes_integration.CTypesIntegrationTest testMethod=test_ctypes_third_party_integration>,) kwargs = {} variant = ToolchainVariant(value=u'gnu') @wraps(func) def wrapper(*args, **kwargs): for variant in ToolchainVariant.iterate_enum_variants(): > func(*args, toolchain_variant=variant, **kwargs) .pants.d/pyprep/sources/68db53b799a649f3f92cbd3d3e740d9a1a47be07/pants_test/backend/python/tasks/native/test_ctypes_integration.py:32: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ .pants.d/pyprep/sources/68db53b799a649f3f92cbd3d3e740d9a1a47be07/pants_test/backend/python/tasks/native/test_ctypes_integration.py:195: in test_ctypes_third_party_integration self.assert_success(pants_run) .pants.d/pyprep/sources/68db53b799a649f3f92cbd3d3e740d9a1a47be07/pants_test/pants_run_integration_test.py:452: in assert_success self.assert_result(pants_run, self.PANTS_SUCCESS_CODE, expected=True, msg=msg) .pants.d/pyprep/sources/68db53b799a649f3f92cbd3d3e740d9a1a47be07/pants_test/pants_run_integration_test.py:473: in assert_result assertion(value, pants_run.returncode, error_msg) E AssertionError: /Users/travis/build/pantsbuild/pants/pants --no-pantsrc --pants-workdir=/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d --kill-nailguns --print-exception-stacktrace=True --pants-config-files=/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/pants.ini -q run testprojects/src/python/python_distribution/ctypes_with_third_party:bin_with_third_party E returncode: 1 E stdout: E E FAILURE: /usr/bin/python /Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/run/py/CPython-2.7.10/a8a8db2fdd4fae99b02f6010a93d6f6dc4f9f3dc ... exited non-zero (1) E E stderr: E Traceback (most recent call last): E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/run/py/CPython-2.7.10/a8a8db2fdd4fae99b02f6010a93d6f6dc4f9f3dc/.bootstrap/_pex/pex.py", line 349, in execute E exit_code = self._wrap_coverage(self._wrap_profiling, self._execute) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/run/py/CPython-2.7.10/a8a8db2fdd4fae99b02f6010a93d6f6dc4f9f3dc/.bootstrap/_pex/pex.py", line 281, in _wrap_coverage E return runner(*args) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/run/py/CPython-2.7.10/a8a8db2fdd4fae99b02f6010a93d6f6dc4f9f3dc/.bootstrap/_pex/pex.py", line 312, in _wrap_profiling E return runner(*args) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/run/py/CPython-2.7.10/a8a8db2fdd4fae99b02f6010a93d6f6dc4f9f3dc/.bootstrap/_pex/pex.py", line 394, in _execute E return self.execute_entry(self._pex_info.entry_point) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/run/py/CPython-2.7.10/a8a8db2fdd4fae99b02f6010a93d6f6dc4f9f3dc/.bootstrap/_pex/pex.py", line 506, in execute_entry E return runner(entry_point) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/run/py/CPython-2.7.10/a8a8db2fdd4fae99b02f6010a93d6f6dc4f9f3dc/.bootstrap/_pex/pex.py", line 513, in execute_module E runpy.run_module(module_name, run_name='__main__') E File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 180, in run_module E fname, loader, pkg_name) E File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 72, in _run_code E exec code in run_globals E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/pyprep/sources/46bc27ffbe03ecfe648c4d677289275aa6a6a93c-DefaultFingerprintStrategy_1b8903baa709/python_distribution/ctypes_with_third_party/main.py", line 7, in <module> E from ctypes_python_pkg.ctypes_wrapper import f E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/pyprep/requirements/CPython-2.7.10/dbfa0d2bb6877c576abca571691b6e7c8432a15a-DefaultFingerprintStrategy_25eb7243d755/.deps/ctypes_third_party_test-0.0.1+20865c6b4968b7f61c37fdc3ed80306ee2ca4a3e.defaultfingerprintstrategy.174c3658bd6c.8f03fa43ba4e-py2-none-macosx_10_13_x86_64.whl/ctypes_python_pkg/ctypes_wrapper.py", line 20, in <module> E asdf_cpp_lib = ctypes.CDLL(asdf_cpp_lib_path) E File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ctypes/__init__.py", line 365, in __init__ E self._handle = _dlopen(self._name, mode) E OSError: dlopen(/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/pyprep/requirements/CPython-2.7.10/dbfa0d2bb6877c576abca571691b6e7c8432a15a-DefaultFingerprintStrategy_25eb7243d755/.deps/ctypes_third_party_test-0.0.1+20865c6b4968b7f61c37fdc3ed80306ee2ca4a3e.defaultfingerprintstrategy.174c3658bd6c.8f03fa43ba4e-py2-none-macosx_10_13_x86_64.whl/libasdf-cpp_ctypes-with-third-party.so, 6): Library not loaded: /Users/stuhood/src/pantsbuild-binaries/build-support/bin/gcc/mac/10.13/7.3.0/gcc-7.3.0-osx/gcc-install/lib/libstdc++.6.dylib E Referenced from: /Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/pyprep/requirements/CPython-2.7.10/dbfa0d2bb6877c576abca571691b6e7c8432a15a-DefaultFingerprintStrategy_25eb7243d755/.deps/ctypes_third_party_test-0.0.1+20865c6b4968b7f61c37fdc3ed80306ee2ca4a3e.defaultfingerprintstrategy.174c3658bd6c.8f03fa43ba4e-py2-none-macosx_10_13_x86_64.whl/libasdf-cpp_ctypes-with-third-party.so E Reason: image not found E E FAILURE -------------- Captured stdout call -------------- logs/exceptions.4006.log +++ logs/exceptions.4006.log --- logs/exceptions.log +++ logs/exceptions.log --- CTypesIntegrationTest.test_native_compiler_option_sets_integration args = (<pants_test.backend.python.tasks.native.test_ctypes_integration.CTypesIntegrationTest testMethod=test_native_compiler_option_sets_integration>,) kwargs = {} variant = ToolchainVariant(value=u'gnu') @wraps(func) def wrapper(*args, **kwargs): for variant in ToolchainVariant.iterate_enum_variants(): > func(*args, toolchain_variant=variant, **kwargs) .pants.d/pyprep/sources/68db53b799a649f3f92cbd3d3e740d9a1a47be07/pants_test/backend/python/tasks/native/test_ctypes_integration.py:32: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ .pants.d/pyprep/sources/68db53b799a649f3f92cbd3d3e740d9a1a47be07/pants_test/backend/python/tasks/native/test_ctypes_integration.py:246: in test_native_compiler_option_sets_integration self.assert_success(pants_run) .pants.d/pyprep/sources/68db53b799a649f3f92cbd3d3e740d9a1a47be07/pants_test/pants_run_integration_test.py:452: in assert_success self.assert_result(pants_run, self.PANTS_SUCCESS_CODE, expected=True, msg=msg) .pants.d/pyprep/sources/68db53b799a649f3f92cbd3d3e740d9a1a47be07/pants_test/pants_run_integration_test.py:473: in assert_result assertion(value, pants_run.returncode, error_msg) E AssertionError: /Users/travis/build/pantsbuild/pants/pants --no-pantsrc --pants-workdir=/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d --kill-nailguns --print-exception-stacktrace=True --pants-config-files=/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/pants.ini run testprojects/src/python/python_distribution/ctypes_with_extra_compiler_flags:bin E returncode: 1 E stdout: E E 16:40:21 00:00 [main] E (To run a reporting server: ./pants server) E 16:40:22 00:01 [setup] E 16:40:22 00:01 [parse] E Executing tasks in goals: bootstrap -> imports -> unpack-jars -> unpack-wheels -> deferred-sources -> native-compile -> link -> jvm-platform-validate -> gen -> pyprep -> resolve -> resources -> compile -> binary -> run E 16:40:23 00:02 [bootstrap] E 16:40:23 00:02 [substitute-aliased-targets] E 16:40:23 00:02 [jar-dependency-management] E 16:40:23 00:02 [bootstrap-jvm-tools] E 16:40:23 00:02 [provide-tools-jar] E 16:40:24 00:03 [imports] E 16:40:24 00:03 [ivy-imports] E 16:40:24 00:03 [unpack-jars] E 16:40:24 00:03 [unpack-jars] E 16:40:24 00:03 [unpack-wheels] E 16:40:24 00:03 [unpack-wheels] E 16:40:24 00:03 [deferred-sources] E 16:40:24 00:03 [deferred-sources] E 16:40:24 00:03 [native-compile] E 16:40:24 00:03 [conan-prep] E 16:40:24 00:03 [create-conan-pex] E 16:40:32 00:11 [conan-fetch] E 16:40:32 00:11 [c-for-ctypes] E 16:40:32 00:11 [cpp-for-ctypes] E Invalidated 1 target. E selected compiler exe name: 'g++' E 16:40:32 00:11 [cpp-compile] E E 16:40:33 00:12 [link] E 16:40:33 00:12 [shared-libraries] E Invalidated 1 target. E selected linker exe name: 'g++' E 16:40:33 00:12 [link-shared-libraries] E 16:40:33 00:12 [jvm-platform-validate] E 16:40:33 00:12 [jvm-platform-validate] E 16:40:33 00:12 [gen] E 16:40:33 00:12 [antlr-java] E 16:40:33 00:12 [antlr-py] E 16:40:33 00:12 [jaxb] E 16:40:33 00:12 [protoc] E 16:40:33 00:12 [ragel] E 16:40:33 00:12 [thrift-java] E 16:40:33 00:12 [thrift-py] E 16:40:33 00:12 [grpcio-prep] E 16:40:33 00:12 [grpcio-run] E 16:40:33 00:12 [wire] E 16:40:33 00:12 [avro-java] E 16:40:33 00:12 [go-thrift] E 16:40:33 00:12 [go-protobuf] E 16:40:33 00:12 [jax-ws] E 16:40:33 00:12 [scrooge] E 16:40:33 00:12 [thrifty] E 16:40:33 00:12 [pyprep] E 16:40:33 00:12 [interpreter] E 16:40:33 00:12 [build-local-dists] E Invalidated 1 target. E 16:40:35 00:14 [setup.py] E 16:40:35 00:14 [requirements] E Invalidated 1 target. E 16:40:36 00:15 [sources] E Invalidated 1 target. E 16:40:36 00:15 [resolve] E 16:40:36 00:15 [ivy] E 16:40:36 00:15 [coursier] E 16:40:36 00:15 [go] E 16:40:36 00:15 [scala-js-compile] E 16:40:36 00:15 [scala-js-link] E 16:40:37 00:16 [node] E 16:40:37 00:16 [resources] E 16:40:37 00:16 [prepare] E 16:40:37 00:16 [services] E 16:40:37 00:16 [compile] E 16:40:37 00:16 [node] E 16:40:37 00:16 [compile-jvm-prep-command] E 16:40:37 00:16 [jvm_prep_command] E 16:40:37 00:16 [compile-prep-command] E 16:40:37 00:16 [compile] E 16:40:37 00:16 [rsc] E 16:40:37 00:16 [zinc] E 16:40:37 00:16 [javac] E 16:40:37 00:16 [cpp] E 16:40:37 00:16 [errorprone] E 16:40:37 00:16 [findbugs] E 16:40:37 00:16 [go] E 16:40:37 00:16 [binary] E 16:40:37 00:16 [binary-jvm-prep-command] E 16:40:37 00:16 [jvm_prep_command] E 16:40:37 00:16 [binary-prep-command] E 16:40:37 00:16 [py] E Invalidated 1 target. E created pex dist/bin.pex E 16:40:38 00:17 [py-wheels] E created wheel dist/ctypes_test-0.0.1+74173b5ce60ddd85088b1fed70c8b071f2679604.defaultfingerprintstrategy.12652e89be0f.8f03fa43ba4e-py2-none-macosx_10_13_x86_64.whl E 16:40:38 00:17 [jvm] E 16:40:38 00:17 [dup] E 16:40:38 00:17 [cpplib] E 16:40:38 00:17 [cpp-library] E 16:40:38 00:17 [cpp] E 16:40:38 00:17 [cpp-binary] E 16:40:38 00:17 [go] E 16:40:38 00:17 [run] E 16:40:38 00:17 [py] E Invalidated 3 targets. E 16:40:39 00:18 [run] E E FAILURE: /usr/bin/python /Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/run/py/CPython-2.7.10/3784d4150334a9a89ddceb31bdb13969e94f73b2 ... exited non-zero (1) E E E Waiting for background workers to finish. E 16:40:39 00:18 [complete] E FAILURE E stderr: E Traceback (most recent call last): E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/run/py/CPython-2.7.10/3784d4150334a9a89ddceb31bdb13969e94f73b2/.bootstrap/_pex/pex.py", line 349, in execute E exit_code = self._wrap_coverage(self._wrap_profiling, self._execute) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/run/py/CPython-2.7.10/3784d4150334a9a89ddceb31bdb13969e94f73b2/.bootstrap/_pex/pex.py", line 281, in _wrap_coverage E return runner(*args) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/run/py/CPython-2.7.10/3784d4150334a9a89ddceb31bdb13969e94f73b2/.bootstrap/_pex/pex.py", line 312, in _wrap_profiling E return runner(*args) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/run/py/CPython-2.7.10/3784d4150334a9a89ddceb31bdb13969e94f73b2/.bootstrap/_pex/pex.py", line 394, in _execute E return self.execute_entry(self._pex_info.entry_point) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/run/py/CPython-2.7.10/3784d4150334a9a89ddceb31bdb13969e94f73b2/.bootstrap/_pex/pex.py", line 506, in execute_entry E return runner(entry_point) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/run/py/CPython-2.7.10/3784d4150334a9a89ddceb31bdb13969e94f73b2/.bootstrap/_pex/pex.py", line 513, in execute_module E runpy.run_module(module_name, run_name='__main__') E File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 180, in run_module E fname, loader, pkg_name) E File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 72, in _run_code E exec code in run_globals E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/pyprep/sources/be29db057705cafb8edc0e69942013e74ccffbe3-DefaultFingerprintStrategy_1b8903baa709/python_distribution/ctypes_with_extra_compiler_flags/main.py", line 7, in <module> E from ctypes_python_pkg.ctypes_wrapper import f E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/pyprep/requirements/CPython-2.7.10/2122a483545750a790ffdd2c65a8039affd3f167-DefaultFingerprintStrategy_25eb7243d755/.deps/ctypes_test-0.0.1+74173b5ce60ddd85088b1fed70c8b071f2679604.defaultfingerprintstrategy.12652e89be0f.8f03fa43ba4e-py2-none-macosx_10_13_x86_64.whl/ctypes_python_pkg/ctypes_wrapper.py", line 20, in <module> E asdf_cpp_lib = ctypes.CDLL(asdf_cpp_lib_path) E File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ctypes/__init__.py", line 365, in __init__ E self._handle = _dlopen(self._name, mode) E OSError: dlopen(/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/pyprep/requirements/CPython-2.7.10/2122a483545750a790ffdd2c65a8039affd3f167-DefaultFingerprintStrategy_25eb7243d755/.deps/ctypes_test-0.0.1+74173b5ce60ddd85088b1fed70c8b071f2679604.defaultfingerprintstrategy.12652e89be0f.8f03fa43ba4e-py2-none-macosx_10_13_x86_64.whl/libasdf-cpp_ctypes-with-extra-compiler-flags.so, 6): Library not loaded: /Users/stuhood/src/pantsbuild-binaries/build-support/bin/gcc/mac/10.13/7.3.0/gcc-7.3.0-osx/gcc-install/lib/libstdc++.6.dylib E Referenced from: /Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/pyprep/requirements/CPython-2.7.10/2122a483545750a790ffdd2c65a8039affd3f167-DefaultFingerprintStrategy_25eb7243d755/.deps/ctypes_test-0.0.1+74173b5ce60ddd85088b1fed70c8b071f2679604.defaultfingerprintstrategy.12652e89be0f.8f03fa43ba4e-py2-none-macosx_10_13_x86_64.whl/libasdf-cpp_ctypes-with-extra-compiler-flags.so E Reason: image not found -------------- Captured stdout call -------------- logs/exceptions.4063.log +++ logs/exceptions.4063.log --- logs/exceptions.log +++ logs/exceptions.log --- ====== 2 failed, 3 passed in 199.95 seconds ======
AssertionError
def enum(*args): """A datatype which can take on a finite set of values. This method is experimental and unstable. Any enum subclass can be constructed with its create() classmethod. This method will use the first element of `all_values` as the default value, but enum classes can override this behavior by setting `default_value` in the class body. NB: Relying on the `field_name` directly is discouraged in favor of using resolve_for_enum_variant() in Python code. The `field_name` argument is exposed to make enum instances more readable when printed, and to allow code in another language using an FFI to reliably extract the value from an enum instance. :param string field_name: A string used as the field for the datatype. This positional argument is optional, and defaults to 'value'. Note that `enum()` does not yet support type checking as with `datatype()`. :param Iterable all_values: A nonempty iterable of objects representing all possible values for the enum. This argument must be a finite, non-empty iterable with unique values. :raises: :class:`ValueError` """ if len(args) == 1: field_name = "value" (all_values,) = args elif len(args) == 2: field_name, all_values = args else: raise ValueError("enum() accepts only 1 or 2 args! args = {!r}".format(args)) # This call to list() will eagerly evaluate any `all_values` which would otherwise be lazy, such # as a generator. all_values_realized = list(all_values) # `OrderedSet` maintains the order of the input iterable, but is faster to check membership. allowed_values_set = OrderedSet(all_values_realized) if len(allowed_values_set) == 0: raise ValueError("all_values must be a non-empty iterable!") elif len(allowed_values_set) < len(all_values_realized): raise ValueError( "When converting all_values ({}) to a set, at least one duplicate " "was detected. The unique elements of all_values were: {}.".format( all_values_realized, list(allowed_values_set) ) ) class ChoiceDatatype(datatype([field_name])): default_value = next(iter(allowed_values_set)) # Overriden from datatype() so providing an invalid variant is catchable as a TypeCheckError, # but more specific. type_check_error_type = EnumVariantSelectionError @memoized_classproperty def _singletons(cls): """Generate memoized instances of this enum wrapping each of this enum's allowed values. NB: The implementation of enum() should use this property as the source of truth for allowed values and enum instances from those values. """ return OrderedDict( (value, cls._make_singleton(value)) for value in allowed_values_set ) @classmethod def _make_singleton(cls, value): """ We convert uses of the constructor to call create(), so we then need to go around __new__ to bootstrap singleton creation from datatype()'s __new__. """ return super(ChoiceDatatype, cls).__new__(cls, value) @classproperty def _allowed_values(cls): """The values provided to the enum() type constructor, for use in error messages.""" return list(cls._singletons.keys()) def __new__(cls, value): """Forward `value` to the .create() factory method. The .create() factory method is preferred, but forwarding the constructor like this allows us to use the generated enum type both as a type to check against with isinstance() as well as a function to create instances with. This makes it easy to use as a pants option type. """ return cls.create(value) # TODO: figure out if this will always trigger on primitives like strings, and what situations # won't call this __eq__ (and therefore won't raise like we want). def __eq__(self, other): """Redefine equality to raise to nudge people to use static pattern matching.""" raise self.make_type_error( "enum equality is defined to be an error -- use .resolve_for_enum_variant() instead!" ) # Redefine the canary so datatype __new__ doesn't raise. __eq__._eq_override_canary = None # NB: as noted in datatype(), __hash__ must be explicitly implemented whenever __eq__ is # overridden. See https://docs.python.org/3/reference/datamodel.html#object.__hash__. def __hash__(self): return super(ChoiceDatatype, self).__hash__() @classmethod def create(cls, *args, **kwargs): """Create an instance of this enum, using the default value if specified. :param value: Use this as the enum value. If `value` is an instance of this class, return it, otherwise it is checked against the enum's allowed values. This positional argument is optional, and if not specified, `cls.default_value` is used. :param bool none_is_default: If this is True, a None `value` is converted into `cls.default_value` before being checked against the enum's allowed values. """ none_is_default = kwargs.pop("none_is_default", False) if kwargs: raise ValueError( "unrecognized keyword arguments for {}.create(): {!r}".format( cls.__name__, kwargs ) ) if len(args) == 0: value = cls.default_value elif len(args) == 1: value = args[0] if none_is_default and value is None: value = cls.default_value else: raise ValueError( "{}.create() accepts 0 or 1 positional args! *args = {!r}".format( cls.__name__, args ) ) # If we get an instance of this enum class, just return it. This means you can call .create() # on an allowed value for the enum, or an existing instance of the enum. if isinstance(value, cls): return value if value not in cls._singletons: raise cls.make_type_error( "Value {!r} for '{}' must be one of: {!r}.".format( value, field_name, cls._allowed_values ) ) return cls._singletons[value] def resolve_for_enum_variant(self, mapping): """Return the object in `mapping` with the key corresponding to the enum value. `mapping` is a dict mapping enum variant value -> arbitrary object. All variant values must be provided. NB: The objects in `mapping` should be made into lambdas if lazy execution is desired, as this will "evaluate" all of the values in `mapping`. """ keys = frozenset(mapping.keys()) if keys != frozenset(self._allowed_values): raise self.make_type_error( "pattern matching must have exactly the keys {} (was: {})".format( self._allowed_values, list(keys) ) ) match_for_variant = mapping[getattr(self, field_name)] return match_for_variant @classmethod def iterate_enum_variants(cls): """Iterate over all instances of this enum, in the declared order. NB: This method is exposed for testing enum variants easily. resolve_for_enum_variant() should be used for performing conditional logic based on an enum instance's value. """ # TODO(#7232): use this method to register attributes on the generated type object for each of # the singletons! return cls._singletons.values() return ChoiceDatatype
def enum(*args): """A datatype which can take on a finite set of values. This method is experimental and unstable. Any enum subclass can be constructed with its create() classmethod. This method will use the first element of `all_values` as the default value, but enum classes can override this behavior by setting `default_value` in the class body. NB: Relying on the `field_name` directly is discouraged in favor of using resolve_for_enum_variant() in Python code. The `field_name` argument is exposed to make enum instances more readable when printed, and to allow code in another language using an FFI to reliably extract the value from an enum instance. :param string field_name: A string used as the field for the datatype. This positional argument is optional, and defaults to 'value'. Note that `enum()` does not yet support type checking as with `datatype()`. :param Iterable all_values: A nonempty iterable of objects representing all possible values for the enum. This argument must be a finite, non-empty iterable with unique values. :raises: :class:`ValueError` """ if len(args) == 1: field_name = "value" (all_values,) = args elif len(args) == 2: field_name, all_values = args else: raise ValueError("enum() accepts only 1 or 2 args! args = {!r}".format(args)) # This call to list() will eagerly evaluate any `all_values` which would otherwise be lazy, such # as a generator. all_values_realized = list(all_values) # `OrderedSet` maintains the order of the input iterable, but is faster to check membership. allowed_values_set = OrderedSet(all_values_realized) if len(allowed_values_set) == 0: raise ValueError("all_values must be a non-empty iterable!") elif len(allowed_values_set) < len(all_values_realized): raise ValueError( "When converting all_values ({}) to a set, at least one duplicate " "was detected. The unique elements of all_values were: {}.".format( all_values_realized, list(allowed_values_set) ) ) class ChoiceDatatype(datatype([field_name])): default_value = next(iter(allowed_values_set)) # Overriden from datatype() so providing an invalid variant is catchable as a TypeCheckError, # but more specific. type_check_error_type = EnumVariantSelectionError @memoized_classproperty def _singletons(cls): """Generate memoized instances of this enum wrapping each of this enum's allowed values. NB: The implementation of enum() should use this property as the source of truth for allowed values and enum instances from those values. """ return OrderedDict( (value, cls._make_singleton(value)) for value in allowed_values_set ) @classmethod def _make_singleton(cls, value): """ We convert uses of the constructor to call create(), so we then need to go around __new__ to bootstrap singleton creation from datatype()'s __new__. """ return super(ChoiceDatatype, cls).__new__(cls, value) @classproperty def _allowed_values(cls): """The values provided to the enum() type constructor, for use in error messages.""" return list(cls._singletons.keys()) def __new__(cls, value): """Forward `value` to the .create() factory method. The .create() factory method is preferred, but forwarding the constructor like this allows us to use the generated enum type both as a type to check against with isinstance() as well as a function to create instances with. This makes it easy to use as a pants option type. """ return cls.create(value) @classmethod def create(cls, *args, **kwargs): """Create an instance of this enum, using the default value if specified. :param value: Use this as the enum value. If `value` is an instance of this class, return it, otherwise it is checked against the enum's allowed values. This positional argument is optional, and if not specified, `cls.default_value` is used. :param bool none_is_default: If this is True, a None `value` is converted into `cls.default_value` before being checked against the enum's allowed values. """ none_is_default = kwargs.pop("none_is_default", False) if kwargs: raise ValueError( "unrecognized keyword arguments for {}.create(): {!r}".format( cls.__name__, kwargs ) ) if len(args) == 0: value = cls.default_value elif len(args) == 1: value = args[0] if none_is_default and value is None: value = cls.default_value else: raise ValueError( "{}.create() accepts 0 or 1 positional args! *args = {!r}".format( cls.__name__, args ) ) # If we get an instance of this enum class, just return it. This means you can call .create() # on an allowed value for the enum, or an existing instance of the enum. if isinstance(value, cls): return value if value not in cls._singletons: raise cls.make_type_error( "Value {!r} for '{}' must be one of: {!r}.".format( value, field_name, cls._allowed_values ) ) return cls._singletons[value] def resolve_for_enum_variant(self, mapping): """Return the object in `mapping` with the key corresponding to the enum value. `mapping` is a dict mapping enum variant value -> arbitrary object. All variant values must be provided. NB: The objects in `mapping` should be made into lambdas if lazy execution is desired, as this will "evaluate" all of the values in `mapping`. """ keys = frozenset(mapping.keys()) if keys != frozenset(self._allowed_values): raise self.make_type_error( "pattern matching must have exactly the keys {} (was: {})".format( self._allowed_values, list(keys) ) ) match_for_variant = mapping[getattr(self, field_name)] return match_for_variant @classmethod def iterate_enum_variants(cls): """Iterate over all instances of this enum, in the declared order. NB: This method is exposed for testing enum variants easily. resolve_for_enum_variant() should be used for performing conditional logic based on an enum instance's value. """ # TODO(#7232): use this method to register attributes on the generated type object for each of # the singletons! return cls._singletons.values() return ChoiceDatatype
https://github.com/pantsbuild/pants/issues/7247
==================== FAILURES ==================== CTypesIntegrationTest.test_ctypes_third_party_integration args = (<pants_test.backend.python.tasks.native.test_ctypes_integration.CTypesIntegrationTest testMethod=test_ctypes_third_party_integration>,) kwargs = {} variant = ToolchainVariant(value=u'gnu') @wraps(func) def wrapper(*args, **kwargs): for variant in ToolchainVariant.iterate_enum_variants(): > func(*args, toolchain_variant=variant, **kwargs) .pants.d/pyprep/sources/68db53b799a649f3f92cbd3d3e740d9a1a47be07/pants_test/backend/python/tasks/native/test_ctypes_integration.py:32: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ .pants.d/pyprep/sources/68db53b799a649f3f92cbd3d3e740d9a1a47be07/pants_test/backend/python/tasks/native/test_ctypes_integration.py:195: in test_ctypes_third_party_integration self.assert_success(pants_run) .pants.d/pyprep/sources/68db53b799a649f3f92cbd3d3e740d9a1a47be07/pants_test/pants_run_integration_test.py:452: in assert_success self.assert_result(pants_run, self.PANTS_SUCCESS_CODE, expected=True, msg=msg) .pants.d/pyprep/sources/68db53b799a649f3f92cbd3d3e740d9a1a47be07/pants_test/pants_run_integration_test.py:473: in assert_result assertion(value, pants_run.returncode, error_msg) E AssertionError: /Users/travis/build/pantsbuild/pants/pants --no-pantsrc --pants-workdir=/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d --kill-nailguns --print-exception-stacktrace=True --pants-config-files=/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/pants.ini -q run testprojects/src/python/python_distribution/ctypes_with_third_party:bin_with_third_party E returncode: 1 E stdout: E E FAILURE: /usr/bin/python /Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/run/py/CPython-2.7.10/a8a8db2fdd4fae99b02f6010a93d6f6dc4f9f3dc ... exited non-zero (1) E E stderr: E Traceback (most recent call last): E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/run/py/CPython-2.7.10/a8a8db2fdd4fae99b02f6010a93d6f6dc4f9f3dc/.bootstrap/_pex/pex.py", line 349, in execute E exit_code = self._wrap_coverage(self._wrap_profiling, self._execute) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/run/py/CPython-2.7.10/a8a8db2fdd4fae99b02f6010a93d6f6dc4f9f3dc/.bootstrap/_pex/pex.py", line 281, in _wrap_coverage E return runner(*args) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/run/py/CPython-2.7.10/a8a8db2fdd4fae99b02f6010a93d6f6dc4f9f3dc/.bootstrap/_pex/pex.py", line 312, in _wrap_profiling E return runner(*args) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/run/py/CPython-2.7.10/a8a8db2fdd4fae99b02f6010a93d6f6dc4f9f3dc/.bootstrap/_pex/pex.py", line 394, in _execute E return self.execute_entry(self._pex_info.entry_point) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/run/py/CPython-2.7.10/a8a8db2fdd4fae99b02f6010a93d6f6dc4f9f3dc/.bootstrap/_pex/pex.py", line 506, in execute_entry E return runner(entry_point) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/run/py/CPython-2.7.10/a8a8db2fdd4fae99b02f6010a93d6f6dc4f9f3dc/.bootstrap/_pex/pex.py", line 513, in execute_module E runpy.run_module(module_name, run_name='__main__') E File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 180, in run_module E fname, loader, pkg_name) E File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 72, in _run_code E exec code in run_globals E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/pyprep/sources/46bc27ffbe03ecfe648c4d677289275aa6a6a93c-DefaultFingerprintStrategy_1b8903baa709/python_distribution/ctypes_with_third_party/main.py", line 7, in <module> E from ctypes_python_pkg.ctypes_wrapper import f E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/pyprep/requirements/CPython-2.7.10/dbfa0d2bb6877c576abca571691b6e7c8432a15a-DefaultFingerprintStrategy_25eb7243d755/.deps/ctypes_third_party_test-0.0.1+20865c6b4968b7f61c37fdc3ed80306ee2ca4a3e.defaultfingerprintstrategy.174c3658bd6c.8f03fa43ba4e-py2-none-macosx_10_13_x86_64.whl/ctypes_python_pkg/ctypes_wrapper.py", line 20, in <module> E asdf_cpp_lib = ctypes.CDLL(asdf_cpp_lib_path) E File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ctypes/__init__.py", line 365, in __init__ E self._handle = _dlopen(self._name, mode) E OSError: dlopen(/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/pyprep/requirements/CPython-2.7.10/dbfa0d2bb6877c576abca571691b6e7c8432a15a-DefaultFingerprintStrategy_25eb7243d755/.deps/ctypes_third_party_test-0.0.1+20865c6b4968b7f61c37fdc3ed80306ee2ca4a3e.defaultfingerprintstrategy.174c3658bd6c.8f03fa43ba4e-py2-none-macosx_10_13_x86_64.whl/libasdf-cpp_ctypes-with-third-party.so, 6): Library not loaded: /Users/stuhood/src/pantsbuild-binaries/build-support/bin/gcc/mac/10.13/7.3.0/gcc-7.3.0-osx/gcc-install/lib/libstdc++.6.dylib E Referenced from: /Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/pyprep/requirements/CPython-2.7.10/dbfa0d2bb6877c576abca571691b6e7c8432a15a-DefaultFingerprintStrategy_25eb7243d755/.deps/ctypes_third_party_test-0.0.1+20865c6b4968b7f61c37fdc3ed80306ee2ca4a3e.defaultfingerprintstrategy.174c3658bd6c.8f03fa43ba4e-py2-none-macosx_10_13_x86_64.whl/libasdf-cpp_ctypes-with-third-party.so E Reason: image not found E E FAILURE -------------- Captured stdout call -------------- logs/exceptions.4006.log +++ logs/exceptions.4006.log --- logs/exceptions.log +++ logs/exceptions.log --- CTypesIntegrationTest.test_native_compiler_option_sets_integration args = (<pants_test.backend.python.tasks.native.test_ctypes_integration.CTypesIntegrationTest testMethod=test_native_compiler_option_sets_integration>,) kwargs = {} variant = ToolchainVariant(value=u'gnu') @wraps(func) def wrapper(*args, **kwargs): for variant in ToolchainVariant.iterate_enum_variants(): > func(*args, toolchain_variant=variant, **kwargs) .pants.d/pyprep/sources/68db53b799a649f3f92cbd3d3e740d9a1a47be07/pants_test/backend/python/tasks/native/test_ctypes_integration.py:32: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ .pants.d/pyprep/sources/68db53b799a649f3f92cbd3d3e740d9a1a47be07/pants_test/backend/python/tasks/native/test_ctypes_integration.py:246: in test_native_compiler_option_sets_integration self.assert_success(pants_run) .pants.d/pyprep/sources/68db53b799a649f3f92cbd3d3e740d9a1a47be07/pants_test/pants_run_integration_test.py:452: in assert_success self.assert_result(pants_run, self.PANTS_SUCCESS_CODE, expected=True, msg=msg) .pants.d/pyprep/sources/68db53b799a649f3f92cbd3d3e740d9a1a47be07/pants_test/pants_run_integration_test.py:473: in assert_result assertion(value, pants_run.returncode, error_msg) E AssertionError: /Users/travis/build/pantsbuild/pants/pants --no-pantsrc --pants-workdir=/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d --kill-nailguns --print-exception-stacktrace=True --pants-config-files=/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/pants.ini run testprojects/src/python/python_distribution/ctypes_with_extra_compiler_flags:bin E returncode: 1 E stdout: E E 16:40:21 00:00 [main] E (To run a reporting server: ./pants server) E 16:40:22 00:01 [setup] E 16:40:22 00:01 [parse] E Executing tasks in goals: bootstrap -> imports -> unpack-jars -> unpack-wheels -> deferred-sources -> native-compile -> link -> jvm-platform-validate -> gen -> pyprep -> resolve -> resources -> compile -> binary -> run E 16:40:23 00:02 [bootstrap] E 16:40:23 00:02 [substitute-aliased-targets] E 16:40:23 00:02 [jar-dependency-management] E 16:40:23 00:02 [bootstrap-jvm-tools] E 16:40:23 00:02 [provide-tools-jar] E 16:40:24 00:03 [imports] E 16:40:24 00:03 [ivy-imports] E 16:40:24 00:03 [unpack-jars] E 16:40:24 00:03 [unpack-jars] E 16:40:24 00:03 [unpack-wheels] E 16:40:24 00:03 [unpack-wheels] E 16:40:24 00:03 [deferred-sources] E 16:40:24 00:03 [deferred-sources] E 16:40:24 00:03 [native-compile] E 16:40:24 00:03 [conan-prep] E 16:40:24 00:03 [create-conan-pex] E 16:40:32 00:11 [conan-fetch] E 16:40:32 00:11 [c-for-ctypes] E 16:40:32 00:11 [cpp-for-ctypes] E Invalidated 1 target. E selected compiler exe name: 'g++' E 16:40:32 00:11 [cpp-compile] E E 16:40:33 00:12 [link] E 16:40:33 00:12 [shared-libraries] E Invalidated 1 target. E selected linker exe name: 'g++' E 16:40:33 00:12 [link-shared-libraries] E 16:40:33 00:12 [jvm-platform-validate] E 16:40:33 00:12 [jvm-platform-validate] E 16:40:33 00:12 [gen] E 16:40:33 00:12 [antlr-java] E 16:40:33 00:12 [antlr-py] E 16:40:33 00:12 [jaxb] E 16:40:33 00:12 [protoc] E 16:40:33 00:12 [ragel] E 16:40:33 00:12 [thrift-java] E 16:40:33 00:12 [thrift-py] E 16:40:33 00:12 [grpcio-prep] E 16:40:33 00:12 [grpcio-run] E 16:40:33 00:12 [wire] E 16:40:33 00:12 [avro-java] E 16:40:33 00:12 [go-thrift] E 16:40:33 00:12 [go-protobuf] E 16:40:33 00:12 [jax-ws] E 16:40:33 00:12 [scrooge] E 16:40:33 00:12 [thrifty] E 16:40:33 00:12 [pyprep] E 16:40:33 00:12 [interpreter] E 16:40:33 00:12 [build-local-dists] E Invalidated 1 target. E 16:40:35 00:14 [setup.py] E 16:40:35 00:14 [requirements] E Invalidated 1 target. E 16:40:36 00:15 [sources] E Invalidated 1 target. E 16:40:36 00:15 [resolve] E 16:40:36 00:15 [ivy] E 16:40:36 00:15 [coursier] E 16:40:36 00:15 [go] E 16:40:36 00:15 [scala-js-compile] E 16:40:36 00:15 [scala-js-link] E 16:40:37 00:16 [node] E 16:40:37 00:16 [resources] E 16:40:37 00:16 [prepare] E 16:40:37 00:16 [services] E 16:40:37 00:16 [compile] E 16:40:37 00:16 [node] E 16:40:37 00:16 [compile-jvm-prep-command] E 16:40:37 00:16 [jvm_prep_command] E 16:40:37 00:16 [compile-prep-command] E 16:40:37 00:16 [compile] E 16:40:37 00:16 [rsc] E 16:40:37 00:16 [zinc] E 16:40:37 00:16 [javac] E 16:40:37 00:16 [cpp] E 16:40:37 00:16 [errorprone] E 16:40:37 00:16 [findbugs] E 16:40:37 00:16 [go] E 16:40:37 00:16 [binary] E 16:40:37 00:16 [binary-jvm-prep-command] E 16:40:37 00:16 [jvm_prep_command] E 16:40:37 00:16 [binary-prep-command] E 16:40:37 00:16 [py] E Invalidated 1 target. E created pex dist/bin.pex E 16:40:38 00:17 [py-wheels] E created wheel dist/ctypes_test-0.0.1+74173b5ce60ddd85088b1fed70c8b071f2679604.defaultfingerprintstrategy.12652e89be0f.8f03fa43ba4e-py2-none-macosx_10_13_x86_64.whl E 16:40:38 00:17 [jvm] E 16:40:38 00:17 [dup] E 16:40:38 00:17 [cpplib] E 16:40:38 00:17 [cpp-library] E 16:40:38 00:17 [cpp] E 16:40:38 00:17 [cpp-binary] E 16:40:38 00:17 [go] E 16:40:38 00:17 [run] E 16:40:38 00:17 [py] E Invalidated 3 targets. E 16:40:39 00:18 [run] E E FAILURE: /usr/bin/python /Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/run/py/CPython-2.7.10/3784d4150334a9a89ddceb31bdb13969e94f73b2 ... exited non-zero (1) E E E Waiting for background workers to finish. E 16:40:39 00:18 [complete] E FAILURE E stderr: E Traceback (most recent call last): E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/run/py/CPython-2.7.10/3784d4150334a9a89ddceb31bdb13969e94f73b2/.bootstrap/_pex/pex.py", line 349, in execute E exit_code = self._wrap_coverage(self._wrap_profiling, self._execute) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/run/py/CPython-2.7.10/3784d4150334a9a89ddceb31bdb13969e94f73b2/.bootstrap/_pex/pex.py", line 281, in _wrap_coverage E return runner(*args) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/run/py/CPython-2.7.10/3784d4150334a9a89ddceb31bdb13969e94f73b2/.bootstrap/_pex/pex.py", line 312, in _wrap_profiling E return runner(*args) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/run/py/CPython-2.7.10/3784d4150334a9a89ddceb31bdb13969e94f73b2/.bootstrap/_pex/pex.py", line 394, in _execute E return self.execute_entry(self._pex_info.entry_point) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/run/py/CPython-2.7.10/3784d4150334a9a89ddceb31bdb13969e94f73b2/.bootstrap/_pex/pex.py", line 506, in execute_entry E return runner(entry_point) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/run/py/CPython-2.7.10/3784d4150334a9a89ddceb31bdb13969e94f73b2/.bootstrap/_pex/pex.py", line 513, in execute_module E runpy.run_module(module_name, run_name='__main__') E File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 180, in run_module E fname, loader, pkg_name) E File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 72, in _run_code E exec code in run_globals E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/pyprep/sources/be29db057705cafb8edc0e69942013e74ccffbe3-DefaultFingerprintStrategy_1b8903baa709/python_distribution/ctypes_with_extra_compiler_flags/main.py", line 7, in <module> E from ctypes_python_pkg.ctypes_wrapper import f E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/pyprep/requirements/CPython-2.7.10/2122a483545750a790ffdd2c65a8039affd3f167-DefaultFingerprintStrategy_25eb7243d755/.deps/ctypes_test-0.0.1+74173b5ce60ddd85088b1fed70c8b071f2679604.defaultfingerprintstrategy.12652e89be0f.8f03fa43ba4e-py2-none-macosx_10_13_x86_64.whl/ctypes_python_pkg/ctypes_wrapper.py", line 20, in <module> E asdf_cpp_lib = ctypes.CDLL(asdf_cpp_lib_path) E File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ctypes/__init__.py", line 365, in __init__ E self._handle = _dlopen(self._name, mode) E OSError: dlopen(/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/pyprep/requirements/CPython-2.7.10/2122a483545750a790ffdd2c65a8039affd3f167-DefaultFingerprintStrategy_25eb7243d755/.deps/ctypes_test-0.0.1+74173b5ce60ddd85088b1fed70c8b071f2679604.defaultfingerprintstrategy.12652e89be0f.8f03fa43ba4e-py2-none-macosx_10_13_x86_64.whl/libasdf-cpp_ctypes-with-extra-compiler-flags.so, 6): Library not loaded: /Users/stuhood/src/pantsbuild-binaries/build-support/bin/gcc/mac/10.13/7.3.0/gcc-7.3.0-osx/gcc-install/lib/libstdc++.6.dylib E Referenced from: /Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/pyprep/requirements/CPython-2.7.10/2122a483545750a790ffdd2c65a8039affd3f167-DefaultFingerprintStrategy_25eb7243d755/.deps/ctypes_test-0.0.1+74173b5ce60ddd85088b1fed70c8b071f2679604.defaultfingerprintstrategy.12652e89be0f.8f03fa43ba4e-py2-none-macosx_10_13_x86_64.whl/libasdf-cpp_ctypes-with-extra-compiler-flags.so E Reason: image not found -------------- Captured stdout call -------------- logs/exceptions.4063.log +++ logs/exceptions.4063.log --- logs/exceptions.log +++ logs/exceptions.log --- ====== 2 failed, 3 passed in 199.95 seconds ======
AssertionError
def __hash__(self): return super(ChoiceDatatype, self).__hash__()
def __hash__(self): return super(DataType, self).__hash__()
https://github.com/pantsbuild/pants/issues/7247
==================== FAILURES ==================== CTypesIntegrationTest.test_ctypes_third_party_integration args = (<pants_test.backend.python.tasks.native.test_ctypes_integration.CTypesIntegrationTest testMethod=test_ctypes_third_party_integration>,) kwargs = {} variant = ToolchainVariant(value=u'gnu') @wraps(func) def wrapper(*args, **kwargs): for variant in ToolchainVariant.iterate_enum_variants(): > func(*args, toolchain_variant=variant, **kwargs) .pants.d/pyprep/sources/68db53b799a649f3f92cbd3d3e740d9a1a47be07/pants_test/backend/python/tasks/native/test_ctypes_integration.py:32: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ .pants.d/pyprep/sources/68db53b799a649f3f92cbd3d3e740d9a1a47be07/pants_test/backend/python/tasks/native/test_ctypes_integration.py:195: in test_ctypes_third_party_integration self.assert_success(pants_run) .pants.d/pyprep/sources/68db53b799a649f3f92cbd3d3e740d9a1a47be07/pants_test/pants_run_integration_test.py:452: in assert_success self.assert_result(pants_run, self.PANTS_SUCCESS_CODE, expected=True, msg=msg) .pants.d/pyprep/sources/68db53b799a649f3f92cbd3d3e740d9a1a47be07/pants_test/pants_run_integration_test.py:473: in assert_result assertion(value, pants_run.returncode, error_msg) E AssertionError: /Users/travis/build/pantsbuild/pants/pants --no-pantsrc --pants-workdir=/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d --kill-nailguns --print-exception-stacktrace=True --pants-config-files=/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/pants.ini -q run testprojects/src/python/python_distribution/ctypes_with_third_party:bin_with_third_party E returncode: 1 E stdout: E E FAILURE: /usr/bin/python /Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/run/py/CPython-2.7.10/a8a8db2fdd4fae99b02f6010a93d6f6dc4f9f3dc ... exited non-zero (1) E E stderr: E Traceback (most recent call last): E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/run/py/CPython-2.7.10/a8a8db2fdd4fae99b02f6010a93d6f6dc4f9f3dc/.bootstrap/_pex/pex.py", line 349, in execute E exit_code = self._wrap_coverage(self._wrap_profiling, self._execute) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/run/py/CPython-2.7.10/a8a8db2fdd4fae99b02f6010a93d6f6dc4f9f3dc/.bootstrap/_pex/pex.py", line 281, in _wrap_coverage E return runner(*args) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/run/py/CPython-2.7.10/a8a8db2fdd4fae99b02f6010a93d6f6dc4f9f3dc/.bootstrap/_pex/pex.py", line 312, in _wrap_profiling E return runner(*args) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/run/py/CPython-2.7.10/a8a8db2fdd4fae99b02f6010a93d6f6dc4f9f3dc/.bootstrap/_pex/pex.py", line 394, in _execute E return self.execute_entry(self._pex_info.entry_point) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/run/py/CPython-2.7.10/a8a8db2fdd4fae99b02f6010a93d6f6dc4f9f3dc/.bootstrap/_pex/pex.py", line 506, in execute_entry E return runner(entry_point) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/run/py/CPython-2.7.10/a8a8db2fdd4fae99b02f6010a93d6f6dc4f9f3dc/.bootstrap/_pex/pex.py", line 513, in execute_module E runpy.run_module(module_name, run_name='__main__') E File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 180, in run_module E fname, loader, pkg_name) E File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 72, in _run_code E exec code in run_globals E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/pyprep/sources/46bc27ffbe03ecfe648c4d677289275aa6a6a93c-DefaultFingerprintStrategy_1b8903baa709/python_distribution/ctypes_with_third_party/main.py", line 7, in <module> E from ctypes_python_pkg.ctypes_wrapper import f E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/pyprep/requirements/CPython-2.7.10/dbfa0d2bb6877c576abca571691b6e7c8432a15a-DefaultFingerprintStrategy_25eb7243d755/.deps/ctypes_third_party_test-0.0.1+20865c6b4968b7f61c37fdc3ed80306ee2ca4a3e.defaultfingerprintstrategy.174c3658bd6c.8f03fa43ba4e-py2-none-macosx_10_13_x86_64.whl/ctypes_python_pkg/ctypes_wrapper.py", line 20, in <module> E asdf_cpp_lib = ctypes.CDLL(asdf_cpp_lib_path) E File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ctypes/__init__.py", line 365, in __init__ E self._handle = _dlopen(self._name, mode) E OSError: dlopen(/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/pyprep/requirements/CPython-2.7.10/dbfa0d2bb6877c576abca571691b6e7c8432a15a-DefaultFingerprintStrategy_25eb7243d755/.deps/ctypes_third_party_test-0.0.1+20865c6b4968b7f61c37fdc3ed80306ee2ca4a3e.defaultfingerprintstrategy.174c3658bd6c.8f03fa43ba4e-py2-none-macosx_10_13_x86_64.whl/libasdf-cpp_ctypes-with-third-party.so, 6): Library not loaded: /Users/stuhood/src/pantsbuild-binaries/build-support/bin/gcc/mac/10.13/7.3.0/gcc-7.3.0-osx/gcc-install/lib/libstdc++.6.dylib E Referenced from: /Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/pyprep/requirements/CPython-2.7.10/dbfa0d2bb6877c576abca571691b6e7c8432a15a-DefaultFingerprintStrategy_25eb7243d755/.deps/ctypes_third_party_test-0.0.1+20865c6b4968b7f61c37fdc3ed80306ee2ca4a3e.defaultfingerprintstrategy.174c3658bd6c.8f03fa43ba4e-py2-none-macosx_10_13_x86_64.whl/libasdf-cpp_ctypes-with-third-party.so E Reason: image not found E E FAILURE -------------- Captured stdout call -------------- logs/exceptions.4006.log +++ logs/exceptions.4006.log --- logs/exceptions.log +++ logs/exceptions.log --- CTypesIntegrationTest.test_native_compiler_option_sets_integration args = (<pants_test.backend.python.tasks.native.test_ctypes_integration.CTypesIntegrationTest testMethod=test_native_compiler_option_sets_integration>,) kwargs = {} variant = ToolchainVariant(value=u'gnu') @wraps(func) def wrapper(*args, **kwargs): for variant in ToolchainVariant.iterate_enum_variants(): > func(*args, toolchain_variant=variant, **kwargs) .pants.d/pyprep/sources/68db53b799a649f3f92cbd3d3e740d9a1a47be07/pants_test/backend/python/tasks/native/test_ctypes_integration.py:32: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ .pants.d/pyprep/sources/68db53b799a649f3f92cbd3d3e740d9a1a47be07/pants_test/backend/python/tasks/native/test_ctypes_integration.py:246: in test_native_compiler_option_sets_integration self.assert_success(pants_run) .pants.d/pyprep/sources/68db53b799a649f3f92cbd3d3e740d9a1a47be07/pants_test/pants_run_integration_test.py:452: in assert_success self.assert_result(pants_run, self.PANTS_SUCCESS_CODE, expected=True, msg=msg) .pants.d/pyprep/sources/68db53b799a649f3f92cbd3d3e740d9a1a47be07/pants_test/pants_run_integration_test.py:473: in assert_result assertion(value, pants_run.returncode, error_msg) E AssertionError: /Users/travis/build/pantsbuild/pants/pants --no-pantsrc --pants-workdir=/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d --kill-nailguns --print-exception-stacktrace=True --pants-config-files=/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/pants.ini run testprojects/src/python/python_distribution/ctypes_with_extra_compiler_flags:bin E returncode: 1 E stdout: E E 16:40:21 00:00 [main] E (To run a reporting server: ./pants server) E 16:40:22 00:01 [setup] E 16:40:22 00:01 [parse] E Executing tasks in goals: bootstrap -> imports -> unpack-jars -> unpack-wheels -> deferred-sources -> native-compile -> link -> jvm-platform-validate -> gen -> pyprep -> resolve -> resources -> compile -> binary -> run E 16:40:23 00:02 [bootstrap] E 16:40:23 00:02 [substitute-aliased-targets] E 16:40:23 00:02 [jar-dependency-management] E 16:40:23 00:02 [bootstrap-jvm-tools] E 16:40:23 00:02 [provide-tools-jar] E 16:40:24 00:03 [imports] E 16:40:24 00:03 [ivy-imports] E 16:40:24 00:03 [unpack-jars] E 16:40:24 00:03 [unpack-jars] E 16:40:24 00:03 [unpack-wheels] E 16:40:24 00:03 [unpack-wheels] E 16:40:24 00:03 [deferred-sources] E 16:40:24 00:03 [deferred-sources] E 16:40:24 00:03 [native-compile] E 16:40:24 00:03 [conan-prep] E 16:40:24 00:03 [create-conan-pex] E 16:40:32 00:11 [conan-fetch] E 16:40:32 00:11 [c-for-ctypes] E 16:40:32 00:11 [cpp-for-ctypes] E Invalidated 1 target. E selected compiler exe name: 'g++' E 16:40:32 00:11 [cpp-compile] E E 16:40:33 00:12 [link] E 16:40:33 00:12 [shared-libraries] E Invalidated 1 target. E selected linker exe name: 'g++' E 16:40:33 00:12 [link-shared-libraries] E 16:40:33 00:12 [jvm-platform-validate] E 16:40:33 00:12 [jvm-platform-validate] E 16:40:33 00:12 [gen] E 16:40:33 00:12 [antlr-java] E 16:40:33 00:12 [antlr-py] E 16:40:33 00:12 [jaxb] E 16:40:33 00:12 [protoc] E 16:40:33 00:12 [ragel] E 16:40:33 00:12 [thrift-java] E 16:40:33 00:12 [thrift-py] E 16:40:33 00:12 [grpcio-prep] E 16:40:33 00:12 [grpcio-run] E 16:40:33 00:12 [wire] E 16:40:33 00:12 [avro-java] E 16:40:33 00:12 [go-thrift] E 16:40:33 00:12 [go-protobuf] E 16:40:33 00:12 [jax-ws] E 16:40:33 00:12 [scrooge] E 16:40:33 00:12 [thrifty] E 16:40:33 00:12 [pyprep] E 16:40:33 00:12 [interpreter] E 16:40:33 00:12 [build-local-dists] E Invalidated 1 target. E 16:40:35 00:14 [setup.py] E 16:40:35 00:14 [requirements] E Invalidated 1 target. E 16:40:36 00:15 [sources] E Invalidated 1 target. E 16:40:36 00:15 [resolve] E 16:40:36 00:15 [ivy] E 16:40:36 00:15 [coursier] E 16:40:36 00:15 [go] E 16:40:36 00:15 [scala-js-compile] E 16:40:36 00:15 [scala-js-link] E 16:40:37 00:16 [node] E 16:40:37 00:16 [resources] E 16:40:37 00:16 [prepare] E 16:40:37 00:16 [services] E 16:40:37 00:16 [compile] E 16:40:37 00:16 [node] E 16:40:37 00:16 [compile-jvm-prep-command] E 16:40:37 00:16 [jvm_prep_command] E 16:40:37 00:16 [compile-prep-command] E 16:40:37 00:16 [compile] E 16:40:37 00:16 [rsc] E 16:40:37 00:16 [zinc] E 16:40:37 00:16 [javac] E 16:40:37 00:16 [cpp] E 16:40:37 00:16 [errorprone] E 16:40:37 00:16 [findbugs] E 16:40:37 00:16 [go] E 16:40:37 00:16 [binary] E 16:40:37 00:16 [binary-jvm-prep-command] E 16:40:37 00:16 [jvm_prep_command] E 16:40:37 00:16 [binary-prep-command] E 16:40:37 00:16 [py] E Invalidated 1 target. E created pex dist/bin.pex E 16:40:38 00:17 [py-wheels] E created wheel dist/ctypes_test-0.0.1+74173b5ce60ddd85088b1fed70c8b071f2679604.defaultfingerprintstrategy.12652e89be0f.8f03fa43ba4e-py2-none-macosx_10_13_x86_64.whl E 16:40:38 00:17 [jvm] E 16:40:38 00:17 [dup] E 16:40:38 00:17 [cpplib] E 16:40:38 00:17 [cpp-library] E 16:40:38 00:17 [cpp] E 16:40:38 00:17 [cpp-binary] E 16:40:38 00:17 [go] E 16:40:38 00:17 [run] E 16:40:38 00:17 [py] E Invalidated 3 targets. E 16:40:39 00:18 [run] E E FAILURE: /usr/bin/python /Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/run/py/CPython-2.7.10/3784d4150334a9a89ddceb31bdb13969e94f73b2 ... exited non-zero (1) E E E Waiting for background workers to finish. E 16:40:39 00:18 [complete] E FAILURE E stderr: E Traceback (most recent call last): E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/run/py/CPython-2.7.10/3784d4150334a9a89ddceb31bdb13969e94f73b2/.bootstrap/_pex/pex.py", line 349, in execute E exit_code = self._wrap_coverage(self._wrap_profiling, self._execute) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/run/py/CPython-2.7.10/3784d4150334a9a89ddceb31bdb13969e94f73b2/.bootstrap/_pex/pex.py", line 281, in _wrap_coverage E return runner(*args) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/run/py/CPython-2.7.10/3784d4150334a9a89ddceb31bdb13969e94f73b2/.bootstrap/_pex/pex.py", line 312, in _wrap_profiling E return runner(*args) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/run/py/CPython-2.7.10/3784d4150334a9a89ddceb31bdb13969e94f73b2/.bootstrap/_pex/pex.py", line 394, in _execute E return self.execute_entry(self._pex_info.entry_point) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/run/py/CPython-2.7.10/3784d4150334a9a89ddceb31bdb13969e94f73b2/.bootstrap/_pex/pex.py", line 506, in execute_entry E return runner(entry_point) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/run/py/CPython-2.7.10/3784d4150334a9a89ddceb31bdb13969e94f73b2/.bootstrap/_pex/pex.py", line 513, in execute_module E runpy.run_module(module_name, run_name='__main__') E File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 180, in run_module E fname, loader, pkg_name) E File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 72, in _run_code E exec code in run_globals E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/pyprep/sources/be29db057705cafb8edc0e69942013e74ccffbe3-DefaultFingerprintStrategy_1b8903baa709/python_distribution/ctypes_with_extra_compiler_flags/main.py", line 7, in <module> E from ctypes_python_pkg.ctypes_wrapper import f E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/pyprep/requirements/CPython-2.7.10/2122a483545750a790ffdd2c65a8039affd3f167-DefaultFingerprintStrategy_25eb7243d755/.deps/ctypes_test-0.0.1+74173b5ce60ddd85088b1fed70c8b071f2679604.defaultfingerprintstrategy.12652e89be0f.8f03fa43ba4e-py2-none-macosx_10_13_x86_64.whl/ctypes_python_pkg/ctypes_wrapper.py", line 20, in <module> E asdf_cpp_lib = ctypes.CDLL(asdf_cpp_lib_path) E File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ctypes/__init__.py", line 365, in __init__ E self._handle = _dlopen(self._name, mode) E OSError: dlopen(/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/pyprep/requirements/CPython-2.7.10/2122a483545750a790ffdd2c65a8039affd3f167-DefaultFingerprintStrategy_25eb7243d755/.deps/ctypes_test-0.0.1+74173b5ce60ddd85088b1fed70c8b071f2679604.defaultfingerprintstrategy.12652e89be0f.8f03fa43ba4e-py2-none-macosx_10_13_x86_64.whl/libasdf-cpp_ctypes-with-extra-compiler-flags.so, 6): Library not loaded: /Users/stuhood/src/pantsbuild-binaries/build-support/bin/gcc/mac/10.13/7.3.0/gcc-7.3.0-osx/gcc-install/lib/libstdc++.6.dylib E Referenced from: /Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/pyprep/requirements/CPython-2.7.10/2122a483545750a790ffdd2c65a8039affd3f167-DefaultFingerprintStrategy_25eb7243d755/.deps/ctypes_test-0.0.1+74173b5ce60ddd85088b1fed70c8b071f2679604.defaultfingerprintstrategy.12652e89be0f.8f03fa43ba4e-py2-none-macosx_10_13_x86_64.whl/libasdf-cpp_ctypes-with-extra-compiler-flags.so E Reason: image not found -------------- Captured stdout call -------------- logs/exceptions.4063.log +++ logs/exceptions.4063.log --- logs/exceptions.log +++ logs/exceptions.log --- ====== 2 failed, 3 passed in 199.95 seconds ======
AssertionError
def __eq__(self, other): """Redefine equality to raise to nudge people to use static pattern matching.""" raise self.make_type_error( "enum equality is defined to be an error -- use .resolve_for_enum_variant() instead!" )
def __eq__(self, other): if self is other: return True # Compare types and fields. if type(self) != type(other): return False # Explicitly return super.__eq__'s value in case super returns NotImplemented return super(DataType, self).__eq__(other)
https://github.com/pantsbuild/pants/issues/7247
==================== FAILURES ==================== CTypesIntegrationTest.test_ctypes_third_party_integration args = (<pants_test.backend.python.tasks.native.test_ctypes_integration.CTypesIntegrationTest testMethod=test_ctypes_third_party_integration>,) kwargs = {} variant = ToolchainVariant(value=u'gnu') @wraps(func) def wrapper(*args, **kwargs): for variant in ToolchainVariant.iterate_enum_variants(): > func(*args, toolchain_variant=variant, **kwargs) .pants.d/pyprep/sources/68db53b799a649f3f92cbd3d3e740d9a1a47be07/pants_test/backend/python/tasks/native/test_ctypes_integration.py:32: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ .pants.d/pyprep/sources/68db53b799a649f3f92cbd3d3e740d9a1a47be07/pants_test/backend/python/tasks/native/test_ctypes_integration.py:195: in test_ctypes_third_party_integration self.assert_success(pants_run) .pants.d/pyprep/sources/68db53b799a649f3f92cbd3d3e740d9a1a47be07/pants_test/pants_run_integration_test.py:452: in assert_success self.assert_result(pants_run, self.PANTS_SUCCESS_CODE, expected=True, msg=msg) .pants.d/pyprep/sources/68db53b799a649f3f92cbd3d3e740d9a1a47be07/pants_test/pants_run_integration_test.py:473: in assert_result assertion(value, pants_run.returncode, error_msg) E AssertionError: /Users/travis/build/pantsbuild/pants/pants --no-pantsrc --pants-workdir=/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d --kill-nailguns --print-exception-stacktrace=True --pants-config-files=/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/pants.ini -q run testprojects/src/python/python_distribution/ctypes_with_third_party:bin_with_third_party E returncode: 1 E stdout: E E FAILURE: /usr/bin/python /Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/run/py/CPython-2.7.10/a8a8db2fdd4fae99b02f6010a93d6f6dc4f9f3dc ... exited non-zero (1) E E stderr: E Traceback (most recent call last): E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/run/py/CPython-2.7.10/a8a8db2fdd4fae99b02f6010a93d6f6dc4f9f3dc/.bootstrap/_pex/pex.py", line 349, in execute E exit_code = self._wrap_coverage(self._wrap_profiling, self._execute) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/run/py/CPython-2.7.10/a8a8db2fdd4fae99b02f6010a93d6f6dc4f9f3dc/.bootstrap/_pex/pex.py", line 281, in _wrap_coverage E return runner(*args) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/run/py/CPython-2.7.10/a8a8db2fdd4fae99b02f6010a93d6f6dc4f9f3dc/.bootstrap/_pex/pex.py", line 312, in _wrap_profiling E return runner(*args) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/run/py/CPython-2.7.10/a8a8db2fdd4fae99b02f6010a93d6f6dc4f9f3dc/.bootstrap/_pex/pex.py", line 394, in _execute E return self.execute_entry(self._pex_info.entry_point) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/run/py/CPython-2.7.10/a8a8db2fdd4fae99b02f6010a93d6f6dc4f9f3dc/.bootstrap/_pex/pex.py", line 506, in execute_entry E return runner(entry_point) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/run/py/CPython-2.7.10/a8a8db2fdd4fae99b02f6010a93d6f6dc4f9f3dc/.bootstrap/_pex/pex.py", line 513, in execute_module E runpy.run_module(module_name, run_name='__main__') E File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 180, in run_module E fname, loader, pkg_name) E File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 72, in _run_code E exec code in run_globals E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/pyprep/sources/46bc27ffbe03ecfe648c4d677289275aa6a6a93c-DefaultFingerprintStrategy_1b8903baa709/python_distribution/ctypes_with_third_party/main.py", line 7, in <module> E from ctypes_python_pkg.ctypes_wrapper import f E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/pyprep/requirements/CPython-2.7.10/dbfa0d2bb6877c576abca571691b6e7c8432a15a-DefaultFingerprintStrategy_25eb7243d755/.deps/ctypes_third_party_test-0.0.1+20865c6b4968b7f61c37fdc3ed80306ee2ca4a3e.defaultfingerprintstrategy.174c3658bd6c.8f03fa43ba4e-py2-none-macosx_10_13_x86_64.whl/ctypes_python_pkg/ctypes_wrapper.py", line 20, in <module> E asdf_cpp_lib = ctypes.CDLL(asdf_cpp_lib_path) E File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ctypes/__init__.py", line 365, in __init__ E self._handle = _dlopen(self._name, mode) E OSError: dlopen(/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/pyprep/requirements/CPython-2.7.10/dbfa0d2bb6877c576abca571691b6e7c8432a15a-DefaultFingerprintStrategy_25eb7243d755/.deps/ctypes_third_party_test-0.0.1+20865c6b4968b7f61c37fdc3ed80306ee2ca4a3e.defaultfingerprintstrategy.174c3658bd6c.8f03fa43ba4e-py2-none-macosx_10_13_x86_64.whl/libasdf-cpp_ctypes-with-third-party.so, 6): Library not loaded: /Users/stuhood/src/pantsbuild-binaries/build-support/bin/gcc/mac/10.13/7.3.0/gcc-7.3.0-osx/gcc-install/lib/libstdc++.6.dylib E Referenced from: /Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp1ZloAV.pants.d/pyprep/requirements/CPython-2.7.10/dbfa0d2bb6877c576abca571691b6e7c8432a15a-DefaultFingerprintStrategy_25eb7243d755/.deps/ctypes_third_party_test-0.0.1+20865c6b4968b7f61c37fdc3ed80306ee2ca4a3e.defaultfingerprintstrategy.174c3658bd6c.8f03fa43ba4e-py2-none-macosx_10_13_x86_64.whl/libasdf-cpp_ctypes-with-third-party.so E Reason: image not found E E FAILURE -------------- Captured stdout call -------------- logs/exceptions.4006.log +++ logs/exceptions.4006.log --- logs/exceptions.log +++ logs/exceptions.log --- CTypesIntegrationTest.test_native_compiler_option_sets_integration args = (<pants_test.backend.python.tasks.native.test_ctypes_integration.CTypesIntegrationTest testMethod=test_native_compiler_option_sets_integration>,) kwargs = {} variant = ToolchainVariant(value=u'gnu') @wraps(func) def wrapper(*args, **kwargs): for variant in ToolchainVariant.iterate_enum_variants(): > func(*args, toolchain_variant=variant, **kwargs) .pants.d/pyprep/sources/68db53b799a649f3f92cbd3d3e740d9a1a47be07/pants_test/backend/python/tasks/native/test_ctypes_integration.py:32: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ .pants.d/pyprep/sources/68db53b799a649f3f92cbd3d3e740d9a1a47be07/pants_test/backend/python/tasks/native/test_ctypes_integration.py:246: in test_native_compiler_option_sets_integration self.assert_success(pants_run) .pants.d/pyprep/sources/68db53b799a649f3f92cbd3d3e740d9a1a47be07/pants_test/pants_run_integration_test.py:452: in assert_success self.assert_result(pants_run, self.PANTS_SUCCESS_CODE, expected=True, msg=msg) .pants.d/pyprep/sources/68db53b799a649f3f92cbd3d3e740d9a1a47be07/pants_test/pants_run_integration_test.py:473: in assert_result assertion(value, pants_run.returncode, error_msg) E AssertionError: /Users/travis/build/pantsbuild/pants/pants --no-pantsrc --pants-workdir=/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d --kill-nailguns --print-exception-stacktrace=True --pants-config-files=/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/pants.ini run testprojects/src/python/python_distribution/ctypes_with_extra_compiler_flags:bin E returncode: 1 E stdout: E E 16:40:21 00:00 [main] E (To run a reporting server: ./pants server) E 16:40:22 00:01 [setup] E 16:40:22 00:01 [parse] E Executing tasks in goals: bootstrap -> imports -> unpack-jars -> unpack-wheels -> deferred-sources -> native-compile -> link -> jvm-platform-validate -> gen -> pyprep -> resolve -> resources -> compile -> binary -> run E 16:40:23 00:02 [bootstrap] E 16:40:23 00:02 [substitute-aliased-targets] E 16:40:23 00:02 [jar-dependency-management] E 16:40:23 00:02 [bootstrap-jvm-tools] E 16:40:23 00:02 [provide-tools-jar] E 16:40:24 00:03 [imports] E 16:40:24 00:03 [ivy-imports] E 16:40:24 00:03 [unpack-jars] E 16:40:24 00:03 [unpack-jars] E 16:40:24 00:03 [unpack-wheels] E 16:40:24 00:03 [unpack-wheels] E 16:40:24 00:03 [deferred-sources] E 16:40:24 00:03 [deferred-sources] E 16:40:24 00:03 [native-compile] E 16:40:24 00:03 [conan-prep] E 16:40:24 00:03 [create-conan-pex] E 16:40:32 00:11 [conan-fetch] E 16:40:32 00:11 [c-for-ctypes] E 16:40:32 00:11 [cpp-for-ctypes] E Invalidated 1 target. E selected compiler exe name: 'g++' E 16:40:32 00:11 [cpp-compile] E E 16:40:33 00:12 [link] E 16:40:33 00:12 [shared-libraries] E Invalidated 1 target. E selected linker exe name: 'g++' E 16:40:33 00:12 [link-shared-libraries] E 16:40:33 00:12 [jvm-platform-validate] E 16:40:33 00:12 [jvm-platform-validate] E 16:40:33 00:12 [gen] E 16:40:33 00:12 [antlr-java] E 16:40:33 00:12 [antlr-py] E 16:40:33 00:12 [jaxb] E 16:40:33 00:12 [protoc] E 16:40:33 00:12 [ragel] E 16:40:33 00:12 [thrift-java] E 16:40:33 00:12 [thrift-py] E 16:40:33 00:12 [grpcio-prep] E 16:40:33 00:12 [grpcio-run] E 16:40:33 00:12 [wire] E 16:40:33 00:12 [avro-java] E 16:40:33 00:12 [go-thrift] E 16:40:33 00:12 [go-protobuf] E 16:40:33 00:12 [jax-ws] E 16:40:33 00:12 [scrooge] E 16:40:33 00:12 [thrifty] E 16:40:33 00:12 [pyprep] E 16:40:33 00:12 [interpreter] E 16:40:33 00:12 [build-local-dists] E Invalidated 1 target. E 16:40:35 00:14 [setup.py] E 16:40:35 00:14 [requirements] E Invalidated 1 target. E 16:40:36 00:15 [sources] E Invalidated 1 target. E 16:40:36 00:15 [resolve] E 16:40:36 00:15 [ivy] E 16:40:36 00:15 [coursier] E 16:40:36 00:15 [go] E 16:40:36 00:15 [scala-js-compile] E 16:40:36 00:15 [scala-js-link] E 16:40:37 00:16 [node] E 16:40:37 00:16 [resources] E 16:40:37 00:16 [prepare] E 16:40:37 00:16 [services] E 16:40:37 00:16 [compile] E 16:40:37 00:16 [node] E 16:40:37 00:16 [compile-jvm-prep-command] E 16:40:37 00:16 [jvm_prep_command] E 16:40:37 00:16 [compile-prep-command] E 16:40:37 00:16 [compile] E 16:40:37 00:16 [rsc] E 16:40:37 00:16 [zinc] E 16:40:37 00:16 [javac] E 16:40:37 00:16 [cpp] E 16:40:37 00:16 [errorprone] E 16:40:37 00:16 [findbugs] E 16:40:37 00:16 [go] E 16:40:37 00:16 [binary] E 16:40:37 00:16 [binary-jvm-prep-command] E 16:40:37 00:16 [jvm_prep_command] E 16:40:37 00:16 [binary-prep-command] E 16:40:37 00:16 [py] E Invalidated 1 target. E created pex dist/bin.pex E 16:40:38 00:17 [py-wheels] E created wheel dist/ctypes_test-0.0.1+74173b5ce60ddd85088b1fed70c8b071f2679604.defaultfingerprintstrategy.12652e89be0f.8f03fa43ba4e-py2-none-macosx_10_13_x86_64.whl E 16:40:38 00:17 [jvm] E 16:40:38 00:17 [dup] E 16:40:38 00:17 [cpplib] E 16:40:38 00:17 [cpp-library] E 16:40:38 00:17 [cpp] E 16:40:38 00:17 [cpp-binary] E 16:40:38 00:17 [go] E 16:40:38 00:17 [run] E 16:40:38 00:17 [py] E Invalidated 3 targets. E 16:40:39 00:18 [run] E E FAILURE: /usr/bin/python /Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/run/py/CPython-2.7.10/3784d4150334a9a89ddceb31bdb13969e94f73b2 ... exited non-zero (1) E E E Waiting for background workers to finish. E 16:40:39 00:18 [complete] E FAILURE E stderr: E Traceback (most recent call last): E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/run/py/CPython-2.7.10/3784d4150334a9a89ddceb31bdb13969e94f73b2/.bootstrap/_pex/pex.py", line 349, in execute E exit_code = self._wrap_coverage(self._wrap_profiling, self._execute) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/run/py/CPython-2.7.10/3784d4150334a9a89ddceb31bdb13969e94f73b2/.bootstrap/_pex/pex.py", line 281, in _wrap_coverage E return runner(*args) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/run/py/CPython-2.7.10/3784d4150334a9a89ddceb31bdb13969e94f73b2/.bootstrap/_pex/pex.py", line 312, in _wrap_profiling E return runner(*args) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/run/py/CPython-2.7.10/3784d4150334a9a89ddceb31bdb13969e94f73b2/.bootstrap/_pex/pex.py", line 394, in _execute E return self.execute_entry(self._pex_info.entry_point) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/run/py/CPython-2.7.10/3784d4150334a9a89ddceb31bdb13969e94f73b2/.bootstrap/_pex/pex.py", line 506, in execute_entry E return runner(entry_point) E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/run/py/CPython-2.7.10/3784d4150334a9a89ddceb31bdb13969e94f73b2/.bootstrap/_pex/pex.py", line 513, in execute_module E runpy.run_module(module_name, run_name='__main__') E File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 180, in run_module E fname, loader, pkg_name) E File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 72, in _run_code E exec code in run_globals E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/pyprep/sources/be29db057705cafb8edc0e69942013e74ccffbe3-DefaultFingerprintStrategy_1b8903baa709/python_distribution/ctypes_with_extra_compiler_flags/main.py", line 7, in <module> E from ctypes_python_pkg.ctypes_wrapper import f E File "/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/pyprep/requirements/CPython-2.7.10/2122a483545750a790ffdd2c65a8039affd3f167-DefaultFingerprintStrategy_25eb7243d755/.deps/ctypes_test-0.0.1+74173b5ce60ddd85088b1fed70c8b071f2679604.defaultfingerprintstrategy.12652e89be0f.8f03fa43ba4e-py2-none-macosx_10_13_x86_64.whl/ctypes_python_pkg/ctypes_wrapper.py", line 20, in <module> E asdf_cpp_lib = ctypes.CDLL(asdf_cpp_lib_path) E File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ctypes/__init__.py", line 365, in __init__ E self._handle = _dlopen(self._name, mode) E OSError: dlopen(/Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/pyprep/requirements/CPython-2.7.10/2122a483545750a790ffdd2c65a8039affd3f167-DefaultFingerprintStrategy_25eb7243d755/.deps/ctypes_test-0.0.1+74173b5ce60ddd85088b1fed70c8b071f2679604.defaultfingerprintstrategy.12652e89be0f.8f03fa43ba4e-py2-none-macosx_10_13_x86_64.whl/libasdf-cpp_ctypes-with-extra-compiler-flags.so, 6): Library not loaded: /Users/stuhood/src/pantsbuild-binaries/build-support/bin/gcc/mac/10.13/7.3.0/gcc-7.3.0-osx/gcc-install/lib/libstdc++.6.dylib E Referenced from: /Users/travis/build/pantsbuild/pants/.pants.d/tmp/tmp8qW7hO.pants.d/pyprep/requirements/CPython-2.7.10/2122a483545750a790ffdd2c65a8039affd3f167-DefaultFingerprintStrategy_25eb7243d755/.deps/ctypes_test-0.0.1+74173b5ce60ddd85088b1fed70c8b071f2679604.defaultfingerprintstrategy.12652e89be0f.8f03fa43ba4e-py2-none-macosx_10_13_x86_64.whl/libasdf-cpp_ctypes-with-extra-compiler-flags.so E Reason: image not found -------------- Captured stdout call -------------- logs/exceptions.4063.log +++ logs/exceptions.4063.log --- logs/exceptions.log +++ logs/exceptions.log --- ====== 2 failed, 3 passed in 199.95 seconds ======
AssertionError
def _setup_interpreter(self, interpreter, identity_str): cache_target_path = os.path.join(self._cache_dir, identity_str) with safe_concurrent_creation(cache_target_path) as safe_path: os.mkdir( safe_path ) # Parent will already have been created by safe_concurrent_creation. os.symlink(interpreter.binary, os.path.join(safe_path, "python")) return self._resolve(interpreter, safe_path)
def _setup_interpreter(self, interpreter, cache_target_path): with safe_concurrent_creation(cache_target_path) as safe_path: os.mkdir( safe_path ) # Parent will already have been created by safe_concurrent_creation. os.symlink(interpreter.binary, os.path.join(safe_path, "python")) return self._resolve(interpreter, safe_path)
https://github.com/pantsbuild/pants/issues/3416
os.path.exists(os.readlink('python')) False subprocess.Popen(['./python', 'blah'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) Traceback (most recent call last): File "<input>", line 1, in <module> File "/opt/twitter_mde/package/python2.7/current/lib/python2.7/subprocess.py", line 710, in __init__ errread, errwrite) File "/opt/twitter_mde/package/python2.7/current/lib/python2.7/subprocess.py", line 1335, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory
OSError
def _setup_cached(self, filters=()): """Find all currently-cached interpreters.""" for interpreter_dir in os.listdir(self._cache_dir): pi = self._interpreter_from_relpath(interpreter_dir, filters=filters) if pi: logger.debug( "Detected interpreter {}: {}".format(pi.binary, str(pi.identity)) ) yield pi
def _setup_cached(self, filters=()): """Find all currently-cached interpreters.""" for interpreter_dir in os.listdir(self._cache_dir): path = os.path.join(self._cache_dir, interpreter_dir) if os.path.isdir(path): pi = self._interpreter_from_path(path, filters=filters) if pi: logger.debug( "Detected interpreter {}: {}".format(pi.binary, str(pi.identity)) ) yield pi
https://github.com/pantsbuild/pants/issues/3416
os.path.exists(os.readlink('python')) False subprocess.Popen(['./python', 'blah'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) Traceback (most recent call last): File "<input>", line 1, in <module> File "/opt/twitter_mde/package/python2.7/current/lib/python2.7/subprocess.py", line 710, in __init__ errread, errwrite) File "/opt/twitter_mde/package/python2.7/current/lib/python2.7/subprocess.py", line 1335, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory
OSError
def _setup_paths(self, paths, filters=()): """Find interpreters under paths, and cache them.""" for interpreter in self._matching(PythonInterpreter.all(paths), filters=filters): identity_str = str(interpreter.identity) pi = self._interpreter_from_relpath(identity_str, filters=filters) if pi is None: self._setup_interpreter(interpreter, identity_str) pi = self._interpreter_from_relpath(identity_str, filters=filters) if pi: yield pi
def _setup_paths(self, paths, filters=()): """Find interpreters under paths, and cache them.""" for interpreter in self._matching(PythonInterpreter.all(paths), filters=filters): identity_str = str(interpreter.identity) cache_path = os.path.join(self._cache_dir, identity_str) pi = self._interpreter_from_path(cache_path, filters=filters) if pi is None: self._setup_interpreter(interpreter, cache_path) pi = self._interpreter_from_path(cache_path, filters=filters) if pi: yield pi
https://github.com/pantsbuild/pants/issues/3416
os.path.exists(os.readlink('python')) False subprocess.Popen(['./python', 'blah'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) Traceback (most recent call last): File "<input>", line 1, in <module> File "/opt/twitter_mde/package/python2.7/current/lib/python2.7/subprocess.py", line 710, in __init__ errread, errwrite) File "/opt/twitter_mde/package/python2.7/current/lib/python2.7/subprocess.py", line 1335, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory
OSError
def execute(self): # NB: Downstream product consumers may need the selected interpreter for use with # any type of importable Python target, including `PythonRequirementLibrary` targets # (for use with the `repl` goal, for instance). For interpreter selection, # we only care about targets with compatibility constraints. python_tgts_and_reqs = self.context.targets( lambda tgt: isinstance(tgt, (PythonTarget, PythonRequirementLibrary)) ) if not python_tgts_and_reqs: return python_tgts = [tgt for tgt in python_tgts_and_reqs if isinstance(tgt, PythonTarget)] fs = PythonInterpreterFingerprintStrategy() with self.invalidated(python_tgts, fingerprint_strategy=fs) as invalidation_check: # If there are no relevant targets, we still go through the motions of selecting # an interpreter, to prevent downstream tasks from having to check for this special case. if invalidation_check.all_vts: target_set_id = VersionedTargetSet.from_versioned_targets( invalidation_check.all_vts ).cache_key.hash else: target_set_id = "no_targets" interpreter_path_file = self._interpreter_path_file(target_set_id) if not os.path.exists(interpreter_path_file): self._create_interpreter_path_file(interpreter_path_file, python_tgts) else: if self._detect_and_purge_invalid_interpreter(interpreter_path_file): self._create_interpreter_path_file(interpreter_path_file, python_tgts) interpreter = self._get_interpreter(interpreter_path_file) self.context.products.register_data(PythonInterpreter, interpreter)
def execute(self): # NB: Downstream product consumers may need the selected interpreter for use with # any type of importable Python target, including `PythonRequirementLibrary` targets # (for use with the `repl` goal, for instance). For interpreter selection, # we only care about targets with compatibility constraints. python_tgts_and_reqs = self.context.targets( lambda tgt: isinstance(tgt, (PythonTarget, PythonRequirementLibrary)) ) if not python_tgts_and_reqs: return python_tgts = [tgt for tgt in python_tgts_and_reqs if isinstance(tgt, PythonTarget)] fs = PythonInterpreterFingerprintStrategy() with self.invalidated(python_tgts, fingerprint_strategy=fs) as invalidation_check: # If there are no relevant targets, we still go through the motions of selecting # an interpreter, to prevent downstream tasks from having to check for this special case. if invalidation_check.all_vts: target_set_id = VersionedTargetSet.from_versioned_targets( invalidation_check.all_vts ).cache_key.hash else: target_set_id = "no_targets" interpreter_path_file = self._interpreter_path_file(target_set_id) if not os.path.exists(interpreter_path_file): self._create_interpreter_path_file(interpreter_path_file, python_tgts) interpreter = self._get_interpreter(interpreter_path_file) self.context.products.register_data(PythonInterpreter, interpreter)
https://github.com/pantsbuild/pants/issues/3416
os.path.exists(os.readlink('python')) False subprocess.Popen(['./python', 'blah'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) Traceback (most recent call last): File "<input>", line 1, in <module> File "/opt/twitter_mde/package/python2.7/current/lib/python2.7/subprocess.py", line 710, in __init__ errread, errwrite) File "/opt/twitter_mde/package/python2.7/current/lib/python2.7/subprocess.py", line 1335, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory
OSError
def get_buildroot(): """Returns the pants build root, calculating it if needed. :API: public """ return BuildRoot().path
def get_buildroot(): """Returns the pants build root, calculating it if needed. :API: public """ try: return BuildRoot().path except BuildRoot.NotFoundError as e: print(str(e), file=sys.stderr) sys.exit(1)
https://github.com/pantsbuild/pants/issues/6847
23:26:42 01:10 [run] ============== test session starts =============== platform darwin -- Python 2.7.10, pytest-3.6.4, py-1.7.0, pluggy-0.7.1 -- /System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python cachedir: .pants.d/.pytest_cache rootdir: /Users/travis/build/pantsbuild/pants/.pants.d, inifile: /Users/travis/build/pantsbuild/pants/.pants.d/test/pytest-prep/CPython-2.7.10/e241a5f8b7de6d34689cc9307d8d06eb155c7c78/pytest.ini plugins: timeout-1.2.1, cov-2.4.0 collecting ... collected 7 items tests/python/pants_test/base/test_exception_sink_integration.py::ExceptionSinkIntegrationTest::test_dumps_logs_on_terminate <- ../../../../../../System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/case.py SKIPPED [ 14%] tests/python/pants_test/base/test_exception_sink_integration.py::ExceptionSinkIntegrationTest::test_dumps_traceback_on_sigabrt <- pyprep/sources/4d9f3a72ced4c3b5cabbfead9552e9e3e78a30ca/pants_test/base/test_exception_sink_integration.py PASSED [ 28%] tests/python/pants_test/base/test_exception_sink_integration.py::ExceptionSinkIntegrationTest::test_keyboardinterrupt_signals <- pyprep/sources/4d9f3a72ced4c3b5cabbfead9552e9e3e78a30ca/pants_test/base/test_exception_sink_integration.py FAILED [ 42%] tests/python/pants_test/base/test_exception_sink_integration.py::ExceptionSinkIntegrationTest::test_logs_unhandled_exception <- pyprep/sources/4d9f3a72ced4c3b5cabbfead9552e9e3e78a30ca/pants_test/base/test_exception_sink_integration.py PASSED [ 57%] tests/python/pants_test/base/test_exception_sink_integration.py::ExceptionSinkIntegrationTest::test_prints_traceback_on_sigusr2 <- pyprep/sources/4d9f3a72ced4c3b5cabbfead9552e9e3e78a30ca/pants_test/base/test_exception_sink_integration.py PASSED [ 71%] tests/python/pants_test/base/test_exception_sink_integration.py::ExceptionSinkIntegrationTest::test_reset_exiter <- pyprep/sources/4d9f3a72ced4c3b5cabbfead9552e9e3e78a30ca/pants_test/base/test_exception_sink_integration.py PASSED [ 85%] tests/python/pants_test/base/test_exception_sink_integration.py::ExceptionSinkIntegrationTest::test_reset_interactive_output_stream <- pyprep/sources/4d9f3a72ced4c3b5cabbfead9552e9e3e78a30ca/pants_test/base/test_exception_sink_integration.py PASSED [100%] ==================== FAILURES ==================== ExceptionSinkIntegrationTest.test_keyboardinterrupt_signals self = <pants_test.base.test_exception_sink_integration.ExceptionSinkIntegrationTest testMethod=test_keyboardinterrupt_signals> def test_keyboardinterrupt_signals(self): for interrupt_signal in [signal.SIGINT, signal.SIGQUIT]: with self._send_signal_to_waiter_handle(interrupt_signal) as (workdir, waiter_run): > self.assertIn('Interrupted by user.\n', waiter_run.stderr_data) E AssertionError: u'Interrupted by user.\n' not found in u'From cffi callback <function extern_clone_val at 0x11098a938>:\nTraceback (most recent call last):\n File "/Users/travis/build/pantsbuild/pants/src/python/pants/engine/native.py", line 427, in extern_clone_val\n @ffi.def_extern()\n File "/Users/travis/build/pantsbuild/pants/src/python/pants/base/exception_sink.py", line 351, in handle_signal_gracefully\n raise KeyboardInterrupt(\'User interrupted execution with control-c!\')\nKeyboardInterrupt: User interrupted execution with control-c!\ntimestamp: 2018-11-29T23:28:22.606384\nException caught: (pants.build_graph.address_lookup_error.AddressLookupError)\n File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/pants_loader.py", line 75, in <module>\n main()\n File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/pants_loader.py", line 71, in main\n PantsLoader.run()\n File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/pants_loader.py", line 67, in run\n cls.load_and_execute(entrypoint)\n File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/pants_loader.py", line 60, in load_and_execute\n entrypoint_main()\n File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/pants_exe.py", line 39, in main\n PantsRunner(exiter, start_time=start_time).run()\n File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/pants_runner.py", line 62, in run\n return runner.run()\n File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/local_pants_runner.py", line 159, in run\n self._run()\n File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/local_pants_runner.py", line 227, in _run\n goal_runner_result = self._maybe_run_v1(run_tracker, reporting)\n File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/local_pants_runner.py", line 176, in _maybe_run_v1\n return goal_runner_factory.create().run()\n File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/goal_runner.py", line 125, in create\n goals, context = self._setup_context()\n File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/goal_runner.py", line 95, in _setup_context\n self._root_dir\n File "/Users/travis/build/pantsbuild/pants/src/python/pants/init/engine_initializer.py", line 226, in create_build_graph\n for _ in graph.inject_roots_closure(target_roots):\n File "/Users/travis/build/pantsbuild/pants/src/python/pants/engine/legacy/graph.py", line 217, in inject_roots_closure\n for address in self._inject_specs(target_roots.specs):\n File "/Users/travis/build/pantsbuild/pants/src/python/pants/engine/legacy/graph.py", line 270, in _inject_specs\n subjects)\n File "/usr/local/Cellar/python/2.7.14/Frameworks/Python.framework/Versions/2.7/lib/python2.7/contextlib.py", line 35, in __exit__\n self.gen.throw(type, value, traceback)\n File "/Users/travis/build/pantsbuild/pants/src/python/pants/engine/legacy/graph.py", line 237, in _resolve_context\n \'Build graph construction failed: {} {}\'.format(type(e).__name__, str(e))\n\nException message: Build graph construction failed: RuntimeError cannot use from_handle() on NULL pointer\n\n\n' .pants.d/pyprep/sources/4d9f3a72ced4c3b5cabbfead9552e9e3e78a30ca/pants_test/base/test_exception_sink_integration.py:151: AssertionError -------------- Captured stdout call -------------- logs/exceptions.84142.log +++ logs/exceptions.84142.log >>> timestamp: 2018-11-29T23:28:22.605908 logs/exceptions.84142.log >>> process title: python /Users/travis/build/pantsbuild/pants/src/python/pants/bin/pants_loader.py --no-pantsrc --pants-workdir=/var/folders/bb/n7t3rs157850byt_jfdcq9k80000gn/T/tmpxqSksJ/.pants.d --kill-nailguns --print-exception-stacktrace=True --no-enable-pantsd run testprojects/src/python/coordinated_runs:waiter -- /var/folders/bb/n7t3rs157850byt_jfdcq9k80000gn/T/tmpxqSksJ/some_file logs/exceptions.84142.log >>> sys.argv: ['/Users/travis/build/pantsbuild/pants/src/python/pants/bin/pants_loader.py', '--no-pantsrc', '--pants-workdir=/var/folders/bb/n7t3rs157850byt_jfdcq9k80000gn/T/tmpxqSksJ/.pants.d', '--kill-nailguns', '--print-exception-stacktrace=True', '--no-enable-pantsd', 'run', 'testprojects/src/python/coordinated_runs:waiter', '--', '/var/folders/bb/n7t3rs157850byt_jfdcq9k80000gn/T/tmpxqSksJ/some_file'] logs/exceptions.84142.log >>> pid: 84142 logs/exceptions.84142.log >>> Exception caught: (pants.build_graph.address_lookup_error.AddressLookupError) logs/exceptions.84142.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/pants_loader.py", line 75, in <module> logs/exceptions.84142.log >>> main() logs/exceptions.84142.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/pants_loader.py", line 71, in main logs/exceptions.84142.log >>> PantsLoader.run() logs/exceptions.84142.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/pants_loader.py", line 67, in run logs/exceptions.84142.log >>> cls.load_and_execute(entrypoint) logs/exceptions.84142.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/pants_loader.py", line 60, in load_and_execute logs/exceptions.84142.log >>> entrypoint_main() logs/exceptions.84142.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/pants_exe.py", line 39, in main logs/exceptions.84142.log >>> PantsRunner(exiter, start_time=start_time).run() logs/exceptions.84142.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/pants_runner.py", line 62, in run logs/exceptions.84142.log >>> return runner.run() logs/exceptions.84142.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/local_pants_runner.py", line 159, in run logs/exceptions.84142.log >>> self._run() logs/exceptions.84142.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/local_pants_runner.py", line 227, in _run logs/exceptions.84142.log >>> goal_runner_result = self._maybe_run_v1(run_tracker, reporting) logs/exceptions.84142.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/local_pants_runner.py", line 176, in _maybe_run_v1 logs/exceptions.84142.log >>> return goal_runner_factory.create().run() logs/exceptions.84142.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/goal_runner.py", line 125, in create logs/exceptions.84142.log >>> goals, context = self._setup_context() logs/exceptions.84142.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/goal_runner.py", line 95, in _setup_context logs/exceptions.84142.log >>> self._root_dir logs/exceptions.84142.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/init/engine_initializer.py", line 226, in create_build_graph logs/exceptions.84142.log >>> for _ in graph.inject_roots_closure(target_roots): logs/exceptions.84142.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/engine/legacy/graph.py", line 217, in inject_roots_closure logs/exceptions.84142.log >>> for address in self._inject_specs(target_roots.specs): logs/exceptions.84142.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/engine/legacy/graph.py", line 270, in _inject_specs logs/exceptions.84142.log >>> subjects) logs/exceptions.84142.log >>> File "/usr/local/Cellar/python/2.7.14/Frameworks/Python.framework/Versions/2.7/lib/python2.7/contextlib.py", line 35, in __exit__ logs/exceptions.84142.log >>> self.gen.throw(type, value, traceback) logs/exceptions.84142.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/engine/legacy/graph.py", line 237, in _resolve_context logs/exceptions.84142.log >>> 'Build graph construction failed: {} {}'.format(type(e).__name__, str(e)) logs/exceptions.84142.log >>> logs/exceptions.84142.log >>> Exception message: Build graph construction failed: RuntimeError cannot use from_handle() on NULL pointer logs/exceptions.84142.log >>> logs/exceptions.84142.log --- logs/exceptions.log +++ logs/exceptions.log >>> timestamp: 2018-11-29T23:28:22.605908 logs/exceptions.log >>> process title: python /Users/travis/build/pantsbuild/pants/src/python/pants/bin/pants_loader.py --no-pantsrc --pants-workdir=/var/folders/bb/n7t3rs157850byt_jfdcq9k80000gn/T/tmpxqSksJ/.pants.d --kill-nailguns --print-exception-stacktrace=True --no-enable-pantsd run testprojects/src/python/coordinated_runs:waiter -- /var/folders/bb/n7t3rs157850byt_jfdcq9k80000gn/T/tmpxqSksJ/some_file logs/exceptions.log >>> sys.argv: ['/Users/travis/build/pantsbuild/pants/src/python/pants/bin/pants_loader.py', '--no-pantsrc', '--pants-workdir=/var/folders/bb/n7t3rs157850byt_jfdcq9k80000gn/T/tmpxqSksJ/.pants.d', '--kill-nailguns', '--print-exception-stacktrace=True', '--no-enable-pantsd', 'run', 'testprojects/src/python/coordinated_runs:waiter', '--', '/var/folders/bb/n7t3rs157850byt_jfdcq9k80000gn/T/tmpxqSksJ/some_file'] logs/exceptions.log >>> pid: 84142 logs/exceptions.log >>> Exception caught: (pants.build_graph.address_lookup_error.AddressLookupError) logs/exceptions.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/pants_loader.py", line 75, in <module> logs/exceptions.log >>> main() logs/exceptions.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/pants_loader.py", line 71, in main logs/exceptions.log >>> PantsLoader.run() logs/exceptions.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/pants_loader.py", line 67, in run logs/exceptions.log >>> cls.load_and_execute(entrypoint) logs/exceptions.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/pants_loader.py", line 60, in load_and_execute logs/exceptions.log >>> entrypoint_main() logs/exceptions.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/pants_exe.py", line 39, in main logs/exceptions.log >>> PantsRunner(exiter, start_time=start_time).run() logs/exceptions.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/pants_runner.py", line 62, in run logs/exceptions.log >>> return runner.run() logs/exceptions.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/local_pants_runner.py", line 159, in run logs/exceptions.log >>> self._run() logs/exceptions.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/local_pants_runner.py", line 227, in _run logs/exceptions.log >>> goal_runner_result = self._maybe_run_v1(run_tracker, reporting) logs/exceptions.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/local_pants_runner.py", line 176, in _maybe_run_v1 logs/exceptions.log >>> return goal_runner_factory.create().run() logs/exceptions.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/goal_runner.py", line 125, in create logs/exceptions.log >>> goals, context = self._setup_context() logs/exceptions.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/goal_runner.py", line 95, in _setup_context logs/exceptions.log >>> self._root_dir logs/exceptions.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/init/engine_initializer.py", line 226, in create_build_graph logs/exceptions.log >>> for _ in graph.inject_roots_closure(target_roots): logs/exceptions.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/engine/legacy/graph.py", line 217, in inject_roots_closure logs/exceptions.log >>> for address in self._inject_specs(target_roots.specs): logs/exceptions.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/engine/legacy/graph.py", line 270, in _inject_specs logs/exceptions.log >>> subjects) logs/exceptions.log >>> File "/usr/local/Cellar/python/2.7.14/Frameworks/Python.framework/Versions/2.7/lib/python2.7/contextlib.py", line 35, in __exit__ logs/exceptions.log >>> self.gen.throw(type, value, traceback) logs/exceptions.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/engine/legacy/graph.py", line 237, in _resolve_context logs/exceptions.log >>> 'Build graph construction failed: {} {}'.format(type(e).__name__, str(e)) logs/exceptions.log >>> logs/exceptions.log >>> Exception message: Build graph construction failed: RuntimeError cannot use from_handle() on NULL pointer logs/exceptions.log >>> logs/exceptions.log --- generated xml file: /Users/travis/build/pantsbuild/pants/.pants.d/test/pytest/tests.python.pants_test.base.exception_sink_integration/junitxml/TEST-tests.python.pants_test.base.exception_sink_integration.xml ============ slowest 3 test durations ============ 93.67s call ../tests/python/pants_test/base/test_exception_sink_integration.py::ExceptionSinkIntegrationTest::test_dumps_traceback_on_sigabrt 6.08s call ../tests/python/pants_test/base/test_exception_sink_integration.py::ExceptionSinkIntegrationTest::test_prints_traceback_on_sigusr2 5.55s call ../tests/python/pants_test/base/test_exception_sink_integration.py::ExceptionSinkIntegrationTest::test_reset_interactive_output_stream 1 failed, 5 passed, 1 skipped in 118.85 seconds =
AssertionError
def reset_log_location(cls, new_log_location): """Re-acquire file handles to error logs based in the new location. Class state: - Overwrites `cls._log_dir`, `cls._pid_specific_error_fileobj`, and `cls._shared_error_fileobj`. OS state: - May create a new directory. - Overwrites signal handlers for many fatal and non-fatal signals. :raises: :class:`ExceptionSink.ExceptionSinkError` if the directory does not exist or is not writable. """ # We could no-op here if the log locations are the same, but there's no reason not to have the # additional safety of re-acquiring file descriptors each time (and erroring out early if the # location is no longer writable). # Create the directory if possible, or raise if not writable. cls._check_or_create_new_destination(new_log_location) pid_specific_error_stream, shared_error_stream = ( cls._recapture_fatal_error_log_streams(new_log_location) ) # NB: mutate process-global state! if faulthandler.is_enabled(): logger.debug("re-enabling faulthandler") # Call Py_CLEAR() on the previous error stream: # https://github.com/vstinner/faulthandler/blob/master/faulthandler.c faulthandler.disable() # Send a stacktrace to this file if interrupted by a fatal error. faulthandler.enable(file=pid_specific_error_stream, all_threads=True) # NB: mutate the class variables! cls._log_dir = new_log_location cls._pid_specific_error_fileobj = pid_specific_error_stream cls._shared_error_fileobj = shared_error_stream
def reset_log_location(cls, new_log_location): """Re-acquire file handles to error logs based in the new location. Class state: - Overwrites `cls._log_dir`, `cls._pid_specific_error_fileobj`, and `cls._shared_error_fileobj`. OS state: - May create a new directory. - Overwrites signal handlers for many fatal and non-fatal signals. :raises: :class:`ExceptionSink.ExceptionSinkError` if the directory does not exist or is not writable. """ # We could no-op here if the log locations are the same, but there's no reason not to have the # additional safety of re-acquiring file descriptors each time (and erroring out early if the # location is no longer writable). # Create the directory if possible, or raise if not writable. cls._check_or_create_new_destination(new_log_location) pid_specific_error_stream, shared_error_stream = ( cls._recapture_fatal_error_log_streams(new_log_location) ) # NB: mutate process-global state! if faulthandler.is_enabled(): logger.debug("re-enabling faulthandler") # Call Py_CLEAR() on the previous error stream: # https://github.com/vstinner/faulthandler/blob/master/faulthandler.c faulthandler.disable() # Send a stacktrace to this file if interrupted by a fatal error. faulthandler.enable(file=pid_specific_error_stream, all_threads=True) # Log a timestamped exception and exit gracefully on non-fatal signals. for signum in cls.all_gracefully_handled_signals: signal.signal(signum, cls.handle_signal_gracefully) signal.siginterrupt(signum, False) # NB: mutate the class variables! cls._log_dir = new_log_location cls._pid_specific_error_fileobj = pid_specific_error_stream cls._shared_error_fileobj = shared_error_stream
https://github.com/pantsbuild/pants/issues/6847
23:26:42 01:10 [run] ============== test session starts =============== platform darwin -- Python 2.7.10, pytest-3.6.4, py-1.7.0, pluggy-0.7.1 -- /System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python cachedir: .pants.d/.pytest_cache rootdir: /Users/travis/build/pantsbuild/pants/.pants.d, inifile: /Users/travis/build/pantsbuild/pants/.pants.d/test/pytest-prep/CPython-2.7.10/e241a5f8b7de6d34689cc9307d8d06eb155c7c78/pytest.ini plugins: timeout-1.2.1, cov-2.4.0 collecting ... collected 7 items tests/python/pants_test/base/test_exception_sink_integration.py::ExceptionSinkIntegrationTest::test_dumps_logs_on_terminate <- ../../../../../../System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/case.py SKIPPED [ 14%] tests/python/pants_test/base/test_exception_sink_integration.py::ExceptionSinkIntegrationTest::test_dumps_traceback_on_sigabrt <- pyprep/sources/4d9f3a72ced4c3b5cabbfead9552e9e3e78a30ca/pants_test/base/test_exception_sink_integration.py PASSED [ 28%] tests/python/pants_test/base/test_exception_sink_integration.py::ExceptionSinkIntegrationTest::test_keyboardinterrupt_signals <- pyprep/sources/4d9f3a72ced4c3b5cabbfead9552e9e3e78a30ca/pants_test/base/test_exception_sink_integration.py FAILED [ 42%] tests/python/pants_test/base/test_exception_sink_integration.py::ExceptionSinkIntegrationTest::test_logs_unhandled_exception <- pyprep/sources/4d9f3a72ced4c3b5cabbfead9552e9e3e78a30ca/pants_test/base/test_exception_sink_integration.py PASSED [ 57%] tests/python/pants_test/base/test_exception_sink_integration.py::ExceptionSinkIntegrationTest::test_prints_traceback_on_sigusr2 <- pyprep/sources/4d9f3a72ced4c3b5cabbfead9552e9e3e78a30ca/pants_test/base/test_exception_sink_integration.py PASSED [ 71%] tests/python/pants_test/base/test_exception_sink_integration.py::ExceptionSinkIntegrationTest::test_reset_exiter <- pyprep/sources/4d9f3a72ced4c3b5cabbfead9552e9e3e78a30ca/pants_test/base/test_exception_sink_integration.py PASSED [ 85%] tests/python/pants_test/base/test_exception_sink_integration.py::ExceptionSinkIntegrationTest::test_reset_interactive_output_stream <- pyprep/sources/4d9f3a72ced4c3b5cabbfead9552e9e3e78a30ca/pants_test/base/test_exception_sink_integration.py PASSED [100%] ==================== FAILURES ==================== ExceptionSinkIntegrationTest.test_keyboardinterrupt_signals self = <pants_test.base.test_exception_sink_integration.ExceptionSinkIntegrationTest testMethod=test_keyboardinterrupt_signals> def test_keyboardinterrupt_signals(self): for interrupt_signal in [signal.SIGINT, signal.SIGQUIT]: with self._send_signal_to_waiter_handle(interrupt_signal) as (workdir, waiter_run): > self.assertIn('Interrupted by user.\n', waiter_run.stderr_data) E AssertionError: u'Interrupted by user.\n' not found in u'From cffi callback <function extern_clone_val at 0x11098a938>:\nTraceback (most recent call last):\n File "/Users/travis/build/pantsbuild/pants/src/python/pants/engine/native.py", line 427, in extern_clone_val\n @ffi.def_extern()\n File "/Users/travis/build/pantsbuild/pants/src/python/pants/base/exception_sink.py", line 351, in handle_signal_gracefully\n raise KeyboardInterrupt(\'User interrupted execution with control-c!\')\nKeyboardInterrupt: User interrupted execution with control-c!\ntimestamp: 2018-11-29T23:28:22.606384\nException caught: (pants.build_graph.address_lookup_error.AddressLookupError)\n File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/pants_loader.py", line 75, in <module>\n main()\n File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/pants_loader.py", line 71, in main\n PantsLoader.run()\n File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/pants_loader.py", line 67, in run\n cls.load_and_execute(entrypoint)\n File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/pants_loader.py", line 60, in load_and_execute\n entrypoint_main()\n File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/pants_exe.py", line 39, in main\n PantsRunner(exiter, start_time=start_time).run()\n File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/pants_runner.py", line 62, in run\n return runner.run()\n File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/local_pants_runner.py", line 159, in run\n self._run()\n File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/local_pants_runner.py", line 227, in _run\n goal_runner_result = self._maybe_run_v1(run_tracker, reporting)\n File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/local_pants_runner.py", line 176, in _maybe_run_v1\n return goal_runner_factory.create().run()\n File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/goal_runner.py", line 125, in create\n goals, context = self._setup_context()\n File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/goal_runner.py", line 95, in _setup_context\n self._root_dir\n File "/Users/travis/build/pantsbuild/pants/src/python/pants/init/engine_initializer.py", line 226, in create_build_graph\n for _ in graph.inject_roots_closure(target_roots):\n File "/Users/travis/build/pantsbuild/pants/src/python/pants/engine/legacy/graph.py", line 217, in inject_roots_closure\n for address in self._inject_specs(target_roots.specs):\n File "/Users/travis/build/pantsbuild/pants/src/python/pants/engine/legacy/graph.py", line 270, in _inject_specs\n subjects)\n File "/usr/local/Cellar/python/2.7.14/Frameworks/Python.framework/Versions/2.7/lib/python2.7/contextlib.py", line 35, in __exit__\n self.gen.throw(type, value, traceback)\n File "/Users/travis/build/pantsbuild/pants/src/python/pants/engine/legacy/graph.py", line 237, in _resolve_context\n \'Build graph construction failed: {} {}\'.format(type(e).__name__, str(e))\n\nException message: Build graph construction failed: RuntimeError cannot use from_handle() on NULL pointer\n\n\n' .pants.d/pyprep/sources/4d9f3a72ced4c3b5cabbfead9552e9e3e78a30ca/pants_test/base/test_exception_sink_integration.py:151: AssertionError -------------- Captured stdout call -------------- logs/exceptions.84142.log +++ logs/exceptions.84142.log >>> timestamp: 2018-11-29T23:28:22.605908 logs/exceptions.84142.log >>> process title: python /Users/travis/build/pantsbuild/pants/src/python/pants/bin/pants_loader.py --no-pantsrc --pants-workdir=/var/folders/bb/n7t3rs157850byt_jfdcq9k80000gn/T/tmpxqSksJ/.pants.d --kill-nailguns --print-exception-stacktrace=True --no-enable-pantsd run testprojects/src/python/coordinated_runs:waiter -- /var/folders/bb/n7t3rs157850byt_jfdcq9k80000gn/T/tmpxqSksJ/some_file logs/exceptions.84142.log >>> sys.argv: ['/Users/travis/build/pantsbuild/pants/src/python/pants/bin/pants_loader.py', '--no-pantsrc', '--pants-workdir=/var/folders/bb/n7t3rs157850byt_jfdcq9k80000gn/T/tmpxqSksJ/.pants.d', '--kill-nailguns', '--print-exception-stacktrace=True', '--no-enable-pantsd', 'run', 'testprojects/src/python/coordinated_runs:waiter', '--', '/var/folders/bb/n7t3rs157850byt_jfdcq9k80000gn/T/tmpxqSksJ/some_file'] logs/exceptions.84142.log >>> pid: 84142 logs/exceptions.84142.log >>> Exception caught: (pants.build_graph.address_lookup_error.AddressLookupError) logs/exceptions.84142.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/pants_loader.py", line 75, in <module> logs/exceptions.84142.log >>> main() logs/exceptions.84142.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/pants_loader.py", line 71, in main logs/exceptions.84142.log >>> PantsLoader.run() logs/exceptions.84142.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/pants_loader.py", line 67, in run logs/exceptions.84142.log >>> cls.load_and_execute(entrypoint) logs/exceptions.84142.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/pants_loader.py", line 60, in load_and_execute logs/exceptions.84142.log >>> entrypoint_main() logs/exceptions.84142.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/pants_exe.py", line 39, in main logs/exceptions.84142.log >>> PantsRunner(exiter, start_time=start_time).run() logs/exceptions.84142.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/pants_runner.py", line 62, in run logs/exceptions.84142.log >>> return runner.run() logs/exceptions.84142.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/local_pants_runner.py", line 159, in run logs/exceptions.84142.log >>> self._run() logs/exceptions.84142.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/local_pants_runner.py", line 227, in _run logs/exceptions.84142.log >>> goal_runner_result = self._maybe_run_v1(run_tracker, reporting) logs/exceptions.84142.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/local_pants_runner.py", line 176, in _maybe_run_v1 logs/exceptions.84142.log >>> return goal_runner_factory.create().run() logs/exceptions.84142.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/goal_runner.py", line 125, in create logs/exceptions.84142.log >>> goals, context = self._setup_context() logs/exceptions.84142.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/goal_runner.py", line 95, in _setup_context logs/exceptions.84142.log >>> self._root_dir logs/exceptions.84142.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/init/engine_initializer.py", line 226, in create_build_graph logs/exceptions.84142.log >>> for _ in graph.inject_roots_closure(target_roots): logs/exceptions.84142.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/engine/legacy/graph.py", line 217, in inject_roots_closure logs/exceptions.84142.log >>> for address in self._inject_specs(target_roots.specs): logs/exceptions.84142.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/engine/legacy/graph.py", line 270, in _inject_specs logs/exceptions.84142.log >>> subjects) logs/exceptions.84142.log >>> File "/usr/local/Cellar/python/2.7.14/Frameworks/Python.framework/Versions/2.7/lib/python2.7/contextlib.py", line 35, in __exit__ logs/exceptions.84142.log >>> self.gen.throw(type, value, traceback) logs/exceptions.84142.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/engine/legacy/graph.py", line 237, in _resolve_context logs/exceptions.84142.log >>> 'Build graph construction failed: {} {}'.format(type(e).__name__, str(e)) logs/exceptions.84142.log >>> logs/exceptions.84142.log >>> Exception message: Build graph construction failed: RuntimeError cannot use from_handle() on NULL pointer logs/exceptions.84142.log >>> logs/exceptions.84142.log --- logs/exceptions.log +++ logs/exceptions.log >>> timestamp: 2018-11-29T23:28:22.605908 logs/exceptions.log >>> process title: python /Users/travis/build/pantsbuild/pants/src/python/pants/bin/pants_loader.py --no-pantsrc --pants-workdir=/var/folders/bb/n7t3rs157850byt_jfdcq9k80000gn/T/tmpxqSksJ/.pants.d --kill-nailguns --print-exception-stacktrace=True --no-enable-pantsd run testprojects/src/python/coordinated_runs:waiter -- /var/folders/bb/n7t3rs157850byt_jfdcq9k80000gn/T/tmpxqSksJ/some_file logs/exceptions.log >>> sys.argv: ['/Users/travis/build/pantsbuild/pants/src/python/pants/bin/pants_loader.py', '--no-pantsrc', '--pants-workdir=/var/folders/bb/n7t3rs157850byt_jfdcq9k80000gn/T/tmpxqSksJ/.pants.d', '--kill-nailguns', '--print-exception-stacktrace=True', '--no-enable-pantsd', 'run', 'testprojects/src/python/coordinated_runs:waiter', '--', '/var/folders/bb/n7t3rs157850byt_jfdcq9k80000gn/T/tmpxqSksJ/some_file'] logs/exceptions.log >>> pid: 84142 logs/exceptions.log >>> Exception caught: (pants.build_graph.address_lookup_error.AddressLookupError) logs/exceptions.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/pants_loader.py", line 75, in <module> logs/exceptions.log >>> main() logs/exceptions.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/pants_loader.py", line 71, in main logs/exceptions.log >>> PantsLoader.run() logs/exceptions.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/pants_loader.py", line 67, in run logs/exceptions.log >>> cls.load_and_execute(entrypoint) logs/exceptions.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/pants_loader.py", line 60, in load_and_execute logs/exceptions.log >>> entrypoint_main() logs/exceptions.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/pants_exe.py", line 39, in main logs/exceptions.log >>> PantsRunner(exiter, start_time=start_time).run() logs/exceptions.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/pants_runner.py", line 62, in run logs/exceptions.log >>> return runner.run() logs/exceptions.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/local_pants_runner.py", line 159, in run logs/exceptions.log >>> self._run() logs/exceptions.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/local_pants_runner.py", line 227, in _run logs/exceptions.log >>> goal_runner_result = self._maybe_run_v1(run_tracker, reporting) logs/exceptions.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/local_pants_runner.py", line 176, in _maybe_run_v1 logs/exceptions.log >>> return goal_runner_factory.create().run() logs/exceptions.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/goal_runner.py", line 125, in create logs/exceptions.log >>> goals, context = self._setup_context() logs/exceptions.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/bin/goal_runner.py", line 95, in _setup_context logs/exceptions.log >>> self._root_dir logs/exceptions.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/init/engine_initializer.py", line 226, in create_build_graph logs/exceptions.log >>> for _ in graph.inject_roots_closure(target_roots): logs/exceptions.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/engine/legacy/graph.py", line 217, in inject_roots_closure logs/exceptions.log >>> for address in self._inject_specs(target_roots.specs): logs/exceptions.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/engine/legacy/graph.py", line 270, in _inject_specs logs/exceptions.log >>> subjects) logs/exceptions.log >>> File "/usr/local/Cellar/python/2.7.14/Frameworks/Python.framework/Versions/2.7/lib/python2.7/contextlib.py", line 35, in __exit__ logs/exceptions.log >>> self.gen.throw(type, value, traceback) logs/exceptions.log >>> File "/Users/travis/build/pantsbuild/pants/src/python/pants/engine/legacy/graph.py", line 237, in _resolve_context logs/exceptions.log >>> 'Build graph construction failed: {} {}'.format(type(e).__name__, str(e)) logs/exceptions.log >>> logs/exceptions.log >>> Exception message: Build graph construction failed: RuntimeError cannot use from_handle() on NULL pointer logs/exceptions.log >>> logs/exceptions.log --- generated xml file: /Users/travis/build/pantsbuild/pants/.pants.d/test/pytest/tests.python.pants_test.base.exception_sink_integration/junitxml/TEST-tests.python.pants_test.base.exception_sink_integration.xml ============ slowest 3 test durations ============ 93.67s call ../tests/python/pants_test/base/test_exception_sink_integration.py::ExceptionSinkIntegrationTest::test_dumps_traceback_on_sigabrt 6.08s call ../tests/python/pants_test/base/test_exception_sink_integration.py::ExceptionSinkIntegrationTest::test_prints_traceback_on_sigusr2 5.55s call ../tests/python/pants_test/base/test_exception_sink_integration.py::ExceptionSinkIntegrationTest::test_reset_interactive_output_stream 1 failed, 5 passed, 1 skipped in 118.85 seconds =
AssertionError