pydevd.py 153 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740
  1. """
  2. Entry point module (keep at root):
  3. This module starts the debugger.
  4. """
  5. import sys # @NoMove
  6. if sys.version_info[:2] < (3, 6):
  7. raise RuntimeError(
  8. "The PyDev.Debugger requires Python 3.6 onwards to be run. If you need to use an older Python version, use an older version of the debugger."
  9. )
  10. import os
  11. # On the first import of a pydevd module, add pydevd itself to the PYTHONPATH
  12. this_dir = os.path.dirname(os.path.abspath(__file__))
  13. sys.path.insert(0, this_dir)
  14. import _pydev_bundle
  15. # Import this first as it'll check for shadowed modules and will make sure that we import
  16. # things as needed for gevent.
  17. from _pydevd_bundle import pydevd_constants
  18. from typing import Optional, Tuple
  19. from types import FrameType
  20. import atexit
  21. import dis
  22. import io
  23. from collections import defaultdict
  24. from contextlib import contextmanager
  25. from functools import partial
  26. import itertools
  27. import traceback
  28. import weakref
  29. import getpass as getpass_mod
  30. import functools
  31. import pydevd_file_utils
  32. from _pydevd_bundle.pydevd_dont_trace_files import LIB_FILES_IN_DONT_TRACE_DIRS
  33. from _pydev_bundle import pydev_imports, pydev_log
  34. from _pydev_bundle._pydev_filesystem_encoding import getfilesystemencoding
  35. from _pydev_bundle.pydev_is_thread_alive import is_thread_alive
  36. from _pydev_bundle.pydev_override import overrides
  37. from _pydev_bundle._pydev_saved_modules import threading, time, thread, ThreadingEvent
  38. from _pydevd_bundle import pydevd_extension_utils, pydevd_frame_utils
  39. from _pydevd_bundle.pydevd_filtering import FilesFiltering, glob_matches_path
  40. from _pydevd_bundle import pydevd_io, pydevd_vm_type, pydevd_defaults
  41. from _pydevd_bundle import pydevd_utils
  42. from _pydevd_bundle import pydevd_runpy
  43. from _pydev_bundle.pydev_console_utils import DebugConsoleStdIn
  44. from _pydevd_bundle.pydevd_additional_thread_info import set_additional_thread_info, remove_additional_info
  45. from _pydevd_bundle.pydevd_breakpoints import ExceptionBreakpoint, get_exception_breakpoint
  46. from _pydevd_bundle.pydevd_comm_constants import (
  47. CMD_THREAD_SUSPEND,
  48. CMD_STEP_INTO,
  49. CMD_SET_BREAK,
  50. CMD_STEP_INTO_MY_CODE,
  51. CMD_STEP_OVER,
  52. CMD_SMART_STEP_INTO,
  53. CMD_RUN_TO_LINE,
  54. CMD_SET_NEXT_STATEMENT,
  55. CMD_STEP_RETURN,
  56. CMD_ADD_EXCEPTION_BREAK,
  57. CMD_STEP_RETURN_MY_CODE,
  58. CMD_STEP_OVER_MY_CODE,
  59. constant_to_str,
  60. CMD_STEP_INTO_COROUTINE,
  61. )
  62. from _pydevd_bundle.pydevd_constants import (
  63. get_thread_id,
  64. get_current_thread_id,
  65. DebugInfoHolder,
  66. PYTHON_SUSPEND,
  67. STATE_SUSPEND,
  68. STATE_RUN,
  69. get_frame,
  70. clear_cached_thread_id,
  71. INTERACTIVE_MODE_AVAILABLE,
  72. SHOW_DEBUG_INFO_ENV,
  73. NULL,
  74. NO_FTRACE,
  75. IS_IRONPYTHON,
  76. JSON_PROTOCOL,
  77. IS_CPYTHON,
  78. HTTP_JSON_PROTOCOL,
  79. USE_CUSTOM_SYS_CURRENT_FRAMES_MAP,
  80. call_only_once,
  81. ForkSafeLock,
  82. IGNORE_BASENAMES_STARTING_WITH,
  83. EXCEPTION_TYPE_UNHANDLED,
  84. SUPPORT_GEVENT,
  85. PYDEVD_IPYTHON_COMPATIBLE_DEBUGGING,
  86. PYDEVD_IPYTHON_CONTEXT,
  87. PYDEVD_USE_SYS_MONITORING,
  88. IS_PY314_OR_GREATER,
  89. )
  90. from _pydevd_bundle.pydevd_defaults import PydevdCustomization # Note: import alias used on pydev_monkey.
  91. from _pydevd_bundle.pydevd_custom_frames import CustomFramesContainer, custom_frames_container_init
  92. from _pydevd_bundle.pydevd_dont_trace_files import DONT_TRACE, PYDEV_FILE, LIB_FILE, DONT_TRACE_DIRS
  93. from _pydevd_bundle.pydevd_extension_api import DebuggerEventHandler
  94. from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, remove_exception_from_frame, short_stack
  95. from _pydevd_bundle.pydevd_net_command_factory_xml import NetCommandFactory
  96. from _pydevd_bundle.pydevd_trace_dispatch import (
  97. trace_dispatch as _trace_dispatch,
  98. global_cache_skips,
  99. global_cache_frame_skips,
  100. fix_top_level_trace_and_get_trace_func,
  101. USING_CYTHON,
  102. )
  103. from _pydevd_bundle.pydevd_utils import save_main_module, is_current_thread_main_thread, import_attr_from_module
  104. from _pydevd_frame_eval.pydevd_frame_eval_main import frame_eval_func, dummy_trace_dispatch, USING_FRAME_EVAL
  105. import pydev_ipython # @UnusedImport
  106. from _pydevd_bundle.pydevd_source_mapping import SourceMapping
  107. from _pydevd_bundle.pydevd_concurrency_analyser.pydevd_concurrency_logger import (
  108. ThreadingLogger,
  109. AsyncioLogger,
  110. send_concurrency_message,
  111. cur_time,
  112. )
  113. from _pydevd_bundle.pydevd_concurrency_analyser.pydevd_thread_wrappers import wrap_threads
  114. from pydevd_file_utils import (
  115. get_abs_path_real_path_and_base_from_frame,
  116. get_abs_path_real_path_and_base_from_file,
  117. NORM_PATHS_AND_BASE_CONTAINER,
  118. )
  119. from pydevd_file_utils import get_fullname, get_package_dir
  120. from os.path import abspath as os_path_abspath
  121. import pydevd_tracing
  122. from _pydevd_bundle.pydevd_comm import InternalThreadCommand, InternalThreadCommandForAnyThread, create_server_socket, FSNotifyThread
  123. from _pydevd_bundle.pydevd_comm import (
  124. InternalConsoleExec,
  125. _queue,
  126. ReaderThread,
  127. GetGlobalDebugger,
  128. get_global_debugger,
  129. set_global_debugger,
  130. WriterThread,
  131. start_client,
  132. start_server,
  133. InternalGetBreakpointException,
  134. InternalSendCurrExceptionTrace,
  135. InternalSendCurrExceptionTraceProceeded,
  136. )
  137. from _pydevd_bundle.pydevd_daemon_thread import PyDBDaemonThread, mark_as_pydevd_daemon_thread
  138. from _pydevd_bundle.pydevd_process_net_command_json import PyDevJsonCommandProcessor
  139. from _pydevd_bundle.pydevd_process_net_command import process_net_command
  140. from _pydevd_bundle.pydevd_net_command import NetCommand, NULL_NET_COMMAND
  141. from _pydevd_bundle.pydevd_breakpoints import stop_on_unhandled_exception
  142. from _pydevd_bundle.pydevd_collect_bytecode_info import collect_try_except_info, collect_return_info, collect_try_except_info_from_source
  143. from _pydevd_bundle.pydevd_suspended_frames import SuspendedFramesManager
  144. from socket import SHUT_RDWR
  145. from _pydevd_bundle.pydevd_api import PyDevdAPI
  146. from _pydevd_bundle.pydevd_timeout import TimeoutTracker
  147. from _pydevd_bundle.pydevd_thread_lifecycle import suspend_all_threads, mark_thread_suspended
  148. if PYDEVD_USE_SYS_MONITORING:
  149. from _pydevd_sys_monitoring import pydevd_sys_monitoring
  150. pydevd_gevent_integration = None
  151. if SUPPORT_GEVENT:
  152. try:
  153. from _pydevd_bundle import pydevd_gevent_integration
  154. except:
  155. pydev_log.exception(
  156. "pydevd: GEVENT_SUPPORT is set but gevent is not available in the environment.\n"
  157. "Please unset GEVENT_SUPPORT from the environment variables or install gevent."
  158. )
  159. else:
  160. pydevd_gevent_integration.log_gevent_debug_info()
  161. if USE_CUSTOM_SYS_CURRENT_FRAMES_MAP:
  162. from _pydevd_bundle.pydevd_constants import constructed_tid_to_last_frame
  163. __version_info__ = (3, 2, 3)
  164. __version_info_str__ = []
  165. for v in __version_info__:
  166. __version_info_str__.append(str(v))
  167. __version__ = ".".join(__version_info_str__)
  168. # IMPORTANT: pydevd_constants must be the 1st thing defined because it'll keep a reference to the original sys._getframe
  169. def install_breakpointhook(pydevd_breakpointhook=None):
  170. if pydevd_breakpointhook is None:
  171. def pydevd_breakpointhook(*args, **kwargs):
  172. hookname = os.getenv("PYTHONBREAKPOINT")
  173. if (
  174. hookname is not None
  175. and len(hookname) > 0
  176. and hasattr(sys, "__breakpointhook__")
  177. and sys.__breakpointhook__ != pydevd_breakpointhook
  178. ):
  179. sys.__breakpointhook__(*args, **kwargs)
  180. else:
  181. settrace(*args, **kwargs)
  182. if sys.version_info[0:2] >= (3, 7):
  183. # There are some choices on how to provide the breakpoint hook. Namely, we can provide a
  184. # PYTHONBREAKPOINT which provides the import path for a method to be executed or we
  185. # can override sys.breakpointhook.
  186. # pydevd overrides sys.breakpointhook instead of providing an environment variable because
  187. # it's possible that the debugger starts the user program but is not available in the
  188. # PYTHONPATH (and would thus fail to be imported if PYTHONBREAKPOINT was set to pydevd.settrace).
  189. # Note that the implementation still takes PYTHONBREAKPOINT in account (so, if it was provided
  190. # by someone else, it'd still work).
  191. sys.breakpointhook = pydevd_breakpointhook
  192. else:
  193. if sys.version_info[0] >= 3:
  194. import builtins as __builtin__ # Py3 noqa
  195. else:
  196. import __builtin__ # noqa
  197. # In older versions, breakpoint() isn't really available, so, install the hook directly
  198. # in the builtins.
  199. __builtin__.breakpoint = pydevd_breakpointhook
  200. sys.__breakpointhook__ = pydevd_breakpointhook
  201. # Install the breakpoint hook at import time.
  202. install_breakpointhook()
  203. from _pydevd_bundle.pydevd_plugin_utils import PluginManager
  204. threadingEnumerate = threading.enumerate
  205. threadingCurrentThread = threading.current_thread
  206. try:
  207. "dummy".encode("utf-8") # Added because otherwise Jython 2.2.1 wasn't finding the encoding (if it wasn't loaded in the main thread).
  208. except:
  209. pass
  210. _global_redirect_stdout_to_server = False
  211. _global_redirect_stderr_to_server = False
  212. file_system_encoding = getfilesystemencoding()
  213. _CACHE_FILE_TYPE = {}
  214. pydev_log.debug("Using GEVENT_SUPPORT: %s", pydevd_constants.SUPPORT_GEVENT)
  215. pydev_log.debug("Using GEVENT_SHOW_PAUSED_GREENLETS: %s", pydevd_constants.GEVENT_SHOW_PAUSED_GREENLETS)
  216. pydev_log.debug("pydevd __file__: %s", os.path.abspath(__file__))
  217. pydev_log.debug("Using PYDEVD_IPYTHON_COMPATIBLE_DEBUGGING: %s", pydevd_constants.PYDEVD_IPYTHON_COMPATIBLE_DEBUGGING)
  218. if pydevd_constants.PYDEVD_IPYTHON_COMPATIBLE_DEBUGGING:
  219. pydev_log.debug("PYDEVD_IPYTHON_CONTEXT: %s", pydevd_constants.PYDEVD_IPYTHON_CONTEXT)
  220. TIMEOUT_SLOW = 0.2
  221. TIMEOUT_FAST = 1.0 / 50
  222. # =======================================================================================================================
  223. # PyDBCommandThread
  224. # =======================================================================================================================
  225. class PyDBCommandThread(PyDBDaemonThread):
  226. def __init__(self, py_db):
  227. PyDBDaemonThread.__init__(self, py_db)
  228. self._py_db_command_thread_event = py_db._py_db_command_thread_event
  229. self.name = "pydevd.CommandThread"
  230. @overrides(PyDBDaemonThread._on_run)
  231. def _on_run(self):
  232. # Delay a bit this initialization to wait for the main program to start.
  233. self._py_db_command_thread_event.wait(TIMEOUT_SLOW)
  234. if self._kill_received:
  235. return
  236. try:
  237. while not self._kill_received:
  238. try:
  239. self.py_db.process_internal_commands(("*",))
  240. except:
  241. pydev_log.info("Finishing debug communication...(2)")
  242. self._py_db_command_thread_event.clear()
  243. self._py_db_command_thread_event.wait(TIMEOUT_SLOW)
  244. except:
  245. try:
  246. pydev_log.debug(sys.exc_info()[0])
  247. except:
  248. # In interpreter shutdown many things can go wrong (any module variables may
  249. # be None, streams can be closed, etc).
  250. pass
  251. # only got this error in interpreter shutdown
  252. # pydev_log.info('Finishing debug communication...(3)')
  253. @overrides(PyDBDaemonThread.do_kill_pydev_thread)
  254. def do_kill_pydev_thread(self):
  255. PyDBDaemonThread.do_kill_pydev_thread(self)
  256. # Set flag so that it can exit before the usual timeout.
  257. self._py_db_command_thread_event.set()
  258. # =======================================================================================================================
  259. # CheckAliveThread
  260. # Non-daemon thread: guarantees that all data is written even if program is finished
  261. # =======================================================================================================================
  262. class CheckAliveThread(PyDBDaemonThread):
  263. def __init__(self, py_db):
  264. PyDBDaemonThread.__init__(self, py_db)
  265. self.name = "pydevd.CheckAliveThread"
  266. self.daemon = False
  267. self._wait_event = ThreadingEvent()
  268. @overrides(PyDBDaemonThread._on_run)
  269. def _on_run(self):
  270. py_db = self.py_db
  271. def can_exit():
  272. with py_db._main_lock:
  273. # Note: it's important to get the lock besides checking that it's empty (this
  274. # means that we're not in the middle of some command processing).
  275. writer = py_db.writer
  276. writer_empty = writer is not None and writer.empty()
  277. return not py_db.has_user_threads_alive() and writer_empty
  278. try:
  279. while not self._kill_received:
  280. self._wait_event.wait(TIMEOUT_SLOW)
  281. if can_exit():
  282. break
  283. py_db.check_output_redirect()
  284. if can_exit():
  285. pydev_log.debug("No threads alive, finishing debug session")
  286. py_db.dispose_and_kill_all_pydevd_threads()
  287. except:
  288. pydev_log.exception()
  289. def join(self, timeout=None):
  290. # If someone tries to join this thread, mark it to be killed.
  291. # This is the case for CherryPy when auto-reload is turned on.
  292. self.do_kill_pydev_thread()
  293. PyDBDaemonThread.join(self, timeout=timeout)
  294. @overrides(PyDBDaemonThread.do_kill_pydev_thread)
  295. def do_kill_pydev_thread(self):
  296. PyDBDaemonThread.do_kill_pydev_thread(self)
  297. # Set flag so that it can exit before the usual timeout.
  298. self._wait_event.set()
  299. class AbstractSingleNotificationBehavior(object):
  300. """
  301. The basic usage should be:
  302. # Increment the request time for the suspend.
  303. single_notification_behavior.increment_suspend_time()
  304. # Notify that this is a pause request (when a pause, not a breakpoint).
  305. single_notification_behavior.on_pause()
  306. # Mark threads to be suspended.
  307. set_suspend(...)
  308. # On do_wait_suspend, use notify_thread_suspended:
  309. def do_wait_suspend(...):
  310. with single_notification_behavior.notify_thread_suspended(thread_id, thread, reason):
  311. ...
  312. """
  313. __slots__ = [
  314. "_last_resume_notification_time",
  315. "_last_suspend_notification_time",
  316. "_lock",
  317. "_next_request_time",
  318. "_suspend_time_request",
  319. "_suspended_thread_id_to_thread",
  320. "_pause_requested",
  321. "_py_db",
  322. ]
  323. NOTIFY_OF_PAUSE_TIMEOUT = 0.5
  324. def __init__(self, py_db):
  325. self._py_db = weakref.ref(py_db)
  326. self._next_request_time = partial(next, itertools.count())
  327. self._last_suspend_notification_time = -1
  328. self._last_resume_notification_time = -1
  329. self._suspend_time_request = self._next_request_time()
  330. self._lock = thread.allocate_lock()
  331. self._suspended_thread_id_to_thread = {}
  332. self._pause_requested = False
  333. def send_suspend_notification(self, thread_id, thread, stop_reason):
  334. raise AssertionError("abstract: subclasses must override.")
  335. def send_resume_notification(self, thread_id):
  336. raise AssertionError("abstract: subclasses must override.")
  337. def increment_suspend_time(self):
  338. with self._lock:
  339. self._suspend_time_request = self._next_request_time()
  340. def on_pause(self):
  341. # Upon a pause, we should force sending new suspend notifications
  342. # if no notification is sent after some time and there's some thread already stopped.
  343. with self._lock:
  344. self._pause_requested = True
  345. global_suspend_time = self._suspend_time_request
  346. py_db = self._py_db()
  347. if py_db is not None:
  348. py_db.timeout_tracker.call_on_timeout(
  349. self.NOTIFY_OF_PAUSE_TIMEOUT, self._notify_after_timeout, kwargs={"global_suspend_time": global_suspend_time}
  350. )
  351. def _notify_after_timeout(self, global_suspend_time):
  352. with self._lock:
  353. if self._suspended_thread_id_to_thread:
  354. if global_suspend_time > self._last_suspend_notification_time:
  355. self._last_suspend_notification_time = global_suspend_time
  356. # Notify about any thread which is currently suspended.
  357. pydev_log.info("Sending suspend notification after timeout.")
  358. thread_id, thread = next(iter(self._suspended_thread_id_to_thread.items()))
  359. self.send_suspend_notification(thread_id, thread, CMD_THREAD_SUSPEND)
  360. def on_thread_suspend(self, thread_id, thread, stop_reason):
  361. with self._lock:
  362. pause_requested = self._pause_requested
  363. if pause_requested:
  364. # When a suspend notification is sent, reset the pause flag.
  365. self._pause_requested = False
  366. self._suspended_thread_id_to_thread[thread_id] = thread
  367. # CMD_THREAD_SUSPEND should always be a side-effect of a break, so, only
  368. # issue for a CMD_THREAD_SUSPEND if a pause is pending.
  369. if stop_reason != CMD_THREAD_SUSPEND or pause_requested:
  370. if self._suspend_time_request > self._last_suspend_notification_time:
  371. pydev_log.info("Sending suspend notification.")
  372. self._last_suspend_notification_time = self._suspend_time_request
  373. self.send_suspend_notification(thread_id, thread, stop_reason)
  374. else:
  375. pydev_log.info(
  376. "Suspend not sent (it was already sent). Last suspend % <= Last resume %s",
  377. self._last_suspend_notification_time,
  378. self._last_resume_notification_time,
  379. )
  380. else:
  381. pydev_log.info(
  382. "Suspend not sent because stop reason is thread suspend and pause was not requested.",
  383. )
  384. def on_thread_resume(self, thread_id, thread):
  385. # on resume (step, continue all):
  386. with self._lock:
  387. self._suspended_thread_id_to_thread.pop(thread_id)
  388. if self._last_resume_notification_time < self._last_suspend_notification_time:
  389. pydev_log.info("Sending resume notification.")
  390. self._last_resume_notification_time = self._last_suspend_notification_time
  391. self.send_resume_notification(thread_id)
  392. else:
  393. pydev_log.info(
  394. "Resume not sent (it was already sent). Last resume %s >= Last suspend %s",
  395. self._last_resume_notification_time,
  396. self._last_suspend_notification_time,
  397. )
  398. @contextmanager
  399. def notify_thread_suspended(self, thread_id, thread, stop_reason):
  400. self.on_thread_suspend(thread_id, thread, stop_reason)
  401. try:
  402. yield # At this point the thread must be actually suspended.
  403. finally:
  404. self.on_thread_resume(thread_id, thread)
  405. class ThreadsSuspendedSingleNotification(AbstractSingleNotificationBehavior):
  406. __slots__ = AbstractSingleNotificationBehavior.__slots__ + ["multi_threads_single_notification", "_callbacks", "_callbacks_lock"]
  407. def __init__(self, py_db):
  408. AbstractSingleNotificationBehavior.__init__(self, py_db)
  409. # If True, pydevd will send a single notification when all threads are suspended/resumed.
  410. self.multi_threads_single_notification = False
  411. self._callbacks_lock = threading.Lock()
  412. self._callbacks = []
  413. def add_on_resumed_callback(self, callback):
  414. with self._callbacks_lock:
  415. self._callbacks.append(callback)
  416. @overrides(AbstractSingleNotificationBehavior.send_resume_notification)
  417. def send_resume_notification(self, thread_id):
  418. py_db = self._py_db()
  419. if py_db is not None:
  420. py_db.writer.add_command(py_db.cmd_factory.make_thread_resume_single_notification(thread_id))
  421. with self._callbacks_lock:
  422. callbacks = self._callbacks
  423. self._callbacks = []
  424. for callback in callbacks:
  425. callback()
  426. @overrides(AbstractSingleNotificationBehavior.send_suspend_notification)
  427. def send_suspend_notification(self, thread_id, thread, stop_reason):
  428. py_db = self._py_db()
  429. if py_db is not None:
  430. py_db.writer.add_command(py_db.cmd_factory.make_thread_suspend_single_notification(py_db, thread_id, thread, stop_reason))
  431. @overrides(AbstractSingleNotificationBehavior.notify_thread_suspended)
  432. @contextmanager
  433. def notify_thread_suspended(self, thread_id, thread, stop_reason):
  434. if self.multi_threads_single_notification:
  435. pydev_log.info("Thread suspend mode: single notification")
  436. with AbstractSingleNotificationBehavior.notify_thread_suspended(self, thread_id, thread, stop_reason):
  437. yield
  438. else:
  439. pydev_log.info("Thread suspend mode: NOT single notification")
  440. yield
  441. class _Authentication(object):
  442. __slots__ = ["access_token", "client_access_token", "_authenticated", "_wrong_attempts"]
  443. def __init__(self):
  444. # A token to be send in the command line or through the settrace api -- when such token
  445. # is given, the first message sent to the IDE must pass the same token to authenticate.
  446. # Note that if a disconnect is sent, the same message must be resent to authenticate.
  447. self.access_token = None
  448. # This token is the one that the client requires to accept a connection from pydevd
  449. # (it's stored here and just passed back when required, it's not used internally
  450. # for anything else).
  451. self.client_access_token = None
  452. self._authenticated = None
  453. self._wrong_attempts = 0
  454. def is_authenticated(self):
  455. if self._authenticated is None:
  456. return self.access_token is None
  457. return self._authenticated
  458. def login(self, access_token):
  459. if self._wrong_attempts >= 10: # A user can fail to authenticate at most 10 times.
  460. return
  461. self._authenticated = access_token == self.access_token
  462. if not self._authenticated:
  463. self._wrong_attempts += 1
  464. else:
  465. self._wrong_attempts = 0
  466. def logout(self):
  467. self._authenticated = None
  468. self._wrong_attempts = 0
  469. class PyDB(object):
  470. """Main debugging class
  471. Lots of stuff going on here:
  472. PyDB starts two threads on startup that connect to remote debugger (RDB)
  473. The threads continuously read & write commands to RDB.
  474. PyDB communicates with these threads through command queues.
  475. Every RDB command is processed by calling process_net_command.
  476. Every PyDB net command is sent to the net by posting NetCommand to WriterThread queue
  477. Some commands need to be executed on the right thread (suspend/resume & friends)
  478. These are placed on the internal command queue.
  479. """
  480. # Direct child pids which should not be terminated when terminating processes.
  481. # Note: class instance because it should outlive PyDB instances.
  482. dont_terminate_child_pids = set()
  483. def __init__(self, set_as_global=True):
  484. if set_as_global:
  485. pydevd_tracing.replace_sys_set_trace_func()
  486. self.authentication = _Authentication()
  487. self.reader = None
  488. self.writer = None
  489. self._fsnotify_thread = None
  490. self.created_pydb_daemon_threads = {}
  491. self._waiting_for_connection_thread = None
  492. self._on_configuration_done_event = ThreadingEvent()
  493. self.check_alive_thread = None
  494. self.py_db_command_thread = None
  495. self.quitting = None
  496. self.cmd_factory = NetCommandFactory()
  497. self._cmd_queue = defaultdict(_queue.Queue) # Key is thread id or '*', value is Queue
  498. self._thread_events = defaultdict(ThreadingEvent) # Key is thread id or '*', value is Event
  499. self.suspended_frames_manager = SuspendedFramesManager()
  500. self._files_filtering = FilesFiltering()
  501. self.timeout_tracker = TimeoutTracker(self)
  502. # Note: when the source mapping is changed we also have to clear the file types cache
  503. # (because if a given file is a part of the project or not may depend on it being
  504. # defined in the source mapping).
  505. self.source_mapping = SourceMapping(on_source_mapping_changed=self._clear_caches)
  506. # Determines whether we should terminate child processes when asked to terminate.
  507. self.terminate_child_processes = True
  508. # Determines whether we should try to do a soft terminate (i.e.: interrupt the main
  509. # thread with a KeyboardInterrupt).
  510. self.terminate_keyboard_interrupt = False
  511. # Set to True after a keyboard interrupt is requested the first time.
  512. self.keyboard_interrupt_requested = False
  513. # These are the breakpoints received by the PyDevdAPI. They are meant to store
  514. # the breakpoints in the api -- its actual contents are managed by the api.
  515. self.api_received_breakpoints = {}
  516. # These are the breakpoints meant to be consumed during runtime.
  517. self.breakpoints = {}
  518. self.function_breakpoint_name_to_breakpoint = {}
  519. # Set communication protocol
  520. PyDevdAPI().set_protocol(self, 0, PydevdCustomization.DEFAULT_PROTOCOL)
  521. self.variable_presentation = PyDevdAPI.VariablePresentation()
  522. # mtime to be raised when something that will affect the
  523. # tracing in place (such as breakpoints change or filtering).
  524. self.mtime = 0
  525. self.file_to_id_to_line_breakpoint = {}
  526. self.file_to_id_to_plugin_breakpoint = {}
  527. # Note: breakpoints dict should not be mutated: a copy should be created
  528. # and later it should be assigned back (to prevent concurrency issues).
  529. self.break_on_uncaught_exceptions = {}
  530. self.break_on_caught_exceptions = {}
  531. self.break_on_user_uncaught_exceptions = {}
  532. self.ready_to_run = False
  533. self._main_lock = thread.allocate_lock()
  534. self._lock_running_thread_ids = thread.allocate_lock()
  535. self._lock_create_fs_notify = thread.allocate_lock()
  536. self._py_db_command_thread_event = ThreadingEvent()
  537. if set_as_global:
  538. CustomFramesContainer._py_db_command_thread_event = self._py_db_command_thread_event
  539. self.pydb_disposed = False
  540. self._wait_for_threads_to_finish_called = False
  541. self._wait_for_threads_to_finish_called_lock = thread.allocate_lock()
  542. self._wait_for_threads_to_finish_called_event = ThreadingEvent()
  543. self.terminate_requested = False
  544. self._disposed_lock = thread.allocate_lock()
  545. self.signature_factory = None
  546. self.SetTrace = pydevd_tracing.SetTrace
  547. self.skip_on_exceptions_thrown_in_same_context = False
  548. self.ignore_exceptions_thrown_in_lines_with_ignore_exception = True
  549. # Suspend debugger even if breakpoint condition raises an exception.
  550. # May be changed with CMD_PYDEVD_JSON_CONFIG.
  551. self.skip_suspend_on_breakpoint_exception = () # By default suspend on any Exception.
  552. self.skip_print_breakpoint_exception = () # By default print on any Exception.
  553. # By default user can step into properties getter/setter/deleter methods
  554. self.disable_property_trace = False
  555. self.disable_property_getter_trace = False
  556. self.disable_property_setter_trace = False
  557. self.disable_property_deleter_trace = False
  558. # this is a dict of thread ids pointing to thread ids. Whenever a command is passed to the java end that
  559. # acknowledges that a thread was created, the thread id should be passed here -- and if at some time we do not
  560. # find that thread alive anymore, we must remove it from this list and make the java side know that the thread
  561. # was killed.
  562. self._running_thread_ids = {}
  563. # Note: also access '_enable_thread_notifications' with '_lock_running_thread_ids'
  564. self._enable_thread_notifications = False
  565. self._set_breakpoints_with_id = False
  566. # This attribute holds the file-> lines which have an @IgnoreException.
  567. self.filename_to_lines_where_exceptions_are_ignored = {}
  568. # working with plugins (lazily initialized)
  569. self.plugin = None
  570. self.has_plugin_line_breaks = False
  571. self.has_plugin_exception_breaks = False
  572. self.thread_analyser = None
  573. self.asyncio_analyser = None
  574. # The GUI event loop that's going to run.
  575. # Possible values:
  576. # matplotlib - Whatever GUI backend matplotlib is using.
  577. # 'wx'/'qt'/'none'/... - GUI toolkits that have bulitin support. See pydevd_ipython/inputhook.py:24.
  578. # Other - A custom function that'll be imported and run.
  579. self._gui_event_loop = "matplotlib"
  580. self._installed_gui_support = False
  581. self.gui_in_use = False
  582. # GUI event loop support in debugger
  583. self.activate_gui_function = None
  584. # matplotlib support in debugger and debug console
  585. self.mpl_hooks_in_debug_console = False
  586. self.mpl_modules_for_patching = {}
  587. self._filename_to_not_in_scope = {}
  588. self.first_breakpoint_reached = False
  589. self._exclude_filters_enabled = self._files_filtering.use_exclude_filters()
  590. self._is_libraries_filter_enabled = self._files_filtering.use_libraries_filter()
  591. self.is_files_filter_enabled = self._exclude_filters_enabled or self._is_libraries_filter_enabled
  592. self.show_return_values = False
  593. self.remove_return_values_flag = False
  594. self.redirect_output = False
  595. # Note that besides the `redirect_output` flag, we also need to consider that someone
  596. # else is already redirecting (i.e.: debugpy).
  597. self.is_output_redirected = False
  598. # this flag disables frame evaluation even if it's available
  599. self.use_frame_eval = True
  600. # If True, pydevd will send a single notification when all threads are suspended/resumed.
  601. self._threads_suspended_single_notification = ThreadsSuspendedSingleNotification(self)
  602. # If True a step command will do a step in one thread and will also resume all other threads.
  603. self.stepping_resumes_all_threads = False
  604. self._local_thread_trace_func = threading.local()
  605. self._client_socket = None
  606. self._server_socket_ready_event = ThreadingEvent()
  607. self._server_socket_name = None
  608. # Bind many locals to the debugger because upon teardown those names may become None
  609. # in the namespace (and thus can't be relied upon unless the reference was previously
  610. # saved).
  611. if IS_IRONPYTHON:
  612. # A partial() cannot be used in IronPython for sys.settrace.
  613. def new_trace_dispatch(frame, event, arg):
  614. return _trace_dispatch(self, frame, event, arg)
  615. self.trace_dispatch = new_trace_dispatch
  616. else:
  617. self.trace_dispatch = partial(_trace_dispatch, self)
  618. self.fix_top_level_trace_and_get_trace_func = fix_top_level_trace_and_get_trace_func
  619. self.frame_eval_func = frame_eval_func
  620. self.dummy_trace_dispatch = dummy_trace_dispatch
  621. # Note: this is different from pydevd_constants.thread_get_ident because we want Jython
  622. # to be None here because it also doesn't have threading._active.
  623. try:
  624. self.threading_get_ident = threading.get_ident # Python 3
  625. self.threading_active = threading._active
  626. except:
  627. try:
  628. self.threading_get_ident = threading._get_ident # Python 2 noqa
  629. self.threading_active = threading._active
  630. except:
  631. self.threading_get_ident = None # Jython
  632. self.threading_active = None
  633. self.threading_current_thread = threading.currentThread
  634. self.set_additional_thread_info = set_additional_thread_info
  635. self.stop_on_unhandled_exception = stop_on_unhandled_exception
  636. self.collect_return_info = collect_return_info
  637. self.get_exception_breakpoint = get_exception_breakpoint
  638. self._dont_trace_get_file_type = DONT_TRACE.get
  639. self._dont_trace_dirs_get_file_type = DONT_TRACE_DIRS.get
  640. self.PYDEV_FILE = PYDEV_FILE
  641. self.LIB_FILE = LIB_FILE
  642. self._in_project_scope_cache = {}
  643. self._exclude_by_filter_cache = {}
  644. self._apply_filter_cache = {}
  645. self._ignore_system_exit_codes = set()
  646. # DAP related
  647. self._dap_messages_listeners = []
  648. if set_as_global:
  649. # Set as the global instance only after it's initialized.
  650. set_global_debugger(self)
  651. pydevd_defaults.on_pydb_init(self)
  652. # Stop the tracing as the last thing before the actual shutdown for a clean exit.
  653. atexit.register(stoptrace)
  654. def collect_try_except_info(self, code_obj):
  655. filename = code_obj.co_filename
  656. try:
  657. if os.path.exists(filename):
  658. pydev_log.debug("Collecting try..except info from source for %s", filename)
  659. try_except_infos = collect_try_except_info_from_source(filename)
  660. if try_except_infos:
  661. # Filter for the current function
  662. max_line = -1
  663. min_line = sys.maxsize
  664. for _, line in dis.findlinestarts(code_obj):
  665. if line is not None:
  666. if line > max_line:
  667. max_line = line
  668. if line < min_line:
  669. min_line = line
  670. try_except_infos = [x for x in try_except_infos if min_line <= x.try_line <= max_line]
  671. return try_except_infos
  672. except:
  673. pydev_log.exception("Error collecting try..except info from source (%s)", filename)
  674. pydev_log.debug("Collecting try..except info from bytecode for %s", filename)
  675. return collect_try_except_info(code_obj)
  676. def setup_auto_reload_watcher(self, enable_auto_reload, watch_dirs, poll_target_time, exclude_patterns, include_patterns):
  677. try:
  678. with self._lock_create_fs_notify:
  679. # When setting up, dispose of the previous one (if any).
  680. if self._fsnotify_thread is not None:
  681. self._fsnotify_thread.do_kill_pydev_thread()
  682. self._fsnotify_thread = None
  683. if not enable_auto_reload:
  684. return
  685. exclude_patterns = tuple(exclude_patterns)
  686. include_patterns = tuple(include_patterns)
  687. def accept_directory(absolute_filename, cache={}):
  688. try:
  689. return cache[absolute_filename]
  690. except:
  691. if absolute_filename and absolute_filename[-1] not in ("/", "\\"):
  692. # I.e.: for directories we always end with '/' or '\\' so that
  693. # we match exclusions such as "**/node_modules/**"
  694. absolute_filename += os.path.sep
  695. # First include what we want
  696. for include_pattern in include_patterns:
  697. if glob_matches_path(absolute_filename, include_pattern):
  698. cache[absolute_filename] = True
  699. return True
  700. # Then exclude what we don't want
  701. for exclude_pattern in exclude_patterns:
  702. if glob_matches_path(absolute_filename, exclude_pattern):
  703. cache[absolute_filename] = False
  704. return False
  705. # By default track all directories not excluded.
  706. cache[absolute_filename] = True
  707. return True
  708. def accept_file(absolute_filename, cache={}):
  709. try:
  710. return cache[absolute_filename]
  711. except:
  712. # First include what we want
  713. for include_pattern in include_patterns:
  714. if glob_matches_path(absolute_filename, include_pattern):
  715. cache[absolute_filename] = True
  716. return True
  717. # Then exclude what we don't want
  718. for exclude_pattern in exclude_patterns:
  719. if glob_matches_path(absolute_filename, exclude_pattern):
  720. cache[absolute_filename] = False
  721. return False
  722. # By default don't track files not included.
  723. cache[absolute_filename] = False
  724. return False
  725. self._fsnotify_thread = FSNotifyThread(self, PyDevdAPI(), watch_dirs)
  726. watcher = self._fsnotify_thread.watcher
  727. watcher.accept_directory = accept_directory
  728. watcher.accept_file = accept_file
  729. watcher.target_time_for_single_scan = poll_target_time
  730. watcher.target_time_for_notification = poll_target_time
  731. self._fsnotify_thread.start()
  732. except:
  733. pydev_log.exception("Error setting up auto-reload.")
  734. def get_arg_ppid(self):
  735. try:
  736. setup = SetupHolder.setup
  737. if setup:
  738. return int(setup.get("ppid", 0))
  739. except:
  740. pydev_log.exception("Error getting ppid.")
  741. return 0
  742. def wait_for_ready_to_run(self):
  743. while not self.ready_to_run:
  744. # busy wait until we receive run command
  745. self.process_internal_commands()
  746. self._py_db_command_thread_event.clear()
  747. self._py_db_command_thread_event.wait(TIMEOUT_FAST)
  748. def on_initialize(self):
  749. """
  750. Note: only called when using the DAP (Debug Adapter Protocol).
  751. """
  752. self._on_configuration_done_event.clear()
  753. def on_configuration_done(self):
  754. """
  755. Note: only called when using the DAP (Debug Adapter Protocol).
  756. """
  757. self._on_configuration_done_event.set()
  758. self._py_db_command_thread_event.set()
  759. def is_attached(self):
  760. return self._on_configuration_done_event.is_set()
  761. def on_disconnect(self):
  762. """
  763. Note: only called when using the DAP (Debug Adapter Protocol).
  764. """
  765. self.authentication.logout()
  766. self._on_configuration_done_event.clear()
  767. def set_ignore_system_exit_codes(self, ignore_system_exit_codes):
  768. assert isinstance(ignore_system_exit_codes, (list, tuple, set))
  769. self._ignore_system_exit_codes = set(ignore_system_exit_codes)
  770. def ignore_system_exit_code(self, system_exit_exc):
  771. if hasattr(system_exit_exc, "code"):
  772. return system_exit_exc.code in self._ignore_system_exit_codes
  773. else:
  774. return system_exit_exc in self._ignore_system_exit_codes
  775. def block_until_configuration_done(self, cancel=None):
  776. if cancel is None:
  777. cancel = NULL
  778. while not cancel.is_set():
  779. if self._on_configuration_done_event.is_set():
  780. cancel.set() # Set cancel to prevent reuse
  781. return
  782. self.process_internal_commands()
  783. self._py_db_command_thread_event.clear()
  784. self._py_db_command_thread_event.wait(TIMEOUT_FAST)
  785. def add_fake_frame(self, thread_id, frame_id, frame):
  786. self.suspended_frames_manager.add_fake_frame(thread_id, frame_id, frame)
  787. def handle_breakpoint_condition(self, info, pybreakpoint, new_frame):
  788. condition = pybreakpoint.condition
  789. try:
  790. if pybreakpoint.handle_hit_condition(new_frame):
  791. return True
  792. if not condition:
  793. return False
  794. return eval(condition, new_frame.f_globals, new_frame.f_locals)
  795. except Exception as e:
  796. if not isinstance(e, self.skip_print_breakpoint_exception):
  797. stack_trace = io.StringIO()
  798. etype, value, tb = sys.exc_info()
  799. traceback.print_exception(etype, value, tb.tb_next, file=stack_trace)
  800. msg = "Error while evaluating expression in conditional breakpoint: %s\n%s" % (condition, stack_trace.getvalue())
  801. api = PyDevdAPI()
  802. api.send_error_message(self, msg)
  803. if not isinstance(e, self.skip_suspend_on_breakpoint_exception):
  804. try:
  805. # add exception_type and stacktrace into thread additional info
  806. etype, value, tb = sys.exc_info()
  807. error = "".join(traceback.format_exception_only(etype, value))
  808. stack = traceback.extract_stack(f=tb.tb_frame.f_back)
  809. # On self.set_suspend(thread, CMD_SET_BREAK) this info will be
  810. # sent to the client.
  811. info.conditional_breakpoint_exception = ("Condition:\n" + condition + "\n\nError:\n" + error, stack)
  812. except:
  813. pydev_log.exception()
  814. return True
  815. return False
  816. finally:
  817. etype, value, tb = None, None, None
  818. def handle_breakpoint_expression(self, pybreakpoint, info, new_frame):
  819. try:
  820. try:
  821. val = eval(pybreakpoint.expression, new_frame.f_globals, new_frame.f_locals)
  822. except:
  823. val = sys.exc_info()[1]
  824. finally:
  825. if val is not None:
  826. info.pydev_message = str(val)
  827. def _internal_get_file_type(self, abs_real_path_and_basename):
  828. basename = abs_real_path_and_basename[-1]
  829. if basename.startswith(IGNORE_BASENAMES_STARTING_WITH) or abs_real_path_and_basename[0].startswith(IGNORE_BASENAMES_STARTING_WITH):
  830. # Note: these are the files that are completely ignored (they aren't shown to the user
  831. # as user nor library code as it's usually just noise in the frame stack).
  832. return self.PYDEV_FILE
  833. file_type = self._dont_trace_get_file_type(basename)
  834. if file_type is not None:
  835. return file_type
  836. if basename.startswith("__init__.py") or basename in LIB_FILES_IN_DONT_TRACE_DIRS:
  837. # i.e.: ignore the __init__ files inside pydevd (the other
  838. # files are ignored just by their name).
  839. abs_path = abs_real_path_and_basename[0]
  840. i = max(abs_path.rfind("/"), abs_path.rfind("\\"))
  841. if i:
  842. abs_path = abs_path[0:i]
  843. i = max(abs_path.rfind("/"), abs_path.rfind("\\"))
  844. if i:
  845. dirname = abs_path[i + 1:]
  846. # At this point, something as:
  847. # "my_path\_pydev_runfiles\__init__.py"
  848. # is now "_pydev_runfiles".
  849. return self._dont_trace_dirs_get_file_type(dirname)
  850. return None
  851. def dont_trace_external_files(self, abs_path):
  852. """
  853. :param abs_path:
  854. The result from get_abs_path_real_path_and_base_from_file or
  855. get_abs_path_real_path_and_base_from_frame.
  856. :return
  857. True :
  858. If files should NOT be traced.
  859. False:
  860. If files should be traced.
  861. """
  862. # By default all external files are traced. Note: this function is expected to
  863. # be changed for another function in PyDevdAPI.set_dont_trace_start_end_patterns.
  864. return False
  865. def get_file_type(self, frame, abs_real_path_and_basename=None, _cache_file_type=_CACHE_FILE_TYPE):
  866. """
  867. :param abs_real_path_and_basename:
  868. The result from get_abs_path_real_path_and_base_from_file or
  869. get_abs_path_real_path_and_base_from_frame.
  870. :return
  871. _pydevd_bundle.pydevd_dont_trace_files.PYDEV_FILE:
  872. If it's a file internal to the debugger which shouldn't be
  873. traced nor shown to the user.
  874. _pydevd_bundle.pydevd_dont_trace_files.LIB_FILE:
  875. If it's a file in a library which shouldn't be traced.
  876. None:
  877. If it's a regular user file which should be traced.
  878. """
  879. if abs_real_path_and_basename is None:
  880. try:
  881. # Make fast path faster!
  882. abs_real_path_and_basename = NORM_PATHS_AND_BASE_CONTAINER[frame.f_code.co_filename]
  883. except:
  884. abs_real_path_and_basename = get_abs_path_real_path_and_base_from_frame(frame)
  885. # Note 1: we have to take into account that we may have files as '<string>', and that in
  886. # this case the cache key can't rely only on the filename. With the current cache, there's
  887. # still a potential miss if 2 functions which have exactly the same content are compiled
  888. # with '<string>', but in practice as we only separate the one from python -c from the rest
  889. # this shouldn't be a problem in practice.
  890. # Note 2: firstlineno added to make misses faster in the first comparison.
  891. # Note 3: this cache key is repeated in pydevd_frame_evaluator.pyx:get_func_code_info (for
  892. # speedups).
  893. cache_key = (frame.f_code.co_firstlineno, abs_real_path_and_basename[0], frame.f_code)
  894. try:
  895. return _cache_file_type[cache_key]
  896. except:
  897. if abs_real_path_and_basename[0] == "<string>":
  898. f = frame.f_back
  899. while f is not None:
  900. if self.get_file_type(f) != self.PYDEV_FILE and pydevd_file_utils.basename(f.f_code.co_filename) not in (
  901. "runpy.py",
  902. "<string>",
  903. ):
  904. # We found some back frame that's not internal, which means we must consider
  905. # this a library file.
  906. # This is done because we only want to trace files as <string> if they don't
  907. # have any back frame (which is the case for python -c ...), for all other
  908. # cases we don't want to trace them because we can't show the source to the
  909. # user (at least for now...).
  910. # Note that we return as a LIB_FILE and not PYDEV_FILE because we still want
  911. # to show it in the stack.
  912. _cache_file_type[cache_key] = LIB_FILE
  913. return LIB_FILE
  914. f = f.f_back
  915. else:
  916. # This is a top-level file (used in python -c), so, trace it as usual... we
  917. # still won't be able to show the sources, but some tests require this to work.
  918. _cache_file_type[cache_key] = None
  919. return None
  920. file_type = self._internal_get_file_type(abs_real_path_and_basename)
  921. if file_type is None:
  922. if self.dont_trace_external_files(abs_real_path_and_basename[0]):
  923. file_type = PYDEV_FILE
  924. _cache_file_type[cache_key] = file_type
  925. return file_type
  926. def is_cache_file_type_empty(self):
  927. return not _CACHE_FILE_TYPE
  928. def get_cache_file_type(self, _cache=_CACHE_FILE_TYPE): # i.e.: Make it local.
  929. return _cache
  930. def get_thread_local_trace_func(self):
  931. try:
  932. thread_trace_func = self._local_thread_trace_func.thread_trace_func
  933. except AttributeError:
  934. thread_trace_func = self.trace_dispatch
  935. return thread_trace_func
  936. def enable_tracing(self, thread_trace_func=None, apply_to_all_threads=False):
  937. """
  938. Enables tracing.
  939. If in regular mode (tracing), will set the tracing function to the tracing
  940. function for this thread -- by default it's `PyDB.trace_dispatch`, but after
  941. `PyDB.enable_tracing` is called with a `thread_trace_func`, the given function will
  942. be the default for the given thread.
  943. :param bool apply_to_all_threads:
  944. If True we'll set the tracing function in all threads, not only in the current thread.
  945. If False only the tracing for the current function should be changed.
  946. In general apply_to_all_threads should only be true if this is the first time
  947. this function is called on a multi-threaded program (either programmatically or attach
  948. to pid).
  949. """
  950. if PYDEVD_USE_SYS_MONITORING:
  951. pydevd_sys_monitoring.start_monitoring(all_threads=apply_to_all_threads)
  952. return
  953. if pydevd_gevent_integration is not None:
  954. pydevd_gevent_integration.enable_gevent_integration()
  955. if self.frame_eval_func is not None:
  956. self.frame_eval_func()
  957. pydevd_tracing.SetTrace(self.dummy_trace_dispatch)
  958. if IS_CPYTHON and apply_to_all_threads:
  959. pydevd_tracing.set_trace_to_threads(self.dummy_trace_dispatch)
  960. return
  961. if apply_to_all_threads:
  962. # If applying to all threads, don't use the local thread trace function.
  963. assert thread_trace_func is not None
  964. else:
  965. if thread_trace_func is None:
  966. thread_trace_func = self.get_thread_local_trace_func()
  967. else:
  968. self._local_thread_trace_func.thread_trace_func = thread_trace_func
  969. pydevd_tracing.SetTrace(thread_trace_func)
  970. if IS_CPYTHON and apply_to_all_threads:
  971. pydevd_tracing.set_trace_to_threads(thread_trace_func)
  972. def disable_tracing(self):
  973. if PYDEVD_USE_SYS_MONITORING:
  974. pydevd_sys_monitoring.stop_monitoring(all_threads=False)
  975. else:
  976. pydevd_tracing.SetTrace(None)
  977. def on_breakpoints_changed(self, removed=False):
  978. """
  979. When breakpoints change, we have to re-evaluate all the assumptions we've made so far.
  980. """
  981. if not self.ready_to_run:
  982. # No need to do anything if we're still not running.
  983. return
  984. self.mtime += 1
  985. if not removed:
  986. # When removing breakpoints we can leave tracing as was, but if a breakpoint was added
  987. # we have to reset the tracing for the existing functions to be re-evaluated.
  988. # The caches also need to be cleared because of django breakpoints use case,
  989. # where adding a file needs to start tracking a context which was previously
  990. # untracked.
  991. self._clear_caches()
  992. self.set_tracing_for_untraced_contexts(breakpoints_changed=True)
  993. def set_tracing_for_untraced_contexts(self, breakpoints_changed=False):
  994. # Enable the tracing for existing threads (because there may be frames being executed that
  995. # are currently untraced).
  996. if PYDEVD_USE_SYS_MONITORING and breakpoints_changed:
  997. pydevd_sys_monitoring.update_monitor_events()
  998. if IS_CPYTHON:
  999. # Note: use sys._current_frames instead of threading.enumerate() because this way
  1000. # we also see C/C++ threads, not only the ones visible to the threading module.
  1001. tid_to_frame = sys._current_frames()
  1002. ignore_thread_ids = set(
  1003. t.ident
  1004. for t in threadingEnumerate()
  1005. if getattr(t, "is_pydev_daemon_thread", False) or getattr(t, "pydev_do_not_trace", False)
  1006. )
  1007. for thread_ident, frame in tid_to_frame.items():
  1008. if thread_ident not in ignore_thread_ids:
  1009. self.set_trace_for_frame_and_parents(thread_ident, frame)
  1010. else:
  1011. try:
  1012. threads = threadingEnumerate()
  1013. for t in threads:
  1014. if getattr(t, "is_pydev_daemon_thread", False) or getattr(t, "pydev_do_not_trace", False):
  1015. continue
  1016. additional_info = set_additional_thread_info(t)
  1017. frame = additional_info.get_topmost_frame(t)
  1018. try:
  1019. if frame is not None:
  1020. self.set_trace_for_frame_and_parents(t.ident, frame)
  1021. finally:
  1022. frame = None
  1023. finally:
  1024. frame = None
  1025. t = None
  1026. threads = None
  1027. additional_info = None
  1028. if PYDEVD_USE_SYS_MONITORING:
  1029. pydevd_sys_monitoring.restart_events()
  1030. @property
  1031. def multi_threads_single_notification(self):
  1032. return self._threads_suspended_single_notification.multi_threads_single_notification
  1033. @multi_threads_single_notification.setter
  1034. def multi_threads_single_notification(self, notify):
  1035. self._threads_suspended_single_notification.multi_threads_single_notification = notify
  1036. @property
  1037. def threads_suspended_single_notification(self):
  1038. return self._threads_suspended_single_notification
  1039. def get_plugin_lazy_init(self):
  1040. if self.plugin is None:
  1041. self.plugin = PluginManager(self)
  1042. return self.plugin
  1043. def in_project_scope(self, frame, absolute_filename=None):
  1044. """
  1045. Note: in general this method should not be used (apply_files_filter should be used
  1046. in most cases as it also handles the project scope check).
  1047. :param frame:
  1048. The frame we want to check.
  1049. :param absolute_filename:
  1050. Must be the result from get_abs_path_real_path_and_base_from_frame(frame)[0] (can
  1051. be used to speed this function a bit if it's already available to the caller, but
  1052. in general it's not needed).
  1053. """
  1054. try:
  1055. if absolute_filename is None:
  1056. try:
  1057. # Make fast path faster!
  1058. abs_real_path_and_basename = NORM_PATHS_AND_BASE_CONTAINER[frame.f_code.co_filename]
  1059. except:
  1060. abs_real_path_and_basename = get_abs_path_real_path_and_base_from_frame(frame)
  1061. absolute_filename = abs_real_path_and_basename[0]
  1062. cache_key = (frame.f_code.co_firstlineno, absolute_filename, frame.f_code)
  1063. return self._in_project_scope_cache[cache_key]
  1064. except KeyError:
  1065. cache = self._in_project_scope_cache
  1066. try:
  1067. abs_real_path_and_basename # If we've gotten it previously, use it again.
  1068. except NameError:
  1069. abs_real_path_and_basename = get_abs_path_real_path_and_base_from_frame(frame)
  1070. # pydevd files are never considered to be in the project scope.
  1071. file_type = self.get_file_type(frame, abs_real_path_and_basename)
  1072. if file_type == self.PYDEV_FILE:
  1073. cache[cache_key] = False
  1074. elif IS_PY314_OR_GREATER and frame.f_code.co_name == "__annotate__":
  1075. # Special handling for __annotate__ functions (PEP 649 in Python 3.14+).
  1076. # These are compiler-generated functions that can raise NotImplementedError
  1077. # when called with unsupported format arguments by inspect.call_annotate_function.
  1078. # They should be treated as library code to avoid false positives in exception handling.
  1079. # Note: PEP 649 reserves the __annotate__ name for compiler-generated functions,
  1080. # so user-defined functions with this name are discouraged and will also be treated
  1081. # as library code to maintain consistency with the language design.
  1082. cache[cache_key] = False
  1083. elif absolute_filename == "<string>":
  1084. # Special handling for '<string>'
  1085. if file_type == self.LIB_FILE:
  1086. cache[cache_key] = False
  1087. else:
  1088. cache[cache_key] = True
  1089. elif self.source_mapping.has_mapping_entry(absolute_filename):
  1090. cache[cache_key] = True
  1091. else:
  1092. cache[cache_key] = self._files_filtering.in_project_roots(absolute_filename)
  1093. return cache[cache_key]
  1094. def in_project_roots_filename_uncached(self, absolute_filename):
  1095. return self._files_filtering.in_project_roots(absolute_filename)
  1096. def _clear_caches(self):
  1097. # Skip caches
  1098. global_cache_skips.clear()
  1099. global_cache_frame_skips.clear()
  1100. # Filter caches
  1101. self._in_project_scope_cache.clear()
  1102. self._exclude_by_filter_cache.clear()
  1103. self._apply_filter_cache.clear()
  1104. self._exclude_filters_enabled = self._files_filtering.use_exclude_filters()
  1105. self._is_libraries_filter_enabled = self._files_filtering.use_libraries_filter()
  1106. self.is_files_filter_enabled = self._exclude_filters_enabled or self._is_libraries_filter_enabled
  1107. self.mtime += 1
  1108. if PYDEVD_USE_SYS_MONITORING:
  1109. pydevd_sys_monitoring.update_monitor_events()
  1110. pydevd_sys_monitoring.restart_events()
  1111. def clear_dont_trace_start_end_patterns_caches(self):
  1112. # When start/end patterns are changed we must clear all caches which would be
  1113. # affected by a change in get_file_type() and reset the tracing function
  1114. # as places which were traced may no longer need to be traced and vice-versa.
  1115. self.on_breakpoints_changed()
  1116. _CACHE_FILE_TYPE.clear()
  1117. self._clear_caches()
  1118. def _exclude_by_filter(self, frame, absolute_filename):
  1119. """
  1120. :return: True if it should be excluded, False if it should be included and None
  1121. if no rule matched the given file.
  1122. :note: it'll be normalized as needed inside of this method.
  1123. """
  1124. cache_key = (absolute_filename, frame.f_code.co_name, frame.f_code.co_firstlineno)
  1125. try:
  1126. return self._exclude_by_filter_cache[cache_key]
  1127. except KeyError:
  1128. cache = self._exclude_by_filter_cache
  1129. # pydevd files are always filtered out
  1130. if self.get_file_type(frame) == self.PYDEV_FILE:
  1131. cache[cache_key] = True
  1132. else:
  1133. module_name = None
  1134. if self._files_filtering.require_module:
  1135. module_name = frame.f_globals.get("__name__", "")
  1136. cache[cache_key] = self._files_filtering.exclude_by_filter(absolute_filename, module_name)
  1137. return cache[cache_key]
  1138. def apply_files_filter(self, frame, original_filename, force_check_project_scope):
  1139. """
  1140. Should only be called if `self.is_files_filter_enabled == True` or `force_check_project_scope == True`.
  1141. Note that it covers both the filter by specific paths includes/excludes as well
  1142. as the check which filters out libraries if not in the project scope.
  1143. :param original_filename:
  1144. Note can either be the original filename or the absolute version of that filename.
  1145. :param force_check_project_scope:
  1146. Check that the file is in the project scope even if the global setting
  1147. is off.
  1148. :return bool:
  1149. True if it should be excluded when stepping and False if it should be
  1150. included.
  1151. """
  1152. cache_key = (frame.f_code.co_firstlineno, original_filename, force_check_project_scope, frame.f_code)
  1153. try:
  1154. return self._apply_filter_cache[cache_key]
  1155. except KeyError:
  1156. DEBUG = True # 'defaulttags' in original_filename
  1157. if self.plugin is not None and (self.has_plugin_line_breaks or self.has_plugin_exception_breaks):
  1158. # If it's explicitly needed by some plugin, we can't skip it.
  1159. if not self.plugin.can_skip(self, frame):
  1160. if DEBUG:
  1161. pydev_log.debug_once("File traced (included by plugins): %s", original_filename)
  1162. self._apply_filter_cache[cache_key] = False
  1163. return False
  1164. if self._exclude_filters_enabled:
  1165. absolute_filename = pydevd_file_utils.absolute_path(original_filename)
  1166. exclude_by_filter = self._exclude_by_filter(frame, absolute_filename)
  1167. if exclude_by_filter is not None:
  1168. if exclude_by_filter:
  1169. # ignore files matching stepping filters
  1170. if DEBUG:
  1171. pydev_log.debug_once("File not traced (excluded by filters): %s", original_filename)
  1172. self._apply_filter_cache[cache_key] = True
  1173. return True
  1174. else:
  1175. if DEBUG:
  1176. pydev_log.debug_once("File traced (explicitly included by filters): %s", original_filename)
  1177. self._apply_filter_cache[cache_key] = False
  1178. return False
  1179. if (self._is_libraries_filter_enabled or force_check_project_scope) and not self.in_project_scope(frame):
  1180. # ignore library files while stepping
  1181. self._apply_filter_cache[cache_key] = True
  1182. if force_check_project_scope:
  1183. if DEBUG:
  1184. pydev_log.debug_once("File not traced (not in project): %s", original_filename)
  1185. else:
  1186. if DEBUG:
  1187. pydev_log.debug_once("File not traced (not in project - force_check_project_scope): %s", original_filename)
  1188. return True
  1189. if force_check_project_scope:
  1190. if DEBUG:
  1191. pydev_log.debug_once("File traced: %s (force_check_project_scope)", original_filename)
  1192. else:
  1193. if DEBUG:
  1194. pydev_log.debug_once("File traced: %s", original_filename)
  1195. self._apply_filter_cache[cache_key] = False
  1196. return False
  1197. def exclude_exception_by_filter(self, exception_breakpoint, trace):
  1198. if not exception_breakpoint.ignore_libraries and not self._exclude_filters_enabled:
  1199. return False
  1200. if trace is None:
  1201. return True
  1202. ignore_libraries = exception_breakpoint.ignore_libraries
  1203. exclude_filters_enabled = self._exclude_filters_enabled
  1204. if (ignore_libraries and not self.in_project_scope(trace.tb_frame)) or (
  1205. exclude_filters_enabled
  1206. and self._exclude_by_filter(trace.tb_frame, pydevd_file_utils.absolute_path(trace.tb_frame.f_code.co_filename))
  1207. ):
  1208. return True
  1209. return False
  1210. def set_project_roots(self, project_roots):
  1211. self._files_filtering.set_project_roots(project_roots)
  1212. self._clear_caches()
  1213. def set_exclude_filters(self, exclude_filters):
  1214. self._files_filtering.set_exclude_filters(exclude_filters)
  1215. self._clear_caches()
  1216. def set_use_libraries_filter(self, use_libraries_filter):
  1217. self._files_filtering.set_use_libraries_filter(use_libraries_filter)
  1218. self._clear_caches()
  1219. def get_use_libraries_filter(self):
  1220. return self._files_filtering.use_libraries_filter()
  1221. def get_require_module_for_filters(self):
  1222. return self._files_filtering.require_module
  1223. def has_user_threads_alive(self):
  1224. for t in pydevd_utils.get_non_pydevd_threads():
  1225. if isinstance(t, PyDBDaemonThread):
  1226. pydev_log.error_once("Error in debugger: Found PyDBDaemonThread not marked with is_pydev_daemon_thread=True.\n")
  1227. if is_thread_alive(t):
  1228. if not t.daemon or hasattr(t, "__pydevd_main_thread"):
  1229. return True
  1230. return False
  1231. def initialize_network(self, sock, terminate_on_socket_close=True):
  1232. assert sock is not None
  1233. try:
  1234. sock.settimeout(None) # infinite, no timeouts from now on - jython does not have it
  1235. except:
  1236. pass
  1237. curr_reader = getattr(self, "reader", None)
  1238. curr_writer = getattr(self, "writer", None)
  1239. if curr_reader:
  1240. curr_reader.do_kill_pydev_thread()
  1241. if curr_writer:
  1242. curr_writer.do_kill_pydev_thread()
  1243. self.writer = WriterThread(sock, self, terminate_on_socket_close=terminate_on_socket_close)
  1244. self.reader = ReaderThread(
  1245. sock,
  1246. self,
  1247. PyDevJsonCommandProcessor=PyDevJsonCommandProcessor,
  1248. process_net_command=process_net_command,
  1249. terminate_on_socket_close=terminate_on_socket_close,
  1250. )
  1251. self.writer.start()
  1252. self.reader.start()
  1253. time.sleep(0.1) # give threads time to start
  1254. def connect(self, host, port):
  1255. if host:
  1256. s = start_client(host, port)
  1257. self._client_socket = s
  1258. else:
  1259. s = start_server(port)
  1260. self.initialize_network(s)
  1261. def create_wait_for_connection_thread(self):
  1262. if self._waiting_for_connection_thread is not None:
  1263. raise AssertionError("There is already another thread waiting for a connection.")
  1264. self._server_socket_ready_event.clear()
  1265. self._waiting_for_connection_thread = self._WaitForConnectionThread(self)
  1266. self._waiting_for_connection_thread.start()
  1267. def set_server_socket_ready(self):
  1268. self._server_socket_ready_event.set()
  1269. def wait_for_server_socket_ready(self):
  1270. self._server_socket_ready_event.wait()
  1271. @property
  1272. def dap_messages_listeners(self):
  1273. return self._dap_messages_listeners
  1274. def add_dap_messages_listener(self, listener):
  1275. self._dap_messages_listeners.append(listener)
  1276. class _WaitForConnectionThread(PyDBDaemonThread):
  1277. def __init__(self, py_db):
  1278. PyDBDaemonThread.__init__(self, py_db)
  1279. self._server_socket = None
  1280. def run(self):
  1281. host = SetupHolder.setup["client"]
  1282. port = SetupHolder.setup["port"]
  1283. self._server_socket = create_server_socket(host=host, port=port)
  1284. self.py_db._server_socket_name = self._server_socket.getsockname()
  1285. self.py_db.set_server_socket_ready()
  1286. while not self._kill_received:
  1287. try:
  1288. s = self._server_socket
  1289. if s is None:
  1290. return
  1291. s.listen(1)
  1292. new_socket, _addr = s.accept()
  1293. if self._kill_received:
  1294. pydev_log.info("Connection (from wait_for_attach) accepted but ignored as kill was already received.")
  1295. return
  1296. pydev_log.info("Connection (from wait_for_attach) accepted.")
  1297. reader = getattr(self.py_db, "reader", None)
  1298. if reader is not None:
  1299. # This is needed if a new connection is done without the client properly
  1300. # sending a disconnect for the previous connection.
  1301. api = PyDevdAPI()
  1302. api.request_disconnect(self.py_db, resume_threads=False)
  1303. self.py_db.initialize_network(new_socket, terminate_on_socket_close=False)
  1304. except:
  1305. if DebugInfoHolder.DEBUG_TRACE_LEVEL > 0:
  1306. pydev_log.exception()
  1307. pydev_log.debug("Exiting _WaitForConnectionThread: %s\n", port)
  1308. def do_kill_pydev_thread(self):
  1309. PyDBDaemonThread.do_kill_pydev_thread(self)
  1310. s = self._server_socket
  1311. if s is not None:
  1312. try:
  1313. s.close()
  1314. except:
  1315. pass
  1316. self._server_socket = None
  1317. def get_internal_queue_and_event(self, thread_id) -> Tuple[_queue.Queue, ThreadingEvent]:
  1318. """returns internal command queue for a given thread.
  1319. if new queue is created, notify the RDB about it"""
  1320. if thread_id.startswith("__frame__"):
  1321. thread_id = thread_id[thread_id.rfind("|") + 1:]
  1322. return self._cmd_queue[thread_id], self._thread_events[thread_id]
  1323. def post_method_as_internal_command(self, thread_id, method, *args, **kwargs):
  1324. if thread_id == "*":
  1325. internal_cmd = InternalThreadCommandForAnyThread(thread_id, method, *args, **kwargs)
  1326. else:
  1327. internal_cmd = InternalThreadCommand(thread_id, method, *args, **kwargs)
  1328. self.post_internal_command(internal_cmd, thread_id)
  1329. def post_internal_command(self, int_cmd, thread_id):
  1330. """if thread_id is *, post to the '*' queue"""
  1331. queue, event = self.get_internal_queue_and_event(thread_id)
  1332. queue.put(int_cmd)
  1333. if thread_id == "*":
  1334. self._py_db_command_thread_event.set()
  1335. else:
  1336. event.set()
  1337. def enable_output_redirection(self, redirect_stdout, redirect_stderr):
  1338. global _global_redirect_stdout_to_server
  1339. global _global_redirect_stderr_to_server
  1340. _global_redirect_stdout_to_server = redirect_stdout
  1341. _global_redirect_stderr_to_server = redirect_stderr
  1342. self.redirect_output = redirect_stdout or redirect_stderr
  1343. if _global_redirect_stdout_to_server:
  1344. _init_stdout_redirect()
  1345. if _global_redirect_stderr_to_server:
  1346. _init_stderr_redirect()
  1347. def check_output_redirect(self):
  1348. global _global_redirect_stdout_to_server
  1349. global _global_redirect_stderr_to_server
  1350. if _global_redirect_stdout_to_server:
  1351. _init_stdout_redirect()
  1352. if _global_redirect_stderr_to_server:
  1353. _init_stderr_redirect()
  1354. def init_gui_support(self):
  1355. if self._installed_gui_support:
  1356. return
  1357. self._installed_gui_support = True
  1358. # enable_gui and enable_gui_function in activate_matplotlib should be called in main thread. Unlike integrated console,
  1359. # in the debug console we have no interpreter instance with exec_queue, but we run this code in the main
  1360. # thread and can call it directly.
  1361. class _ReturnGuiLoopControlHelper:
  1362. _return_control_osc = False
  1363. def return_control():
  1364. # Some of the input hooks (e.g. Qt4Agg) check return control without doing
  1365. # a single operation, so we don't return True on every
  1366. # call when the debug hook is in place to allow the GUI to run
  1367. _ReturnGuiLoopControlHelper._return_control_osc = not _ReturnGuiLoopControlHelper._return_control_osc
  1368. return _ReturnGuiLoopControlHelper._return_control_osc
  1369. from pydev_ipython.inputhook import set_return_control_callback, enable_gui
  1370. set_return_control_callback(return_control)
  1371. if self._gui_event_loop == "matplotlib":
  1372. # prepare debugger for matplotlib integration with GUI event loop
  1373. from pydev_ipython.matplotlibtools import activate_matplotlib, activate_pylab, activate_pyplot, do_enable_gui
  1374. self.mpl_modules_for_patching = {
  1375. "matplotlib": lambda: activate_matplotlib(do_enable_gui),
  1376. "matplotlib.pyplot": activate_pyplot,
  1377. "pylab": activate_pylab,
  1378. }
  1379. else:
  1380. self.activate_gui_function = enable_gui
  1381. def _activate_gui_if_needed(self):
  1382. if self.gui_in_use:
  1383. return
  1384. if len(self.mpl_modules_for_patching) > 0:
  1385. if is_current_thread_main_thread(): # Note that we call only in the main thread.
  1386. for module in list(self.mpl_modules_for_patching):
  1387. if module in sys.modules:
  1388. activate_function = self.mpl_modules_for_patching.pop(module, None)
  1389. if activate_function is not None:
  1390. activate_function()
  1391. self.gui_in_use = True
  1392. if self.activate_gui_function:
  1393. if is_current_thread_main_thread(): # Only call enable_gui in the main thread.
  1394. try:
  1395. # First try to activate builtin GUI event loops.
  1396. self.activate_gui_function(self._gui_event_loop)
  1397. self.activate_gui_function = None
  1398. self.gui_in_use = True
  1399. except ValueError:
  1400. # The user requested a custom GUI event loop, try to import it.
  1401. from pydev_ipython.inputhook import set_inputhook
  1402. try:
  1403. inputhook_function = import_attr_from_module(self._gui_event_loop)
  1404. set_inputhook(inputhook_function)
  1405. self.gui_in_use = True
  1406. except Exception as e:
  1407. pydev_log.debug("Cannot activate custom GUI event loop {}: {}".format(self._gui_event_loop, e))
  1408. finally:
  1409. self.activate_gui_function = None
  1410. def _call_input_hook(self):
  1411. try:
  1412. from pydev_ipython.inputhook import get_inputhook
  1413. inputhook = get_inputhook()
  1414. if inputhook:
  1415. inputhook()
  1416. except:
  1417. pass
  1418. def notify_skipped_step_in_because_of_filters(self, frame):
  1419. self.writer.add_command(self.cmd_factory.make_skipped_step_in_because_of_filters(self, frame))
  1420. def notify_thread_created(self, thread_id, thread, use_lock=True):
  1421. if self.writer is None:
  1422. # Protect about threads being created before the communication structure is in place
  1423. # (note that they will appear later on anyways as pydevd does reconcile live/dead threads
  1424. # when processing internal commands, albeit it may take longer and in general this should
  1425. # not be usual as it's expected that the debugger is live before other threads are created).
  1426. return
  1427. with self._lock_running_thread_ids if use_lock else NULL:
  1428. if not self._enable_thread_notifications:
  1429. return
  1430. if thread_id in self._running_thread_ids:
  1431. return
  1432. additional_info = set_additional_thread_info(thread)
  1433. if additional_info.pydev_notify_kill:
  1434. # After we notify it should be killed, make sure we don't notify it's alive (on a racing condition
  1435. # this could happen as we may notify before the thread is stopped internally).
  1436. return
  1437. self._running_thread_ids[thread_id] = thread
  1438. self.writer.add_command(self.cmd_factory.make_thread_created_message(thread))
  1439. def notify_thread_not_alive(self, thread_id, use_lock=True):
  1440. """if thread is not alive, cancel trace_dispatch processing"""
  1441. if self.writer is None:
  1442. return
  1443. with self._lock_running_thread_ids if use_lock else NULL:
  1444. if not self._enable_thread_notifications:
  1445. return
  1446. thread = self._running_thread_ids.pop(thread_id, None)
  1447. if thread is None:
  1448. return
  1449. additional_info = set_additional_thread_info(thread)
  1450. was_notified = additional_info.pydev_notify_kill
  1451. if not was_notified:
  1452. additional_info.pydev_notify_kill = True
  1453. remove_additional_info(additional_info)
  1454. self.writer.add_command(self.cmd_factory.make_thread_killed_message(thread_id))
  1455. def set_enable_thread_notifications(self, enable):
  1456. with self._lock_running_thread_ids:
  1457. if self._enable_thread_notifications != enable:
  1458. self._enable_thread_notifications = enable
  1459. if enable:
  1460. # As it was previously disabled, we have to notify about existing threads again
  1461. # (so, clear the cache related to that).
  1462. self._running_thread_ids = {}
  1463. def process_internal_commands(self, process_thread_ids: Optional[tuple]=None):
  1464. """
  1465. This function processes internal commands.
  1466. """
  1467. # If this method is being called before the debugger is ready to run we should not notify
  1468. # about threads and should only process commands sent to all threads.
  1469. ready_to_run = self.ready_to_run
  1470. dispose = False
  1471. with self._main_lock:
  1472. program_threads_alive = {}
  1473. if ready_to_run:
  1474. self.check_output_redirect()
  1475. all_threads = threadingEnumerate()
  1476. program_threads_dead = []
  1477. with self._lock_running_thread_ids:
  1478. reset_cache = not self._running_thread_ids
  1479. for t in all_threads:
  1480. if getattr(t, "is_pydev_daemon_thread", False):
  1481. pass # I.e.: skip the DummyThreads created from pydev daemon threads
  1482. elif isinstance(t, PyDBDaemonThread):
  1483. pydev_log.error_once("Error in debugger: Found PyDBDaemonThread not marked with is_pydev_daemon_thread=True.")
  1484. elif is_thread_alive(t):
  1485. if reset_cache:
  1486. # Fix multiprocessing debug with breakpoints in both main and child processes
  1487. # (https://youtrack.jetbrains.com/issue/PY-17092) When the new process is created, the main
  1488. # thread in the new process already has the attribute 'pydevd_id', so the new thread doesn't
  1489. # get new id with its process number and the debugger loses access to both threads.
  1490. # Therefore we should update thread_id for every main thread in the new process.
  1491. clear_cached_thread_id(t)
  1492. thread_id = get_thread_id(t)
  1493. program_threads_alive[thread_id] = t
  1494. self.notify_thread_created(thread_id, t, use_lock=False)
  1495. # Compute and notify about threads which are no longer alive.
  1496. thread_ids = list(self._running_thread_ids.keys())
  1497. for thread_id in thread_ids:
  1498. if thread_id not in program_threads_alive:
  1499. program_threads_dead.append(thread_id)
  1500. for thread_id in program_threads_dead:
  1501. self.notify_thread_not_alive(thread_id, use_lock=False)
  1502. cmds_to_execute = []
  1503. # Without self._lock_running_thread_ids
  1504. if len(program_threads_alive) == 0 and ready_to_run:
  1505. dispose = True
  1506. else:
  1507. curr_thread_id = get_current_thread_id(threadingCurrentThread())
  1508. if process_thread_ids is None:
  1509. # Actually process the commands now (make sure we don't have a lock for _lock_running_thread_ids
  1510. # acquired at this point as it could lead to a deadlock if some command evaluated tried to
  1511. # create a thread and wait for it -- which would try to notify about it getting that lock).
  1512. if ready_to_run:
  1513. process_thread_ids = (curr_thread_id, "*")
  1514. else:
  1515. process_thread_ids = ("*",)
  1516. for thread_id in process_thread_ids:
  1517. queue, _event = self.get_internal_queue_and_event(thread_id)
  1518. # some commands must be processed by the thread itself... if that's the case,
  1519. # we will re-add the commands to the queue after executing.
  1520. cmds_to_add_back = []
  1521. try:
  1522. while True:
  1523. internal_cmd = queue.get(False)
  1524. try:
  1525. if internal_cmd.can_be_executed_by(curr_thread_id):
  1526. cmds_to_execute.append(internal_cmd)
  1527. else:
  1528. pydev_log.verbose("NOT processing internal command: %s ", internal_cmd)
  1529. cmds_to_add_back.append(internal_cmd)
  1530. except:
  1531. pydev_log.exception()
  1532. raise
  1533. except _queue.Empty: # @UndefinedVariable
  1534. # this is how we exit
  1535. for internal_cmd in cmds_to_add_back:
  1536. queue.put(internal_cmd)
  1537. if dispose:
  1538. # Note: must be called without the main lock to avoid deadlocks.
  1539. self.dispose_and_kill_all_pydevd_threads()
  1540. else:
  1541. # Actually execute the commands without the main lock!
  1542. for internal_cmd in cmds_to_execute:
  1543. pydev_log.verbose("processing internal command: %s", internal_cmd)
  1544. try:
  1545. internal_cmd.do_it(self)
  1546. except:
  1547. pydev_log.exception("Error processing internal command.")
  1548. def consolidate_breakpoints(self, canonical_normalized_filename, id_to_breakpoint, file_to_line_to_breakpoints):
  1549. break_dict = {}
  1550. for _breakpoint_id, pybreakpoint in id_to_breakpoint.items():
  1551. break_dict[pybreakpoint.line] = pybreakpoint
  1552. file_to_line_to_breakpoints[canonical_normalized_filename] = break_dict
  1553. self._clear_caches()
  1554. def add_break_on_exception(
  1555. self,
  1556. exception,
  1557. condition,
  1558. expression,
  1559. notify_on_handled_exceptions,
  1560. notify_on_unhandled_exceptions,
  1561. notify_on_user_unhandled_exceptions,
  1562. notify_on_first_raise_only,
  1563. ignore_libraries=False,
  1564. ):
  1565. try:
  1566. eb = ExceptionBreakpoint(
  1567. exception,
  1568. condition,
  1569. expression,
  1570. notify_on_handled_exceptions,
  1571. notify_on_unhandled_exceptions,
  1572. notify_on_user_unhandled_exceptions,
  1573. notify_on_first_raise_only,
  1574. ignore_libraries,
  1575. )
  1576. except ImportError:
  1577. pydev_log.critical("Error unable to add break on exception for: %s (exception could not be imported).", exception)
  1578. return None
  1579. if eb.notify_on_unhandled_exceptions:
  1580. cp = self.break_on_uncaught_exceptions.copy()
  1581. cp[exception] = eb
  1582. pydev_log.info("Exceptions to hook on terminate: %s.", cp)
  1583. self.break_on_uncaught_exceptions = cp
  1584. if eb.notify_on_handled_exceptions:
  1585. cp = self.break_on_caught_exceptions.copy()
  1586. cp[exception] = eb
  1587. pydev_log.info("Exceptions to hook always: %s.", cp)
  1588. self.break_on_caught_exceptions = cp
  1589. if eb.notify_on_user_unhandled_exceptions:
  1590. cp = self.break_on_user_uncaught_exceptions.copy()
  1591. cp[exception] = eb
  1592. pydev_log.info("Exceptions to hook on user uncaught code: %s.", cp)
  1593. self.break_on_user_uncaught_exceptions = cp
  1594. return eb
  1595. def set_suspend(
  1596. self,
  1597. thread,
  1598. stop_reason: int,
  1599. suspend_other_threads: bool=False,
  1600. is_pause=False,
  1601. original_step_cmd: int=-1,
  1602. suspend_requested: bool=False,
  1603. ):
  1604. """
  1605. :param thread:
  1606. The thread which should be suspended.
  1607. :param stop_reason:
  1608. Reason why the thread was suspended.
  1609. :param suspend_other_threads:
  1610. Whether to force other threads to be suspended (i.e.: when hitting a breakpoint
  1611. with a suspend all threads policy).
  1612. :param is_pause:
  1613. If this is a pause to suspend all threads, any thread can be considered as the 'main'
  1614. thread paused.
  1615. :param original_step_cmd:
  1616. If given we may change the stop reason to this.
  1617. :param suspend_requested:
  1618. If the execution will be suspended right away then this may be false, otherwise,
  1619. if the thread should be stopped due to this suspend at a later time then it
  1620. should be true.
  1621. """
  1622. self._threads_suspended_single_notification.increment_suspend_time()
  1623. if is_pause:
  1624. self._threads_suspended_single_notification.on_pause()
  1625. info = mark_thread_suspended(thread, stop_reason, original_step_cmd=original_step_cmd)
  1626. if (suspend_requested or is_pause) and PYDEVD_USE_SYS_MONITORING:
  1627. pydevd_sys_monitoring.update_monitor_events(suspend_requested=True)
  1628. if is_pause:
  1629. # Must set tracing after setting the state to suspend.
  1630. frame = info.get_topmost_frame(thread)
  1631. if frame is not None:
  1632. # Where suspend was requested
  1633. # traceback.print_stack(frame)
  1634. try:
  1635. self.set_trace_for_frame_and_parents(thread.ident, frame)
  1636. finally:
  1637. frame = None
  1638. # If conditional breakpoint raises any exception during evaluation send the details to the client.
  1639. if stop_reason == CMD_SET_BREAK and info.conditional_breakpoint_exception is not None:
  1640. conditional_breakpoint_exception_tuple = info.conditional_breakpoint_exception
  1641. info.conditional_breakpoint_exception = None
  1642. self._send_breakpoint_condition_exception(thread, conditional_breakpoint_exception_tuple)
  1643. if not suspend_other_threads and self.multi_threads_single_notification:
  1644. # In the mode which gives a single notification when all threads are
  1645. # stopped, stop all threads whenever a set_suspend is issued.
  1646. suspend_other_threads = True
  1647. if suspend_other_threads:
  1648. # Suspend all except the current one (which we're currently suspending already).
  1649. suspend_all_threads(self, except_thread=thread)
  1650. if PYDEVD_USE_SYS_MONITORING:
  1651. pydevd_sys_monitoring.restart_events()
  1652. def _send_breakpoint_condition_exception(self, thread, conditional_breakpoint_exception_tuple):
  1653. """If conditional breakpoint raises an exception during evaluation
  1654. send exception details to java
  1655. """
  1656. thread_id = get_thread_id(thread)
  1657. # conditional_breakpoint_exception_tuple - should contain 2 values (exception_type, stacktrace)
  1658. if conditional_breakpoint_exception_tuple and len(conditional_breakpoint_exception_tuple) == 2:
  1659. exc_type, stacktrace = conditional_breakpoint_exception_tuple
  1660. int_cmd = InternalGetBreakpointException(thread_id, exc_type, stacktrace)
  1661. self.post_internal_command(int_cmd, thread_id)
  1662. def send_caught_exception_stack(self, thread, arg, curr_frame_id):
  1663. """Sends details on the exception which was caught (and where we stopped) to the java side.
  1664. arg is: exception type, description, traceback object
  1665. """
  1666. thread_id = get_thread_id(thread)
  1667. int_cmd = InternalSendCurrExceptionTrace(thread_id, arg, curr_frame_id)
  1668. self.post_internal_command(int_cmd, thread_id)
  1669. def send_caught_exception_stack_proceeded(self, thread):
  1670. """Sends that some thread was resumed and is no longer showing an exception trace."""
  1671. thread_id = get_thread_id(thread)
  1672. int_cmd = InternalSendCurrExceptionTraceProceeded(thread_id)
  1673. self.post_internal_command(int_cmd, thread_id)
  1674. self.process_internal_commands()
  1675. def send_process_created_message(self):
  1676. """Sends a message that a new process has been created."""
  1677. if self.writer is None or self.cmd_factory is None:
  1678. return
  1679. cmd = self.cmd_factory.make_process_created_message()
  1680. self.writer.add_command(cmd)
  1681. def send_process_about_to_be_replaced(self):
  1682. """Sends a message that a new process has been created."""
  1683. if self.writer is None or self.cmd_factory is None:
  1684. return
  1685. cmd = self.cmd_factory.make_process_about_to_be_replaced_message()
  1686. if cmd is NULL_NET_COMMAND:
  1687. return
  1688. sent = [False]
  1689. def after_sent(*args, **kwargs):
  1690. sent[0] = True
  1691. cmd.call_after_send(after_sent)
  1692. self.writer.add_command(cmd)
  1693. timeout = 5 # Wait up to 5 seconds
  1694. initial_time = time.time()
  1695. while not sent[0]:
  1696. time.sleep(0.05)
  1697. if (time.time() - initial_time) > timeout:
  1698. pydev_log.critical("pydevd: Sending message related to process being replaced timed-out after %s seconds", timeout)
  1699. break
  1700. def set_next_statement(self, frame, event, func_name, next_line):
  1701. stop = False
  1702. response_msg = ""
  1703. old_line = frame.f_lineno
  1704. if event == "line" or event == "exception":
  1705. # If we're already in the correct context, we have to stop it now, because we can act only on
  1706. # line events -- if a return was the next statement it wouldn't work (so, we have this code
  1707. # repeated at pydevd_frame).
  1708. curr_func_name = frame.f_code.co_name
  1709. # global context is set with an empty name
  1710. if curr_func_name in ("?", "<module>"):
  1711. curr_func_name = ""
  1712. if func_name == "*" or curr_func_name == func_name:
  1713. line = next_line
  1714. frame.f_trace = self.trace_dispatch
  1715. frame.f_lineno = line
  1716. stop = True
  1717. else:
  1718. response_msg = "jump is available only within the bottom frame"
  1719. return stop, old_line, response_msg
  1720. def cancel_async_evaluation(self, thread_id, frame_id):
  1721. with self._main_lock:
  1722. try:
  1723. all_threads = threadingEnumerate()
  1724. for t in all_threads:
  1725. if (
  1726. getattr(t, "is_pydev_daemon_thread", False)
  1727. and hasattr(t, "cancel_event")
  1728. and t.thread_id == thread_id
  1729. and t.frame_id == frame_id
  1730. ):
  1731. t.cancel_event.set()
  1732. except:
  1733. pydev_log.exception()
  1734. def find_frame(self, thread_id, frame_id):
  1735. """returns a frame on the thread that has a given frame_id"""
  1736. return self.suspended_frames_manager.find_frame(thread_id, frame_id)
  1737. def do_wait_suspend(self, thread, frame, event, arg, exception_type=None): # @UnusedVariable
  1738. """busy waits until the thread state changes to RUN
  1739. it expects thread's state as attributes of the thread.
  1740. Upon running, processes any outstanding Stepping commands.
  1741. :param exception_type:
  1742. If pausing due to an exception, its type.
  1743. """
  1744. if USE_CUSTOM_SYS_CURRENT_FRAMES_MAP:
  1745. constructed_tid_to_last_frame[thread.ident] = sys._getframe()
  1746. # Only process from all threads, not for current one (we'll do that later on in this method).
  1747. self.process_internal_commands(("*",))
  1748. thread_id = get_current_thread_id(thread)
  1749. # if DebugInfoHolder.DEBUG_TRACE_LEVEL >= 2:
  1750. # pydev_log.debug('do_wait_suspend %s %s %s %s %s %s (%s)' % (frame.f_lineno, frame.f_code.co_name, frame.f_code.co_filename, event, arg, constant_to_str(thread.additional_info.pydev_step_cmd), constant_to_str(thread.additional_info.pydev_original_step_cmd)))
  1751. # pydev_log.debug('--- internal stack ---')
  1752. # _f = sys._getframe()
  1753. # while _f is not None:
  1754. # pydev_log.debug(' -> %s' % (_f))
  1755. # _f = _f.f_back
  1756. # pydev_log.debug('--- end internal stack ---')
  1757. # Send the suspend message
  1758. message = thread.additional_info.pydev_message
  1759. trace_suspend_type = thread.additional_info.trace_suspend_type
  1760. thread.additional_info.trace_suspend_type = "trace" # Reset to trace mode for next call.
  1761. stop_reason = thread.stop_reason
  1762. frames_list = None
  1763. if arg is not None and event == "exception":
  1764. # arg must be the exception info (tuple(exc_type, exc, traceback))
  1765. exc_type, exc_desc, trace_obj = arg
  1766. if trace_obj is not None:
  1767. frames_list = pydevd_frame_utils.create_frames_list_from_traceback(
  1768. trace_obj, frame, exc_type, exc_desc, exception_type=exception_type
  1769. )
  1770. if frames_list is None:
  1771. frames_list = pydevd_frame_utils.create_frames_list_from_frame(frame)
  1772. if DebugInfoHolder.DEBUG_TRACE_LEVEL > 2:
  1773. pydev_log.debug(
  1774. "PyDB.do_wait_suspend\nname: %s (line: %s)\n file: %s\n event: %s\n arg: %s\n step: %s (original step: %s)\n thread: %s, thread id: %s, id(thread): %s",
  1775. frame.f_code.co_name,
  1776. frame.f_lineno,
  1777. frame.f_code.co_filename,
  1778. event,
  1779. arg,
  1780. constant_to_str(thread.additional_info.pydev_step_cmd),
  1781. constant_to_str(thread.additional_info.pydev_original_step_cmd),
  1782. thread,
  1783. thread_id,
  1784. id(thread),
  1785. )
  1786. for f in frames_list:
  1787. pydev_log.debug(" Stack: %s, %s, %s", f.f_code.co_filename, f.f_code.co_name, f.f_lineno)
  1788. with self.suspended_frames_manager.track_frames(self) as frames_tracker:
  1789. frames_tracker.track(thread_id, frames_list)
  1790. cmd = frames_tracker.create_thread_suspend_command(
  1791. thread_id, stop_reason, message, trace_suspend_type, thread, thread.additional_info
  1792. )
  1793. self.writer.add_command(cmd)
  1794. with CustomFramesContainer.custom_frames_lock: # @UndefinedVariable
  1795. from_this_thread = []
  1796. for frame_custom_thread_id, custom_frame in CustomFramesContainer.custom_frames.items():
  1797. if custom_frame.thread_id == thread.ident:
  1798. frames_tracker.track(
  1799. thread_id,
  1800. pydevd_frame_utils.create_frames_list_from_frame(custom_frame.frame),
  1801. frame_custom_thread_id=frame_custom_thread_id,
  1802. )
  1803. # print('Frame created as thread: %s' % (frame_custom_thread_id,))
  1804. self.writer.add_command(
  1805. self.cmd_factory.make_custom_frame_created_message(frame_custom_thread_id, custom_frame.name)
  1806. )
  1807. self.writer.add_command(
  1808. frames_tracker.create_thread_suspend_command(
  1809. frame_custom_thread_id, CMD_THREAD_SUSPEND, "", trace_suspend_type, thread, thread.additional_info
  1810. )
  1811. )
  1812. from_this_thread.append(frame_custom_thread_id)
  1813. with self._threads_suspended_single_notification.notify_thread_suspended(thread_id, thread, stop_reason):
  1814. keep_suspended = self._do_wait_suspend(thread, frame, event, arg, trace_suspend_type, from_this_thread, frames_tracker)
  1815. frames_list = None
  1816. if keep_suspended:
  1817. # This means that we should pause again after a set next statement.
  1818. self._threads_suspended_single_notification.increment_suspend_time()
  1819. self.do_wait_suspend(thread, frame, event, arg, exception_type)
  1820. if DebugInfoHolder.DEBUG_TRACE_LEVEL > 2:
  1821. pydev_log.debug("Leaving PyDB.do_wait_suspend: %s (%s) %s", thread, thread_id, id(thread))
  1822. def _do_wait_suspend(self, thread, frame, event, arg, trace_suspend_type, from_this_thread, frames_tracker):
  1823. info = thread.additional_info
  1824. try:
  1825. info.is_in_wait_loop = True
  1826. info.update_stepping_info()
  1827. info.step_in_initial_location = None
  1828. keep_suspended = False
  1829. with self._main_lock: # Use lock to check if suspended state changed
  1830. activate_gui = info.pydev_state == STATE_SUSPEND and not self.pydb_disposed
  1831. in_main_thread = is_current_thread_main_thread()
  1832. if activate_gui and in_main_thread:
  1833. # before every stop check if matplotlib modules were imported inside script code
  1834. # or some GUI event loop needs to be activated
  1835. self._activate_gui_if_needed()
  1836. # self.process_internal_commands(): processes for all the threads
  1837. # and updates running threads. This was called once in `do_wait_suspend`
  1838. # At this point it's just processing for this thread.
  1839. # Note that clients may not post an actual event (for instance, it
  1840. # could just set the internal state and signal the event instead
  1841. # of posting a command to the queue). In any case, if an item is
  1842. # put in the queue, the event must be set too.
  1843. curr_thread_id = get_current_thread_id(threadingCurrentThread())
  1844. queue, notify_event = self.get_internal_queue_and_event(curr_thread_id)
  1845. wait_timeout = TIMEOUT_SLOW
  1846. while True:
  1847. with self._main_lock: # Use lock to check if suspended state changed
  1848. if info.pydev_state != STATE_SUSPEND or (self.pydb_disposed and not self.terminate_requested):
  1849. # Note: we can't exit here if terminate was requested while a breakpoint was hit.
  1850. break
  1851. if in_main_thread and self.gui_in_use:
  1852. wait_timeout = TIMEOUT_FAST
  1853. # call input hooks if only GUI is in use
  1854. self._call_input_hook()
  1855. # No longer process commands for '*' at this point, just the
  1856. # ones related to this thread.
  1857. try:
  1858. internal_cmd = queue.get(False)
  1859. except _queue.Empty:
  1860. pass
  1861. else:
  1862. if internal_cmd.can_be_executed_by(curr_thread_id):
  1863. pydev_log.verbose("processing internal command: %s", internal_cmd)
  1864. try:
  1865. internal_cmd.do_it(self)
  1866. except:
  1867. pydev_log.exception("Error processing internal command.")
  1868. else:
  1869. # This shouldn't really happen...
  1870. pydev_log.verbose("NOT processing internal command: %s ", internal_cmd)
  1871. queue.put(internal_cmd)
  1872. wait_timeout = TIMEOUT_FAST
  1873. notify_event.wait(wait_timeout)
  1874. notify_event.clear()
  1875. finally:
  1876. info.is_in_wait_loop = False
  1877. info.update_stepping_info()
  1878. self.cancel_async_evaluation(get_current_thread_id(thread), str(id(frame)))
  1879. # process any stepping instructions
  1880. if info.pydev_step_cmd in (CMD_STEP_INTO, CMD_STEP_INTO_MY_CODE):
  1881. info.step_in_initial_location = (frame, frame.f_lineno)
  1882. if frame.f_code.co_flags & 0x80: # CO_COROUTINE = 0x80
  1883. # When in a coroutine we switch to CMD_STEP_INTO_COROUTINE.
  1884. info.pydev_step_cmd = CMD_STEP_INTO_COROUTINE
  1885. info.pydev_step_stop = frame
  1886. self.set_trace_for_frame_and_parents(thread.ident, frame)
  1887. else:
  1888. info.pydev_step_stop = None
  1889. self.set_trace_for_frame_and_parents(thread.ident, frame)
  1890. elif info.pydev_step_cmd in (CMD_STEP_OVER, CMD_STEP_OVER_MY_CODE, CMD_SMART_STEP_INTO):
  1891. info.pydev_step_stop = frame
  1892. self.set_trace_for_frame_and_parents(thread.ident, frame)
  1893. elif info.pydev_step_cmd == CMD_RUN_TO_LINE or info.pydev_step_cmd == CMD_SET_NEXT_STATEMENT:
  1894. info.pydev_step_stop = None
  1895. self.set_trace_for_frame_and_parents(thread.ident, frame)
  1896. stop = False
  1897. response_msg = ""
  1898. try:
  1899. stop, _old_line, response_msg = self.set_next_statement(frame, event, info.pydev_func_name, info.pydev_next_line)
  1900. except ValueError as e:
  1901. response_msg = "%s" % e
  1902. finally:
  1903. seq = info.pydev_message
  1904. cmd = self.cmd_factory.make_set_next_stmnt_status_message(seq, stop, response_msg)
  1905. self.writer.add_command(cmd)
  1906. info.pydev_message = ""
  1907. if stop:
  1908. # Uninstall the current frames tracker before running it.
  1909. frames_tracker.untrack_all()
  1910. cmd = self.cmd_factory.make_thread_run_message(self, get_current_thread_id(thread), info.pydev_step_cmd)
  1911. self.writer.add_command(cmd)
  1912. info.pydev_state = STATE_SUSPEND
  1913. thread.stop_reason = CMD_SET_NEXT_STATEMENT
  1914. keep_suspended = True
  1915. else:
  1916. # Set next did not work...
  1917. info.pydev_original_step_cmd = -1
  1918. info.pydev_step_cmd = -1
  1919. info.pydev_state = STATE_SUSPEND
  1920. thread.stop_reason = CMD_THREAD_SUSPEND
  1921. # return to the suspend state and wait for other command (without sending any
  1922. # additional notification to the client).
  1923. return self._do_wait_suspend(thread, frame, event, arg, trace_suspend_type, from_this_thread, frames_tracker)
  1924. elif info.pydev_step_cmd in (CMD_STEP_RETURN, CMD_STEP_RETURN_MY_CODE):
  1925. back_frame = frame.f_back
  1926. force_check_project_scope = info.pydev_step_cmd == CMD_STEP_RETURN_MY_CODE
  1927. if force_check_project_scope or self.is_files_filter_enabled:
  1928. while back_frame is not None:
  1929. if self.apply_files_filter(back_frame, back_frame.f_code.co_filename, force_check_project_scope):
  1930. frame = back_frame
  1931. back_frame = back_frame.f_back
  1932. else:
  1933. break
  1934. if back_frame is not None:
  1935. # steps back to the same frame (in a return call it will stop in the 'back frame' for the user)
  1936. info.pydev_step_stop = frame
  1937. self.set_trace_for_frame_and_parents(thread.ident, frame)
  1938. else:
  1939. # No back frame?!? -- this happens in jython when we have some frame created from an awt event
  1940. # (the previous frame would be the awt event, but this doesn't make part of 'jython', only 'java')
  1941. # so, if we're doing a step return in this situation, it's the same as just making it run
  1942. info.pydev_step_stop = None
  1943. info.pydev_original_step_cmd = -1
  1944. info.pydev_step_cmd = -1
  1945. info.pydev_state = STATE_RUN
  1946. if PYDEVD_IPYTHON_COMPATIBLE_DEBUGGING:
  1947. info.pydev_use_scoped_step_frame = False
  1948. if info.pydev_step_cmd in (CMD_STEP_OVER, CMD_STEP_OVER_MY_CODE, CMD_STEP_INTO, CMD_STEP_INTO_MY_CODE):
  1949. # i.e.: We're stepping: check if the stepping should be scoped (i.e.: in ipython
  1950. # each line is executed separately in a new frame, in which case we need to consider
  1951. # the next line as if it was still in the same frame).
  1952. f = frame.f_back
  1953. if f and f.f_code.co_name == PYDEVD_IPYTHON_CONTEXT[1]:
  1954. f = f.f_back
  1955. if f and f.f_code.co_name == PYDEVD_IPYTHON_CONTEXT[2]:
  1956. info.pydev_use_scoped_step_frame = True
  1957. pydev_log.info("Using (ipython) scoped stepping.")
  1958. del f
  1959. del frame
  1960. cmd = self.cmd_factory.make_thread_run_message(self, get_current_thread_id(thread), info.pydev_step_cmd)
  1961. self.writer.add_command(cmd)
  1962. with CustomFramesContainer.custom_frames_lock:
  1963. # The ones that remained on last_running must now be removed.
  1964. for frame_id in from_this_thread:
  1965. # print('Removing created frame: %s' % (frame_id,))
  1966. self.writer.add_command(self.cmd_factory.make_thread_killed_message(frame_id))
  1967. info.update_stepping_info()
  1968. return keep_suspended
  1969. def do_stop_on_unhandled_exception(self, thread, frame, frames_byid, arg):
  1970. pydev_log.debug("We are stopping in unhandled exception.")
  1971. try:
  1972. add_exception_to_frame(frame, arg)
  1973. self.send_caught_exception_stack(thread, arg, id(frame))
  1974. try:
  1975. self.set_suspend(thread, CMD_ADD_EXCEPTION_BREAK)
  1976. self.do_wait_suspend(thread, frame, "exception", arg, EXCEPTION_TYPE_UNHANDLED)
  1977. except:
  1978. self.send_caught_exception_stack_proceeded(thread)
  1979. except:
  1980. pydev_log.exception("We've got an error while stopping in unhandled exception: %s.", arg[0])
  1981. finally:
  1982. remove_exception_from_frame(frame)
  1983. frame = None
  1984. def set_trace_for_frame_and_parents(self, thread_ident: Optional[int], frame, **kwargs):
  1985. disable = kwargs.pop("disable", False)
  1986. assert not kwargs
  1987. DEBUG = True # 'defaulttags' in frame.f_code.co_filename
  1988. while frame is not None:
  1989. if not isinstance(frame, FrameType):
  1990. # This is the case for django/jinja frames.
  1991. frame = frame.f_back
  1992. continue
  1993. # Don't change the tracing on debugger-related files
  1994. file_type = self.get_file_type(frame)
  1995. if PYDEVD_USE_SYS_MONITORING:
  1996. if file_type is None:
  1997. if disable:
  1998. if DEBUG:
  1999. pydev_log.debug("Disable tracing of frame: %s - %s", frame.f_code.co_filename, frame.f_code.co_name)
  2000. pydevd_sys_monitoring.disable_code_tracing(frame.f_code)
  2001. else:
  2002. if DEBUG:
  2003. pydev_log.debug("Set tracing of frame: %s - %s", frame.f_code.co_filename, frame.f_code.co_name)
  2004. pydevd_sys_monitoring.enable_code_tracing(thread_ident, frame.f_code, frame)
  2005. else:
  2006. if DEBUG:
  2007. pydev_log.debug("SKIP set tracing of frame: %s - %s", frame.f_code.co_filename, frame.f_code.co_name)
  2008. else:
  2009. # Not using sys.monitoring.
  2010. if file_type is None:
  2011. if disable:
  2012. if DEBUG:
  2013. pydev_log.debug("Disable tracing of frame: %s - %s", frame.f_code.co_filename, frame.f_code.co_name)
  2014. if frame.f_trace is not None and frame.f_trace is not NO_FTRACE:
  2015. frame.f_trace = NO_FTRACE
  2016. elif frame.f_trace is not self.trace_dispatch:
  2017. if DEBUG:
  2018. pydev_log.debug("Set tracing of frame: %s - %s", frame.f_code.co_filename, frame.f_code.co_name)
  2019. frame.f_trace = self.trace_dispatch
  2020. else:
  2021. if DEBUG:
  2022. pydev_log.debug("SKIP set tracing of frame: %s - %s", frame.f_code.co_filename, frame.f_code.co_name)
  2023. frame = frame.f_back
  2024. del frame
  2025. def _create_pydb_command_thread(self):
  2026. curr_pydb_command_thread = self.py_db_command_thread
  2027. if curr_pydb_command_thread is not None:
  2028. curr_pydb_command_thread.do_kill_pydev_thread()
  2029. new_pydb_command_thread = self.py_db_command_thread = PyDBCommandThread(self)
  2030. new_pydb_command_thread.start()
  2031. def _create_check_output_thread(self):
  2032. curr_output_checker_thread = self.check_alive_thread
  2033. if curr_output_checker_thread is not None:
  2034. curr_output_checker_thread.do_kill_pydev_thread()
  2035. check_alive_thread = self.check_alive_thread = CheckAliveThread(self)
  2036. check_alive_thread.start()
  2037. def start_auxiliary_daemon_threads(self):
  2038. self._create_pydb_command_thread()
  2039. self._create_check_output_thread()
  2040. def __wait_for_threads_to_finish(self, timeout):
  2041. try:
  2042. with self._wait_for_threads_to_finish_called_lock:
  2043. wait_for_threads_to_finish_called = self._wait_for_threads_to_finish_called
  2044. self._wait_for_threads_to_finish_called = True
  2045. if wait_for_threads_to_finish_called:
  2046. # Make sure that we wait for the previous call to be finished.
  2047. self._wait_for_threads_to_finish_called_event.wait(timeout=timeout)
  2048. else:
  2049. try:
  2050. def get_pydb_daemon_threads_to_wait():
  2051. pydb_daemon_threads = set(self.created_pydb_daemon_threads)
  2052. pydb_daemon_threads.discard(self.check_alive_thread)
  2053. pydb_daemon_threads.discard(threading.current_thread())
  2054. return pydb_daemon_threads
  2055. pydev_log.debug("PyDB.dispose_and_kill_all_pydevd_threads waiting for pydb daemon threads to finish")
  2056. started_at = time.time()
  2057. # Note: we wait for all except the check_alive_thread (which is not really a daemon
  2058. # thread and it can call this method itself).
  2059. while time.time() < started_at + timeout:
  2060. if len(get_pydb_daemon_threads_to_wait()) == 0:
  2061. break
  2062. time.sleep(1 / 10.0)
  2063. else:
  2064. thread_names = [t.name for t in get_pydb_daemon_threads_to_wait()]
  2065. if thread_names:
  2066. pydev_log.debug("The following pydb threads may not have finished correctly: %s", ", ".join(thread_names))
  2067. finally:
  2068. self._wait_for_threads_to_finish_called_event.set()
  2069. except:
  2070. pydev_log.exception()
  2071. def dispose_and_kill_all_pydevd_threads(self, wait=True, timeout=0.5):
  2072. """
  2073. When this method is called we finish the debug session, terminate threads
  2074. and if this was registered as the global instance, unregister it -- afterwards
  2075. it should be possible to create a new instance and set as global to start
  2076. a new debug session.
  2077. :param bool wait:
  2078. If True we'll wait for the threads to be actually finished before proceeding
  2079. (based on the available timeout).
  2080. Note that this must be thread-safe and if one thread is waiting the other thread should
  2081. also wait.
  2082. """
  2083. try:
  2084. back_frame = sys._getframe().f_back
  2085. pydev_log.debug(
  2086. 'PyDB.dispose_and_kill_all_pydevd_threads (called from: File "%s", line %s, in %s)',
  2087. back_frame.f_code.co_filename,
  2088. back_frame.f_lineno,
  2089. back_frame.f_code.co_name,
  2090. )
  2091. back_frame = None
  2092. with self._disposed_lock:
  2093. disposed = self.pydb_disposed
  2094. self.pydb_disposed = True
  2095. if disposed:
  2096. if wait:
  2097. pydev_log.debug("PyDB.dispose_and_kill_all_pydevd_threads (already disposed - wait)")
  2098. self.__wait_for_threads_to_finish(timeout)
  2099. else:
  2100. pydev_log.debug("PyDB.dispose_and_kill_all_pydevd_threads (already disposed - no wait)")
  2101. return
  2102. pydev_log.debug("PyDB.dispose_and_kill_all_pydevd_threads (first call)")
  2103. # Wait until a time when there are no commands being processed to kill the threads.
  2104. started_at = time.time()
  2105. while time.time() < started_at + timeout:
  2106. with self._main_lock:
  2107. writer = self.writer
  2108. if writer is None or writer.empty():
  2109. pydev_log.debug("PyDB.dispose_and_kill_all_pydevd_threads no commands being processed.")
  2110. break
  2111. else:
  2112. pydev_log.debug("PyDB.dispose_and_kill_all_pydevd_threads timed out waiting for writer to be empty.")
  2113. pydb_daemon_threads = set(self.created_pydb_daemon_threads)
  2114. for t in pydb_daemon_threads:
  2115. if hasattr(t, "do_kill_pydev_thread"):
  2116. pydev_log.debug("PyDB.dispose_and_kill_all_pydevd_threads killing thread: %s", t)
  2117. t.do_kill_pydev_thread()
  2118. if wait:
  2119. self.__wait_for_threads_to_finish(timeout)
  2120. else:
  2121. pydev_log.debug("PyDB.dispose_and_kill_all_pydevd_threads: no wait")
  2122. py_db = get_global_debugger()
  2123. if py_db is self:
  2124. set_global_debugger(None)
  2125. except:
  2126. pydev_log.debug("PyDB.dispose_and_kill_all_pydevd_threads: exception")
  2127. try:
  2128. if DebugInfoHolder.DEBUG_TRACE_LEVEL >= 3:
  2129. pydev_log.exception()
  2130. except:
  2131. pass
  2132. finally:
  2133. if self._client_socket:
  2134. self._client_socket.close()
  2135. self._client_socket = None
  2136. pydev_log.debug("PyDB.dispose_and_kill_all_pydevd_threads: finished")
  2137. def prepare_to_run(self):
  2138. """Shared code to prepare debugging by installing traces and registering threads"""
  2139. self.patch_threads()
  2140. self.start_auxiliary_daemon_threads()
  2141. def patch_threads(self):
  2142. if PYDEVD_USE_SYS_MONITORING:
  2143. pydevd_sys_monitoring.start_monitoring(all_threads=True)
  2144. else:
  2145. try:
  2146. # not available in jython!
  2147. threading.settrace(self.trace_dispatch) # for all future threads
  2148. except:
  2149. pass
  2150. from _pydev_bundle.pydev_monkey import patch_thread_modules
  2151. patch_thread_modules()
  2152. def run(self, file, globals=None, locals=None, is_module=False, set_trace=True):
  2153. module_name = None
  2154. entry_point_fn = ""
  2155. if is_module:
  2156. # When launching with `python -m <module>`, python automatically adds
  2157. # an empty path to the PYTHONPATH which resolves files in the current
  2158. # directory, so, depending how pydevd itself is launched, we may need
  2159. # to manually add such an entry to properly resolve modules in the
  2160. # current directory (see: https://github.com/Microsoft/ptvsd/issues/1010).
  2161. if "" not in sys.path:
  2162. sys.path.insert(0, "")
  2163. file, _, entry_point_fn = file.partition(":")
  2164. module_name = file
  2165. filename = get_fullname(file)
  2166. if filename is None:
  2167. mod_dir = get_package_dir(module_name)
  2168. if mod_dir is None:
  2169. sys.stderr.write("No module named %s\n" % file)
  2170. return
  2171. else:
  2172. filename = get_fullname("%s.__main__" % module_name)
  2173. if filename is None:
  2174. sys.stderr.write("No module named %s\n" % file)
  2175. return
  2176. else:
  2177. file = filename
  2178. else:
  2179. file = filename
  2180. mod_dir = os.path.dirname(filename)
  2181. main_py = os.path.join(mod_dir, "__main__.py")
  2182. main_pyc = os.path.join(mod_dir, "__main__.pyc")
  2183. if filename.endswith("__init__.pyc"):
  2184. if os.path.exists(main_pyc):
  2185. filename = main_pyc
  2186. elif os.path.exists(main_py):
  2187. filename = main_py
  2188. elif filename.endswith("__init__.py"):
  2189. if os.path.exists(main_pyc) and not os.path.exists(main_py):
  2190. filename = main_pyc
  2191. elif os.path.exists(main_py):
  2192. filename = main_py
  2193. sys.argv[0] = filename
  2194. if os.path.isdir(file):
  2195. new_target = os.path.join(file, "__main__.py")
  2196. if os.path.isfile(new_target):
  2197. file = new_target
  2198. m = None
  2199. if globals is None:
  2200. m = save_main_module(file, "pydevd")
  2201. globals = m.__dict__
  2202. try:
  2203. globals["__builtins__"] = __builtins__
  2204. except NameError:
  2205. pass # Not there on Jython...
  2206. if locals is None:
  2207. locals = globals
  2208. # Predefined (writable) attributes: __name__ is the module's name;
  2209. # __doc__ is the module's documentation string, or None if unavailable;
  2210. # __file__ is the pathname of the file from which the module was loaded,
  2211. # if it was loaded from a file. The __file__ attribute is not present for
  2212. # C modules that are statically linked into the interpreter; for extension modules
  2213. # loaded dynamically from a shared library, it is the pathname of the shared library file.
  2214. # I think this is an ugly hack, bug it works (seems to) for the bug that says that sys.path should be the same in
  2215. # debug and run.
  2216. if sys.path[0] != "" and m is not None and m.__file__.startswith(sys.path[0]):
  2217. # print >> sys.stderr, 'Deleting: ', sys.path[0]
  2218. del sys.path[0]
  2219. if not is_module:
  2220. # now, the local directory has to be added to the pythonpath
  2221. # sys.path.insert(0, os.getcwd())
  2222. # Changed: it's not the local directory, but the directory of the file launched
  2223. # The file being run must be in the pythonpath (even if it was not before)
  2224. sys.path.insert(0, os.path.split(os_path_abspath(file))[0])
  2225. if set_trace:
  2226. self.wait_for_ready_to_run()
  2227. # call prepare_to_run when we already have all information about breakpoints
  2228. self.prepare_to_run()
  2229. t = threadingCurrentThread()
  2230. thread_id = get_current_thread_id(t)
  2231. if self.thread_analyser is not None:
  2232. wrap_threads()
  2233. self.thread_analyser.set_start_time(cur_time())
  2234. send_concurrency_message("threading_event", 0, t.name, thread_id, "thread", "start", file, 1, None, parent=thread_id)
  2235. if self.asyncio_analyser is not None:
  2236. # we don't have main thread in asyncio graph, so we should add a fake event
  2237. send_concurrency_message("asyncio_event", 0, "Task", "Task", "thread", "stop", file, 1, frame=None, parent=None)
  2238. try:
  2239. if INTERACTIVE_MODE_AVAILABLE:
  2240. self.init_gui_support()
  2241. except:
  2242. pydev_log.exception("Matplotlib support in debugger failed")
  2243. if hasattr(sys, "exc_clear"):
  2244. # we should clean exception information in Python 2, before user's code execution
  2245. sys.exc_clear()
  2246. # Notify that the main thread is created.
  2247. self.notify_thread_created(thread_id, t)
  2248. # Note: important: set the tracing right before calling _exec.
  2249. if set_trace:
  2250. self.enable_tracing()
  2251. return self._exec(is_module, entry_point_fn, module_name, file, globals, locals)
  2252. def _exec(self, is_module, entry_point_fn, module_name, file, globals, locals):
  2253. """
  2254. This function should have frames tracked by unhandled exceptions (the `_exec` name is important).
  2255. """
  2256. t = threading.current_thread() # Keep in 't' local variable to be accessed afterwards from frame.f_locals.
  2257. if not is_module:
  2258. globals = pydevd_runpy.run_path(file, globals, "__main__")
  2259. else:
  2260. # treat ':' as a separator between module and entry point function
  2261. # if there is no entry point we run we same as with -m switch. Otherwise we perform
  2262. # an import and execute the entry point
  2263. if entry_point_fn:
  2264. mod = __import__(module_name, level=0, fromlist=[entry_point_fn], globals=globals, locals=locals)
  2265. func = getattr(mod, entry_point_fn)
  2266. func()
  2267. else:
  2268. # Run with the -m switch
  2269. globals = pydevd_runpy._run_module_as_main(module_name, alter_argv=False)
  2270. return globals
  2271. def wait_for_commands(self, globals):
  2272. self._activate_gui_if_needed()
  2273. thread = threading.current_thread()
  2274. from _pydevd_bundle import pydevd_frame_utils
  2275. frame = pydevd_frame_utils.Frame(
  2276. None, -1, pydevd_frame_utils.FCode("Console", os.path.abspath(os.path.dirname(__file__))), globals, globals
  2277. )
  2278. thread_id = get_current_thread_id(thread)
  2279. self.add_fake_frame(thread_id, id(frame), frame)
  2280. cmd = self.cmd_factory.make_show_console_message(self, thread_id, frame)
  2281. if self.writer is not None:
  2282. self.writer.add_command(cmd)
  2283. while True:
  2284. if self.gui_in_use:
  2285. # call input hooks if only GUI is in use
  2286. self._call_input_hook()
  2287. self.process_internal_commands()
  2288. time.sleep(0.01)
  2289. class IDAPMessagesListener(object):
  2290. def before_send(self, message_as_dict):
  2291. """
  2292. Called just before a message is sent to the IDE.
  2293. :type message_as_dict: dict
  2294. """
  2295. def after_receive(self, message_as_dict):
  2296. """
  2297. Called just after a message is received from the IDE.
  2298. :type message_as_dict: dict
  2299. """
  2300. def add_dap_messages_listener(dap_messages_listener):
  2301. """
  2302. Adds a listener for the DAP (debug adapter protocol) messages.
  2303. :type dap_messages_listener: IDAPMessagesListener
  2304. :note: messages from the xml backend are not notified through this API.
  2305. :note: the notifications are sent from threads and they are not synchronized (so,
  2306. it's possible that a message is sent and received from different threads at the same time).
  2307. """
  2308. py_db = get_global_debugger()
  2309. if py_db is None:
  2310. raise AssertionError("PyDB is still not setup.")
  2311. py_db.add_dap_messages_listener(dap_messages_listener)
  2312. def send_json_message(msg):
  2313. """
  2314. API to send some custom json message.
  2315. :param dict|pydevd_schema.BaseSchema msg:
  2316. The custom message to be sent.
  2317. :return bool:
  2318. True if the message was added to the queue to be sent and False otherwise.
  2319. """
  2320. py_db = get_global_debugger()
  2321. if py_db is None:
  2322. return False
  2323. writer = py_db.writer
  2324. if writer is None:
  2325. return False
  2326. cmd = NetCommand(-1, 0, msg, is_json=True)
  2327. writer.add_command(cmd)
  2328. return True
  2329. def enable_qt_support(qt_support_mode):
  2330. from _pydev_bundle import pydev_monkey_qt
  2331. pydev_monkey_qt.patch_qt(qt_support_mode)
  2332. def start_dump_threads_thread(filename_template, timeout, recurrent):
  2333. """
  2334. Helper to dump threads after a timeout.
  2335. :param filename_template:
  2336. A template filename, such as 'c:/temp/thread_dump_%s.txt', where the %s will
  2337. be replaced by the time for the dump.
  2338. :param timeout:
  2339. The timeout (in seconds) for the dump.
  2340. :param recurrent:
  2341. If True we'll keep on doing thread dumps.
  2342. """
  2343. assert filename_template.count("%s") == 1, "Expected one %%s to appear in: %s" % (filename_template,)
  2344. def _threads_on_timeout():
  2345. try:
  2346. while True:
  2347. time.sleep(timeout)
  2348. filename = filename_template % (time.time(),)
  2349. try:
  2350. os.makedirs(os.path.dirname(filename))
  2351. except Exception:
  2352. pass
  2353. with open(filename, "w") as stream:
  2354. dump_threads(stream)
  2355. if not recurrent:
  2356. return
  2357. except Exception:
  2358. pydev_log.exception()
  2359. t = threading.Thread(target=_threads_on_timeout)
  2360. mark_as_pydevd_daemon_thread(t)
  2361. t.start()
  2362. def dump_threads(stream=None):
  2363. """
  2364. Helper to dump thread info (default is printing to stderr).
  2365. """
  2366. pydevd_utils.dump_threads(stream)
  2367. def usage(doExit=0):
  2368. sys.stdout.write("Usage:\n")
  2369. sys.stdout.write("pydevd.py --port N [(--client hostname) | --server] --file executable [file_options]\n")
  2370. if doExit:
  2371. sys.exit(0)
  2372. def _init_stdout_redirect():
  2373. pydevd_io.redirect_stream_to_pydb_io_messages(std="stdout")
  2374. def _init_stderr_redirect():
  2375. pydevd_io.redirect_stream_to_pydb_io_messages(std="stderr")
  2376. def _enable_attach(
  2377. address,
  2378. dont_trace_start_patterns=(),
  2379. dont_trace_end_patterns=(),
  2380. patch_multiprocessing=False,
  2381. access_token=None,
  2382. client_access_token=None,
  2383. ):
  2384. """
  2385. Starts accepting connections at the given host/port. The debugger will not be initialized nor
  2386. configured, it'll only start accepting connections (and will have the tracing setup in this
  2387. thread).
  2388. Meant to be used with the DAP (Debug Adapter Protocol) with _wait_for_attach().
  2389. :param address: (host, port)
  2390. :type address: tuple(str, int)
  2391. """
  2392. host = address[0]
  2393. port = int(address[1])
  2394. if SetupHolder.setup is not None:
  2395. if port != SetupHolder.setup["port"]:
  2396. raise AssertionError("Unable to listen in port: %s (already listening in port: %s)" % (port, SetupHolder.setup["port"]))
  2397. settrace(
  2398. host=host,
  2399. port=port,
  2400. suspend=False,
  2401. wait_for_ready_to_run=False,
  2402. block_until_connected=False,
  2403. dont_trace_start_patterns=dont_trace_start_patterns,
  2404. dont_trace_end_patterns=dont_trace_end_patterns,
  2405. patch_multiprocessing=patch_multiprocessing,
  2406. access_token=access_token,
  2407. client_access_token=client_access_token,
  2408. )
  2409. py_db = get_global_debugger()
  2410. py_db.wait_for_server_socket_ready()
  2411. return py_db._server_socket_name
  2412. def _wait_for_attach(cancel=None):
  2413. """
  2414. Meant to be called after _enable_attach() -- the current thread will only unblock after a
  2415. connection is in place and the DAP (Debug Adapter Protocol) sends the ConfigurationDone
  2416. request.
  2417. """
  2418. py_db = get_global_debugger()
  2419. if py_db is None:
  2420. raise AssertionError("Debugger still not created. Please use _enable_attach() before using _wait_for_attach().")
  2421. py_db.block_until_configuration_done(cancel=cancel)
  2422. def _is_attached():
  2423. """
  2424. Can be called any time to check if the connection was established and the DAP (Debug Adapter Protocol) has sent
  2425. the ConfigurationDone request.
  2426. """
  2427. py_db = get_global_debugger()
  2428. return (py_db is not None) and py_db.is_attached()
  2429. # =======================================================================================================================
  2430. # settrace
  2431. # =======================================================================================================================
  2432. def settrace(
  2433. host=None,
  2434. stdout_to_server=False,
  2435. stderr_to_server=False,
  2436. port=5678,
  2437. suspend=True,
  2438. trace_only_current_thread=False,
  2439. overwrite_prev_trace=False, # Deprecated
  2440. patch_multiprocessing=False,
  2441. stop_at_frame=None,
  2442. block_until_connected=True,
  2443. wait_for_ready_to_run=True,
  2444. dont_trace_start_patterns=(),
  2445. dont_trace_end_patterns=(),
  2446. access_token=None,
  2447. client_access_token=None,
  2448. notify_stdin=True,
  2449. protocol=None,
  2450. ppid=0,
  2451. **kwargs,
  2452. ):
  2453. """Sets the tracing function with the pydev debug function and initializes needed facilities.
  2454. :param host: the user may specify another host, if the debug server is not in the same machine (default is the local
  2455. host)
  2456. :param stdout_to_server: when this is true, the stdout is passed to the debug server
  2457. :param stderr_to_server: when this is true, the stderr is passed to the debug server
  2458. so that they are printed in its console and not in this process console.
  2459. :param port: specifies which port to use for communicating with the server (note that the server must be started
  2460. in the same port). @note: currently it's hard-coded at 5678 in the client
  2461. :param suspend: whether a breakpoint should be emulated as soon as this function is called.
  2462. :param trace_only_current_thread: determines if only the current thread will be traced or all current and future
  2463. threads will also have the tracing enabled.
  2464. :param overwrite_prev_trace: deprecated
  2465. :param patch_multiprocessing: if True we'll patch the functions which create new processes so that launched
  2466. processes are debugged.
  2467. :param stop_at_frame: if passed it'll stop at the given frame, otherwise it'll stop in the function which
  2468. called this method.
  2469. :param wait_for_ready_to_run: if True settrace will block until the ready_to_run flag is set to True,
  2470. otherwise, it'll set ready_to_run to True and this function won't block.
  2471. Note that if wait_for_ready_to_run == False, there are no guarantees that the debugger is synchronized
  2472. with what's configured in the client (IDE), the only guarantee is that when leaving this function
  2473. the debugger will be already connected.
  2474. :param dont_trace_start_patterns: if set, then any path that starts with one fo the patterns in the collection
  2475. will not be traced
  2476. :param dont_trace_end_patterns: if set, then any path that ends with one fo the patterns in the collection
  2477. will not be traced
  2478. :param access_token: token to be sent from the client (i.e.: IDE) to the debugger when a connection
  2479. is established (verified by the debugger).
  2480. :param client_access_token: token to be sent from the debugger to the client (i.e.: IDE) when
  2481. a connection is established (verified by the client).
  2482. :param notify_stdin:
  2483. If True sys.stdin will be patched to notify the client when a message is requested
  2484. from the IDE. This is done so that when reading the stdin the client is notified.
  2485. Clients may need this to know when something that is being written should be interpreted
  2486. as an input to the process or as a command to be evaluated.
  2487. Note that parallel-python has issues with this (because it tries to assert that sys.stdin
  2488. is of a given type instead of just checking that it has what it needs).
  2489. :param protocol:
  2490. When using in Eclipse the protocol should not be passed, but when used in VSCode
  2491. or some other IDE/editor that accepts the Debug Adapter Protocol then 'dap' should
  2492. be passed.
  2493. :param ppid:
  2494. Override the parent process id (PPID) for the current debugging session. This PPID is
  2495. reported to the debug client (IDE) and can be used to act like a child process of an
  2496. existing debugged process without being a child process.
  2497. """
  2498. if protocol and protocol.lower() == "dap":
  2499. pydevd_defaults.PydevdCustomization.DEFAULT_PROTOCOL = pydevd_constants.HTTP_JSON_PROTOCOL
  2500. stdout_to_server = stdout_to_server or kwargs.get("stdoutToServer", False) # Backward compatibility
  2501. stderr_to_server = stderr_to_server or kwargs.get("stderrToServer", False) # Backward compatibility
  2502. # Internal use (may be used to set the setup info directly for subprocesess).
  2503. __setup_holder__ = kwargs.get("__setup_holder__")
  2504. with _set_trace_lock:
  2505. _locked_settrace(
  2506. host,
  2507. stdout_to_server,
  2508. stderr_to_server,
  2509. port,
  2510. suspend,
  2511. trace_only_current_thread,
  2512. patch_multiprocessing,
  2513. stop_at_frame,
  2514. block_until_connected,
  2515. wait_for_ready_to_run,
  2516. dont_trace_start_patterns,
  2517. dont_trace_end_patterns,
  2518. access_token,
  2519. client_access_token,
  2520. __setup_holder__=__setup_holder__,
  2521. notify_stdin=notify_stdin,
  2522. ppid=ppid,
  2523. )
  2524. _set_trace_lock = ForkSafeLock()
  2525. def _locked_settrace(
  2526. host,
  2527. stdout_to_server,
  2528. stderr_to_server,
  2529. port,
  2530. suspend,
  2531. trace_only_current_thread,
  2532. patch_multiprocessing,
  2533. stop_at_frame,
  2534. block_until_connected,
  2535. wait_for_ready_to_run,
  2536. dont_trace_start_patterns,
  2537. dont_trace_end_patterns,
  2538. access_token,
  2539. client_access_token,
  2540. __setup_holder__,
  2541. notify_stdin,
  2542. ppid,
  2543. ):
  2544. if patch_multiprocessing:
  2545. try:
  2546. from _pydev_bundle import pydev_monkey
  2547. except:
  2548. pass
  2549. else:
  2550. pydev_monkey.patch_new_process_functions()
  2551. if host is None:
  2552. from _pydev_bundle import pydev_localhost
  2553. host = pydev_localhost.get_localhost()
  2554. global _global_redirect_stdout_to_server
  2555. global _global_redirect_stderr_to_server
  2556. py_db = get_global_debugger()
  2557. if __setup_holder__:
  2558. SetupHolder.setup = __setup_holder__
  2559. if py_db is None:
  2560. py_db = PyDB()
  2561. pydevd_vm_type.setup_type()
  2562. if SetupHolder.setup is None:
  2563. setup = {
  2564. "client": host, # dispatch expects client to be set to the host address when server is False
  2565. "server": False,
  2566. "port": int(port),
  2567. "multiprocess": patch_multiprocessing,
  2568. "skip-notify-stdin": not notify_stdin,
  2569. pydevd_constants.ARGUMENT_PPID: ppid,
  2570. }
  2571. SetupHolder.setup = setup
  2572. if access_token is not None:
  2573. py_db.authentication.access_token = access_token
  2574. SetupHolder.setup["access-token"] = access_token
  2575. if client_access_token is not None:
  2576. py_db.authentication.client_access_token = client_access_token
  2577. SetupHolder.setup["client-access-token"] = client_access_token
  2578. if block_until_connected:
  2579. py_db.connect(host, port) # Note: connect can raise error.
  2580. else:
  2581. # Create a dummy writer and wait for the real connection.
  2582. py_db.writer = WriterThread(NULL, py_db, terminate_on_socket_close=False)
  2583. py_db.create_wait_for_connection_thread()
  2584. if dont_trace_start_patterns or dont_trace_end_patterns:
  2585. PyDevdAPI().set_dont_trace_start_end_patterns(py_db, dont_trace_start_patterns, dont_trace_end_patterns)
  2586. _global_redirect_stdout_to_server = stdout_to_server
  2587. _global_redirect_stderr_to_server = stderr_to_server
  2588. if _global_redirect_stdout_to_server:
  2589. _init_stdout_redirect()
  2590. if _global_redirect_stderr_to_server:
  2591. _init_stderr_redirect()
  2592. if notify_stdin:
  2593. patch_stdin()
  2594. t = threadingCurrentThread()
  2595. additional_info = set_additional_thread_info(t)
  2596. if not wait_for_ready_to_run:
  2597. py_db.ready_to_run = True
  2598. py_db.wait_for_ready_to_run()
  2599. py_db.start_auxiliary_daemon_threads()
  2600. try:
  2601. if INTERACTIVE_MODE_AVAILABLE:
  2602. py_db.init_gui_support()
  2603. except:
  2604. pydev_log.exception("Matplotlib support in debugger failed")
  2605. if trace_only_current_thread:
  2606. py_db.enable_tracing()
  2607. else:
  2608. # Trace future threads.
  2609. py_db.patch_threads()
  2610. py_db.enable_tracing(py_db.trace_dispatch, apply_to_all_threads=True)
  2611. # As this is the first connection, also set tracing for any untraced threads
  2612. py_db.set_tracing_for_untraced_contexts()
  2613. py_db.set_trace_for_frame_and_parents(t.ident, get_frame().f_back)
  2614. with CustomFramesContainer.custom_frames_lock: # @UndefinedVariable
  2615. for _frameId, custom_frame in CustomFramesContainer.custom_frames.items():
  2616. py_db.set_trace_for_frame_and_parents(None, custom_frame.frame)
  2617. else:
  2618. # ok, we're already in debug mode, with all set, so, let's just set the break
  2619. if access_token is not None:
  2620. py_db.authentication.access_token = access_token
  2621. if client_access_token is not None:
  2622. py_db.authentication.client_access_token = client_access_token
  2623. t = threadingCurrentThread()
  2624. py_db.set_trace_for_frame_and_parents(t.ident, get_frame().f_back)
  2625. additional_info = set_additional_thread_info(t)
  2626. if trace_only_current_thread:
  2627. py_db.enable_tracing()
  2628. else:
  2629. # Trace future threads.
  2630. py_db.patch_threads()
  2631. py_db.enable_tracing(py_db.trace_dispatch, apply_to_all_threads=True)
  2632. # Suspend as the last thing after all tracing is in place.
  2633. if suspend:
  2634. additional_info.pydev_original_step_cmd = CMD_SET_BREAK
  2635. if stop_at_frame is not None:
  2636. # If the step was set we have to go to run state and
  2637. # set the proper frame for it to stop.
  2638. additional_info.pydev_state = STATE_RUN
  2639. additional_info.pydev_step_cmd = CMD_STEP_OVER
  2640. additional_info.pydev_step_stop = stop_at_frame
  2641. additional_info.suspend_type = PYTHON_SUSPEND
  2642. additional_info.update_stepping_info()
  2643. if PYDEVD_USE_SYS_MONITORING:
  2644. pydevd_sys_monitoring.update_monitor_events(suspend_requested=True)
  2645. py_db.set_trace_for_frame_and_parents(t.ident, stop_at_frame)
  2646. else:
  2647. # Ask to break as soon as possible.
  2648. py_db.set_suspend(t, CMD_SET_BREAK, suspend_requested=True)
  2649. py_db.set_trace_for_frame_and_parents(t.ident, get_frame().f_back)
  2650. if PYDEVD_USE_SYS_MONITORING:
  2651. pydevd_sys_monitoring.restart_events()
  2652. def stoptrace():
  2653. pydev_log.debug("pydevd.stoptrace()")
  2654. pydevd_tracing.restore_sys_set_trace_func()
  2655. if PYDEVD_USE_SYS_MONITORING:
  2656. pydevd_sys_monitoring.stop_monitoring(all_threads=True)
  2657. else:
  2658. sys.settrace(None)
  2659. try:
  2660. # not available in jython!
  2661. threading.settrace(None) # for all future threads
  2662. except:
  2663. pass
  2664. from _pydev_bundle.pydev_monkey import undo_patch_thread_modules
  2665. undo_patch_thread_modules()
  2666. # Either or both standard streams can be closed at this point,
  2667. # in which case flush() will fail.
  2668. try:
  2669. sys.stdout.flush()
  2670. except:
  2671. pass
  2672. try:
  2673. sys.stderr.flush()
  2674. except:
  2675. pass
  2676. py_db = get_global_debugger()
  2677. if py_db is not None:
  2678. py_db.dispose_and_kill_all_pydevd_threads()
  2679. class Dispatcher(object):
  2680. def __init__(self):
  2681. self.port = None
  2682. def connect(self, host, port):
  2683. self.host = host
  2684. self.port = port
  2685. self.client = start_client(self.host, self.port)
  2686. self.reader = DispatchReader(self)
  2687. self.reader.pydev_do_not_trace = False # we run reader in the same thread so we don't want to loose tracing
  2688. self.reader.run()
  2689. def close(self):
  2690. try:
  2691. self.reader.do_kill_pydev_thread()
  2692. except:
  2693. pass
  2694. class DispatchReader(ReaderThread):
  2695. def __init__(self, dispatcher):
  2696. self.dispatcher = dispatcher
  2697. ReaderThread.__init__(
  2698. self,
  2699. get_global_debugger(),
  2700. self.dispatcher.client,
  2701. PyDevJsonCommandProcessor=PyDevJsonCommandProcessor,
  2702. process_net_command=process_net_command,
  2703. )
  2704. @overrides(ReaderThread._on_run)
  2705. def _on_run(self):
  2706. dummy_thread = threading.current_thread()
  2707. dummy_thread.is_pydev_daemon_thread = False
  2708. return ReaderThread._on_run(self)
  2709. @overrides(PyDBDaemonThread.do_kill_pydev_thread)
  2710. def do_kill_pydev_thread(self):
  2711. if not self._kill_received:
  2712. ReaderThread.do_kill_pydev_thread(self)
  2713. try:
  2714. self.sock.shutdown(SHUT_RDWR)
  2715. except:
  2716. pass
  2717. try:
  2718. self.sock.close()
  2719. except:
  2720. pass
  2721. def process_command(self, cmd_id, seq, text):
  2722. if cmd_id == 99:
  2723. self.dispatcher.port = int(text)
  2724. self._kill_received = True
  2725. DISPATCH_APPROACH_NEW_CONNECTION = 1 # Used by PyDev
  2726. DISPATCH_APPROACH_EXISTING_CONNECTION = 2 # Used by PyCharm
  2727. DISPATCH_APPROACH = DISPATCH_APPROACH_NEW_CONNECTION
  2728. def dispatch():
  2729. setup = SetupHolder.setup
  2730. host = setup["client"]
  2731. port = setup["port"]
  2732. if DISPATCH_APPROACH == DISPATCH_APPROACH_EXISTING_CONNECTION:
  2733. dispatcher = Dispatcher()
  2734. try:
  2735. dispatcher.connect(host, port)
  2736. port = dispatcher.port
  2737. finally:
  2738. dispatcher.close()
  2739. return host, port
  2740. def settrace_forked(setup_tracing=True):
  2741. """
  2742. When creating a fork from a process in the debugger, we need to reset the whole debugger environment!
  2743. """
  2744. from _pydevd_bundle.pydevd_constants import GlobalDebuggerHolder
  2745. py_db = GlobalDebuggerHolder.global_dbg
  2746. if py_db is not None:
  2747. py_db.created_pydb_daemon_threads = {} # Just making sure we won't touch those (paused) threads.
  2748. py_db = None
  2749. GlobalDebuggerHolder.global_dbg = None
  2750. threading.current_thread().additional_info = None
  2751. # Make sure that we keep the same access tokens for subprocesses started through fork.
  2752. setup = SetupHolder.setup
  2753. if setup is None:
  2754. setup = {}
  2755. else:
  2756. # i.e.: Get the ppid at this point as it just changed.
  2757. # If we later do an exec() it should remain the same ppid.
  2758. setup[pydevd_constants.ARGUMENT_PPID] = PyDevdAPI().get_ppid()
  2759. access_token = setup.get("access-token")
  2760. client_access_token = setup.get("client-access-token")
  2761. if setup_tracing:
  2762. from _pydevd_frame_eval.pydevd_frame_eval_main import clear_thread_local_info
  2763. host, port = dispatch()
  2764. import pydevd_tracing
  2765. pydevd_tracing.restore_sys_set_trace_func()
  2766. if setup_tracing:
  2767. if port is not None:
  2768. custom_frames_container_init()
  2769. if clear_thread_local_info is not None:
  2770. clear_thread_local_info()
  2771. if PYDEVD_USE_SYS_MONITORING:
  2772. pydevd_sys_monitoring.reset_thread_local_info()
  2773. settrace(
  2774. host,
  2775. port=port,
  2776. suspend=False,
  2777. trace_only_current_thread=False,
  2778. overwrite_prev_trace=True,
  2779. patch_multiprocessing=True,
  2780. access_token=access_token,
  2781. client_access_token=client_access_token,
  2782. )
  2783. @contextmanager
  2784. def skip_subprocess_arg_patch():
  2785. """
  2786. May be used to skip the monkey-patching that pydevd does to
  2787. skip changing arguments to embed the debugger into child processes.
  2788. i.e.:
  2789. with pydevd.skip_subprocess_arg_patch():
  2790. subprocess.call(...)
  2791. """
  2792. from _pydev_bundle import pydev_monkey
  2793. with pydev_monkey.skip_subprocess_arg_patch():
  2794. yield
  2795. def add_dont_terminate_child_pid(pid):
  2796. """
  2797. May be used to ask pydevd to skip the termination of some process
  2798. when it's asked to terminate (debug adapter protocol only).
  2799. :param int pid:
  2800. The pid to be ignored.
  2801. i.e.:
  2802. process = subprocess.Popen(...)
  2803. pydevd.add_dont_terminate_child_pid(process.pid)
  2804. """
  2805. py_db = get_global_debugger()
  2806. if py_db is not None:
  2807. py_db.dont_terminate_child_pids.add(pid)
  2808. class SetupHolder:
  2809. setup = None
  2810. def apply_debugger_options(setup_options):
  2811. """
  2812. :type setup_options: dict[str, bool]
  2813. """
  2814. default_options = {"save-signatures": False, "qt-support": ""}
  2815. default_options.update(setup_options)
  2816. setup_options = default_options
  2817. debugger = get_global_debugger()
  2818. if setup_options["save-signatures"]:
  2819. if pydevd_vm_type.get_vm_type() == pydevd_vm_type.PydevdVmType.JYTHON:
  2820. sys.stderr.write("Collecting run-time type information is not supported for Jython\n")
  2821. else:
  2822. # Only import it if we're going to use it!
  2823. from _pydevd_bundle.pydevd_signature import SignatureFactory
  2824. debugger.signature_factory = SignatureFactory()
  2825. if setup_options["qt-support"]:
  2826. enable_qt_support(setup_options["qt-support"])
  2827. @call_only_once
  2828. def patch_stdin():
  2829. _internal_patch_stdin(None, sys, getpass_mod)
  2830. def _internal_patch_stdin(py_db=None, sys=None, getpass_mod=None):
  2831. """
  2832. Note: don't use this function directly, use `patch_stdin()` instead.
  2833. (this function is only meant to be used on test-cases to avoid patching the actual globals).
  2834. """
  2835. # Patch stdin so that we notify when readline() is called.
  2836. original_sys_stdin = sys.stdin
  2837. debug_console_stdin = DebugConsoleStdIn(py_db, original_sys_stdin)
  2838. sys.stdin = debug_console_stdin
  2839. _original_getpass = getpass_mod.getpass
  2840. @functools.wraps(_original_getpass)
  2841. def getpass(*args, **kwargs):
  2842. with DebugConsoleStdIn.notify_input_requested(debug_console_stdin):
  2843. try:
  2844. curr_stdin = sys.stdin
  2845. if curr_stdin is debug_console_stdin:
  2846. sys.stdin = original_sys_stdin
  2847. return _original_getpass(*args, **kwargs)
  2848. finally:
  2849. sys.stdin = curr_stdin
  2850. getpass_mod.getpass = getpass
  2851. # Dispatch on_debugger_modules_loaded here, after all primary py_db modules are loaded
  2852. for handler in pydevd_extension_utils.extensions_of_type(DebuggerEventHandler):
  2853. handler.on_debugger_modules_loaded(debugger_version=__version__)
  2854. def log_to(log_file: str, log_level=3) -> None:
  2855. """
  2856. In pydevd it's possible to log by setting the following environment variables:
  2857. PYDEVD_DEBUG=1 (sets the default log level to 3 along with other default options)
  2858. PYDEVD_DEBUG_FILE=</path/to/file.log>
  2859. Note that the file will have the pid of the process added to it (so, logging to
  2860. /path/to/file.log would actually start logging to /path/to/file.<pid>.log -- if subprocesses are
  2861. logged, each new subprocess will have the logging set to its own pid).
  2862. Usually setting the environment variable is preferred as it'd log information while
  2863. pydevd is still doing its imports and not just after this method is called, but on
  2864. cases where this is hard to do this function may be called to set the tracing after
  2865. pydevd itself is already imported.
  2866. """
  2867. pydev_log.log_to(log_file, log_level)
  2868. def _log_initial_info():
  2869. pydev_log.debug("Initial arguments: %s", (sys.argv,))
  2870. pydev_log.debug("Current pid: %s", os.getpid())
  2871. pydev_log.debug("Using cython: %s", USING_CYTHON)
  2872. pydev_log.debug("Using frame eval: %s", USING_FRAME_EVAL)
  2873. pydev_log.debug("Using gevent mode: %s / imported gevent module support: %s", SUPPORT_GEVENT, bool(pydevd_gevent_integration))
  2874. def config(protocol="", debug_mode="", preimport=""):
  2875. pydev_log.debug("Config: protocol: %s, debug_mode: %s, preimport: %s", protocol, debug_mode, preimport)
  2876. PydevdCustomization.DEFAULT_PROTOCOL = protocol
  2877. PydevdCustomization.DEBUG_MODE = debug_mode
  2878. PydevdCustomization.PREIMPORT = preimport
  2879. # =======================================================================================================================
  2880. # main
  2881. # =======================================================================================================================
  2882. def main():
  2883. # parse the command line. --file is our last argument that is required
  2884. _log_initial_info()
  2885. original_argv = sys.argv[:]
  2886. try:
  2887. from _pydevd_bundle.pydevd_command_line_handling import process_command_line
  2888. setup = process_command_line(sys.argv)
  2889. SetupHolder.setup = setup
  2890. except ValueError:
  2891. pydev_log.exception()
  2892. usage(1)
  2893. preimport = setup.get("preimport")
  2894. if preimport:
  2895. pydevd_defaults.PydevdCustomization.PREIMPORT = preimport
  2896. debug_mode = setup.get("debug-mode")
  2897. if debug_mode:
  2898. pydevd_defaults.PydevdCustomization.DEBUG_MODE = debug_mode
  2899. log_trace_level = setup.get("log-level")
  2900. # Note: the logging info could've been changed (this would happen if this is a
  2901. # subprocess and the value in the environment variable does not match the value in the
  2902. # argument because the user used `pydevd.log_to` instead of supplying the environment
  2903. # variable). If this is the case, update the logging info and re-log some information
  2904. # in the new target.
  2905. new_debug_file = setup.get("log-file")
  2906. if new_debug_file and DebugInfoHolder.PYDEVD_DEBUG_FILE != new_debug_file:
  2907. # The debug file can't be set directly, we need to use log_to() so that the a
  2908. # new stream is actually created for the new file.
  2909. log_to(new_debug_file, log_trace_level if log_trace_level is not None else 3)
  2910. _log_initial_info() # The redirection info just changed, log it again.
  2911. elif log_trace_level is not None:
  2912. # The log file was not specified
  2913. DebugInfoHolder.DEBUG_TRACE_LEVEL = log_trace_level
  2914. pydev_log.debug("Original sys.argv: %s", original_argv)
  2915. if setup["print-in-debugger-startup"]:
  2916. try:
  2917. pid = " (pid: %s)" % os.getpid()
  2918. except:
  2919. pid = ""
  2920. sys.stderr.write("pydev debugger: starting%s\n" % pid)
  2921. pydev_log.debug("Executing file %s", setup["file"])
  2922. pydev_log.debug("arguments: %s", (sys.argv,))
  2923. pydevd_vm_type.setup_type(setup.get("vm_type", None))
  2924. port = setup["port"]
  2925. host = setup["client"]
  2926. f = setup["file"]
  2927. fix_app_engine_debug = False
  2928. debugger = get_global_debugger()
  2929. if debugger is None:
  2930. debugger = PyDB()
  2931. try:
  2932. from _pydev_bundle import pydev_monkey
  2933. except:
  2934. pass # Not usable on jython 2.1
  2935. else:
  2936. if setup["multiprocess"]: # PyDev
  2937. pydev_monkey.patch_new_process_functions()
  2938. elif setup["multiproc"]: # PyCharm
  2939. pydev_log.debug("Started in multiproc mode\n")
  2940. global DISPATCH_APPROACH
  2941. DISPATCH_APPROACH = DISPATCH_APPROACH_EXISTING_CONNECTION
  2942. dispatcher = Dispatcher()
  2943. try:
  2944. dispatcher.connect(host, port)
  2945. if dispatcher.port is not None:
  2946. port = dispatcher.port
  2947. pydev_log.debug("Received port %d\n", port)
  2948. pydev_log.info("pydev debugger: process %d is connecting\n" % os.getpid())
  2949. try:
  2950. pydev_monkey.patch_new_process_functions()
  2951. except:
  2952. pydev_log.exception("Error patching process functions.")
  2953. else:
  2954. pydev_log.critical("pydev debugger: couldn't get port for new debug process.")
  2955. finally:
  2956. dispatcher.close()
  2957. else:
  2958. try:
  2959. pydev_monkey.patch_new_process_functions_with_warning()
  2960. except:
  2961. pydev_log.exception("Error patching process functions.")
  2962. # Only do this patching if we're not running with multiprocess turned on.
  2963. if f.find("dev_appserver.py") != -1:
  2964. if os.path.basename(f).startswith("dev_appserver.py"):
  2965. appserver_dir = os.path.dirname(f)
  2966. version_file = os.path.join(appserver_dir, "VERSION")
  2967. if os.path.exists(version_file):
  2968. try:
  2969. stream = open(version_file, "r")
  2970. try:
  2971. for line in stream.read().splitlines():
  2972. line = line.strip()
  2973. if line.startswith("release:"):
  2974. line = line[8:].strip()
  2975. version = line.replace('"', "")
  2976. version = version.split(".")
  2977. if int(version[0]) > 1:
  2978. fix_app_engine_debug = True
  2979. elif int(version[0]) == 1:
  2980. if int(version[1]) >= 7:
  2981. # Only fix from 1.7 onwards
  2982. fix_app_engine_debug = True
  2983. break
  2984. finally:
  2985. stream.close()
  2986. except:
  2987. pydev_log.exception()
  2988. try:
  2989. # In the default run (i.e.: run directly on debug mode), we try to patch stackless as soon as possible
  2990. # on a run where we have a remote debug, we may have to be more careful because patching stackless means
  2991. # that if the user already had a stackless.set_schedule_callback installed, he'd loose it and would need
  2992. # to call it again (because stackless provides no way of getting the last function which was registered
  2993. # in set_schedule_callback).
  2994. #
  2995. # So, ideally, if there's an application using stackless and the application wants to use the remote debugger
  2996. # and benefit from stackless debugging, the application itself must call:
  2997. #
  2998. # import pydevd_stackless
  2999. # pydevd_stackless.patch_stackless()
  3000. #
  3001. # itself to be able to benefit from seeing the tasklets created before the remote debugger is attached.
  3002. from _pydevd_bundle import pydevd_stackless
  3003. pydevd_stackless.patch_stackless()
  3004. except:
  3005. # It's ok not having stackless there...
  3006. try:
  3007. if hasattr(sys, "exc_clear"):
  3008. sys.exc_clear() # the exception information should be cleaned in Python 2
  3009. except:
  3010. pass
  3011. is_module = setup["module"]
  3012. if not setup["skip-notify-stdin"]:
  3013. patch_stdin()
  3014. if setup[pydevd_constants.ARGUMENT_JSON_PROTOCOL]:
  3015. PyDevdAPI().set_protocol(debugger, 0, JSON_PROTOCOL)
  3016. elif setup[pydevd_constants.ARGUMENT_HTTP_JSON_PROTOCOL]:
  3017. PyDevdAPI().set_protocol(debugger, 0, HTTP_JSON_PROTOCOL)
  3018. elif setup[pydevd_constants.ARGUMENT_HTTP_PROTOCOL]:
  3019. PyDevdAPI().set_protocol(debugger, 0, pydevd_constants.HTTP_PROTOCOL)
  3020. elif setup[pydevd_constants.ARGUMENT_QUOTED_LINE_PROTOCOL]:
  3021. PyDevdAPI().set_protocol(debugger, 0, pydevd_constants.QUOTED_LINE_PROTOCOL)
  3022. access_token = setup["access-token"]
  3023. if access_token:
  3024. debugger.authentication.access_token = access_token
  3025. client_access_token = setup["client-access-token"]
  3026. if client_access_token:
  3027. debugger.authentication.client_access_token = client_access_token
  3028. if fix_app_engine_debug:
  3029. sys.stderr.write("pydev debugger: google app engine integration enabled\n")
  3030. curr_dir = os.path.dirname(__file__)
  3031. app_engine_startup_file = os.path.join(curr_dir, "pydev_app_engine_debug_startup.py")
  3032. sys.argv.insert(1, "--python_startup_script=" + app_engine_startup_file)
  3033. import json
  3034. setup["pydevd"] = __file__
  3035. sys.argv.insert(
  3036. 2,
  3037. "--python_startup_args=%s" % json.dumps(setup),
  3038. )
  3039. sys.argv.insert(3, "--automatic_restart=no")
  3040. sys.argv.insert(4, "--max_module_instances=1")
  3041. # Run the dev_appserver
  3042. debugger.run(setup["file"], None, None, is_module, set_trace=False)
  3043. else:
  3044. if setup["save-threading"]:
  3045. debugger.thread_analyser = ThreadingLogger()
  3046. if setup["save-asyncio"]:
  3047. debugger.asyncio_analyser = AsyncioLogger()
  3048. apply_debugger_options(setup)
  3049. try:
  3050. debugger.connect(host, port)
  3051. except:
  3052. sys.stderr.write("Could not connect to %s: %s\n" % (host, port))
  3053. pydev_log.exception()
  3054. sys.exit(1)
  3055. globals = debugger.run(setup["file"], None, None, is_module)
  3056. if setup["cmd-line"]:
  3057. debugger.wait_for_commands(globals)
  3058. try:
  3059. # Remove the entry we added: it should no longer be needed as
  3060. # what we need should've been imported already
  3061. if sys.path[:1] == [this_dir]:
  3062. sys.path.remove(this_dir)
  3063. except Exception:
  3064. pass
  3065. if __name__ == "__main__":
  3066. main()