Debian Codegraph @

tools/rpdb2.py

raw symbols SCIP
1 #! /usr/bin/env python3
2
3 """
4 rpdb2.py - version 2.4.8
5
6 A remote Python debugger for CPython
7
8 Copyright (C) 2005-2009 Nir Aides
9
10 This program is free software; you can redistribute it and/or modify it
11 under the terms of the GNU General Public License as published by the
12 Free Software Foundation; either version 2 of the License, or any later
13 version.
14
15 This program is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
18 See the GNU General Public License for more details.
19
20 You should have received a copy of the GNU General Public License along
21 with this program; if not, write to the Free Software Foundation, Inc.,
22 51 Franklin Street, Fifth Floor, Boston, MA 02111-1307 USA
23 """
24
25 COPYRIGHT_NOTICE = """Copyright (C) 2005-2009 Nir Aides"""
26
27 CREDITS_NOTICE = """Work on version 2.4.8 was sponsored by Investortools, Inc."""
28
29 LICENSE_NOTICE = """
30 This program is free software; you can redistribute it and/or modify it
31 under the terms of the GNU General Public License as published by the
32 Free Software Foundation; either version 2 of the License, or any later
33 version.
34
35 This program is distributed in the hope that it will be useful,
36 but WITHOUT ANY WARRANTY; without even the implied warranty of
37 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
38 See the GNU General Public License for more details.
39
40 A copy of the GPL with the precise terms and conditions for
41 copying, distribution and modification follow:
42 """
43
44 COPY_OF_THE_GPL_LICENSE = """
45 TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
46
47 0.
48 This License applies to any program or other work which contains a notice
49 placed by the copyright holder saying it may be distributed under the terms
50 of this General Public License. The "Program", below, refers to any such
51 program or work, and a "work based on the Program" means either the Program
52 or any derivative work under copyright law: that is to say, a work containing
53 the Program or a portion of it, either verbatim or with modifications and/or
54 translated into another language. (Hereinafter, translation is included
55 without limitation in the term "modification".) Each licensee is addressed
56 as "you".
57
58 Activities other than copying, distribution and modification are not covered
59 by this License; they are outside its scope. The act of running the Program
60 is not restricted, and the output from the Program is covered only if its
61 contents constitute a work based on the Program (independent of having been
62 made by running the Program). Whether that is true depends on what the
63 Program does.
64
65 1.
66 You may copy and distribute verbatim copies of the Program's source code as
67 you receive it, in any medium, provided that you conspicuously and
68 appropriately publish on each copy an appropriate copyright notice and
69 disclaimer of warranty; keep intact all the notices that refer to this
70 License and to the absence of any warranty; and give any other recipients of
71 the Program a copy of this License along with the Program.
72
73 You may charge a fee for the physical act of transferring a copy, and you
74 may at your option offer warranty protection in exchange for a fee.
75
76 2.
77 You may modify your copy or copies of the Program or any portion of it, thus
78 forming a work based on the Program, and copy and distribute such modifications
79 or work under the terms of Section 1 above, provided that you also meet all
80 of these conditions:
81
82 a) You must cause the modified files to carry prominent notices stating
83 that you changed the files and the date of any change.
84
85 b) You must cause any work that you distribute or publish, that in whole
86 or in part contains or is derived from the Program or any part thereof,
87 to be licensed as a whole at no charge to all third parties under the
88 terms of this License.
89
90 c) If the modified program normally reads commands interactively when
91 run, you must cause it, when started running for such interactive use in
92 the most ordinary way, to print or display an announcement including an
93 appropriate copyright notice and a notice that there is no warranty (or
94 else, saying that you provide a warranty) and that users may redistribute
95 the program under these conditions, and telling the user how to view a
96 copy of this License. (Exception: if the Program itself is interactive
97 but does not normally print such an announcement, your work based on the
98 Program is not required to print an announcement.)
99
100 These requirements apply to the modified work as a whole. If identifiable
101 sections of that work are not derived from the Program, and can be reasonably
102 considered independent and separate works in themselves, then this License,
103 and its terms, do not apply to those sections when you distribute them as
104 separate works. But when you distribute the same sections as part of a whole
105 which is a work based on the Program, the distribution of the whole must be
106 on the terms of this License, whose permissions for other licensees extend to
107 the entire whole, and thus to each and every part regardless of who wrote it.
108
109 Thus, it is not the intent of this section to claim rights or contest your
110 rights to work written entirely by you; rather, the intent is to exercise the
111 right to control the distribution of derivative or collective works based on
112 the Program.
113
114 In addition, mere aggregation of another work not based on the Program with
115 the Program (or with a work based on the Program) on a volume of a storage or
116 distribution medium does not bring the other work under the scope of this
117 License.
118
119 3. You may copy and distribute the Program (or a work based on it, under
120 Section 2) in object code or executable form under the terms of Sections 1
121 and 2 above provided that you also do one of the following:
122
123 a) Accompany it with the complete corresponding machine-readable source
124 code, which must be distributed under the terms of Sections 1 and 2 above
125 on a medium customarily used for software interchange; or,
126
127 b) Accompany it with a written offer, valid for at least three years, to
128 give any third party, for a charge no more than your cost of physically
129 performing source distribution, a complete machine-readable copy of the
130 corresponding source code, to be distributed under the terms of Sections
131 1 and 2 above on a medium customarily used for software interchange; or,
132
133 c) Accompany it with the information you received as to the offer to
134 distribute corresponding source code. (This alternative is allowed only
135 for noncommercial distribution and only if you received the program in
136 object code or executable form with such an offer, in accord with
137 Subsection b above.)
138
139 The source code for a work means the preferred form of the work for making
140 modifications to it. For an executable work, complete source code means all
141 the source code for all modules it contains, plus any associated interface
142 definition files, plus the scripts used to control compilation and
143 installation of the executable. However, as a special exception, the source
144 code distributed need not include anything that is normally distributed (in
145 either source or binary form) with the major components (compiler, kernel,
146 and so on) of the operating system on which the executable runs, unless that
147 component itself accompanies the executable.
148
149 If distribution of executable or object code is made by offering access to
150 copy from a designated place, then offering equivalent access to copy the
151 source code from the same place counts as distribution of the source code,
152 even though third parties are not compelled to copy the source along with
153 the object code.
154
155 4. You may not copy, modify, sublicense, or distribute the Program except as
156 expressly provided under this License. Any attempt otherwise to copy, modify,
157 sublicense or distribute the Program is void, and will automatically
158 terminate your rights under this License. However, parties who have received
159 copies, or rights, from you under this License will not have their licenses
160 terminated so long as such parties remain in full compliance.
161
162 5. You are not required to accept this License, since you have not signed it.
163 However, nothing else grants you permission to modify or distribute the
164 Program or its derivative works. These actions are prohibited by law if you
165 do not accept this License. Therefore, by modifying or distributing the
166 Program (or any work based on the Program), you indicate your acceptance of
167 this License to do so, and all its terms and conditions for copying,
168 distributing or modifying the Program or works based on it.
169
170 6. Each time you redistribute the Program (or any work based on the Program),
171 the recipient automatically receives a license from the original licensor to
172 copy, distribute or modify the Program subject to these terms and conditions.
173 You may not impose any further restrictions on the recipients' exercise of
174 the rights granted herein. You are not responsible for enforcing compliance
175 by third parties to this License.
176
177 7. If, as a consequence of a court judgment or allegation of patent
178 infringement or for any other reason (not limited to patent issues),
179 conditions are imposed on you (whether by court order, agreement or otherwise)
180 that contradict the conditions of this License, they do not excuse you from
181 the conditions of this License. If you cannot distribute so as to satisfy
182 simultaneously your obligations under this License and any other pertinent
183 obligations, then as a consequence you may not distribute the Program at all.
184 For example, if a patent license would not permit royalty-free redistribution
185 of the Program by all those who receive copies directly or indirectly through
186 you, then the only way you could satisfy both it and this License would be to
187 refrain entirely from distribution of the Program.
188
189 If any portion of this section is held invalid or unenforceable under any
190 particular circumstance, the balance of the section is intended to apply and
191 the section as a whole is intended to apply in other circumstances.
192
193 It is not the purpose of this section to induce you to infringe any patents
194 or other property right claims or to contest validity of any such claims;
195 this section has the sole purpose of protecting the integrity of the free
196 software distribution system, which is implemented by public license
197 practices. Many people have made generous contributions to the wide range of
198 software distributed through that system in reliance on consistent
199 application of that system; it is up to the author/donor to decide if he or
200 she is willing to distribute software through any other system and a licensee
201 cannot impose that choice.
202
203 This section is intended to make thoroughly clear what is believed to be a
204 consequence of the rest of this License.
205
206 8. If the distribution and/or use of the Program is restricted in certain
207 countries either by patents or by copyrighted interfaces, the original
208 copyright holder who places the Program under this License may add an
209 explicit geographical distribution limitation excluding those countries,
210 so that distribution is permitted only in or among countries not thus
211 excluded. In such case, this License incorporates the limitation as if
212 written in the body of this License.
213
214 9. The Free Software Foundation may publish revised and/or new versions of
215 the General Public License from time to time. Such new versions will be
216 similar in spirit to the present version, but may differ in detail to
217 address new problems or concerns.
218
219 Each version is given a distinguishing version number. If the Program
220 specifies a version number of this License which applies to it and
221 "any later version", you have the option of following the terms and
222 conditions either of that version or of any later version published by the
223 Free Software Foundation. If the Program does not specify a version number
224 of this License, you may choose any version ever published by the
225 Free Software Foundation.
226
227 10. If you wish to incorporate parts of the Program into other free programs
228 whose distribution conditions are different, write to the author to ask for
229 permission. For software which is copyrighted by the Free Software
230 Foundation, write to the Free Software Foundation; we sometimes make
231 exceptions for this. Our decision will be guided by the two goals of
232 preserving the free status of all derivatives of our free software and of
233 promoting the sharing and reuse of software generally.
234
235 NO WARRANTY
236
237 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR
238 THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE
239 STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE
240 PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED,
241 INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
242 AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND
243 PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE,
244 YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
245
246 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
247 WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
248 REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
249 INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
250 OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO
251 LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR
252 THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
253 PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
254 POSSIBILITY OF SUCH DAMAGES.
255
256 END OF TERMS AND CONDITIONS
257 """
258
259
260
261 if '.' in __name__:
262 raise ImportError('rpdb2 must not be imported as part of a package!')
263
264
265
266 import subprocess
267 import threading
268 import traceback
269 import zipimport
270 import tempfile
271 import __main__
272 import platform
273 import operator
274 import weakref
275 import os.path
276 import zipfile
277 import pickle
278 import socket
279 import getopt
280 import string
281 import random
282 import base64
283 import atexit
284 import locale
285 import codecs
286 import signal
287 import errno
288 import time
289 import copy
290 import hmac
291 import stat
292 import zlib
293 import sys
294 import cmd
295 import imp
296 import os
297 import re
298
299 try:
300 import hashlib
301 _md5 = hashlib.md5
302 except:
303 import md5
304 _md5 = md5
305
306 try:
307 import compiler
308 import sets
309 except:
310 pass
311
312 try:
313 import popen2
314 except:
315 pass
316
317 try:
318 from Crypto.Cipher import DES
319 except ImportError:
320 pass
321
322 #
323 # Pre-Import needed by my_abspath1
324 #
325 try:
326 from nt import _getfullpathname
327 except ImportError:
328 pass
329
330 try:
331 import SimpleXMLRPCServer
332 import xmlrpclib
333 import SocketServer
334 import commands
335 import copy_reg
336 import httplib
337 import thread
338
339 except:
340 #
341 # The above modules were renamed in Python 3 so try to import them 'as'
342 #
343 import xmlrpc.server as SimpleXMLRPCServer
344 import xmlrpc.client as xmlrpclib
345 import socketserver as SocketServer
346 import subprocess as commands
347 import copyreg as copy_reg
348 import http.client as httplib
349 import _thread as thread
350
351 #
352 # Needed in py3k path.
353 #
354 import numbers
355
356
357
358 #
359 #-------------------------------- Design Notes -------------------------------
360 #
361
362 """
363 Design:
364
365 RPDB2 divides the world into two main parts: debugger and debuggee.
366 The debuggee is the script that needs to be debugged.
367 The debugger is another script that attaches to the debuggee for the
368 purpose of debugging.
369
370 Thus RPDB2 includes two main components: The debuggee-server that runs
371 in the debuggee and the session-manager that runs in the debugger.
372
373 The session manager and the debuggee-server communicate via XML-RPC.
374
375 The main classes are: CSessionManager and CDebuggeeServer
376 """
377
378
379
380 #
381 #--------------------------------- Export functions ------------------------
382 #
383
384
385
386 TIMEOUT_FIVE_MINUTES = 5 * 60.0
387
388
389
390 def start_embedded_debugger(
391 _rpdb2_pwd,
392 fAllowUnencrypted = True,
393 fAllowRemote = False,
394 timeout = TIMEOUT_FIVE_MINUTES,
395 source_provider = None,
396 fDebug = False,
397 depth = 0
398 ):
399
400 """
401 Use 'start_embedded_debugger' to invoke the debugger engine in embedded
402 scripts. put the following line as the first line in your script:
403
404 import rpdb2; rpdb2.start_embedded_debugger(<some-password-string>)
405
406 This will cause the script to freeze until a debugger console attaches.
407
408 _rpdb2_pwd - The password that governs security of client/server communication.
409
410 fAllowUnencrypted - Allow unencrypted communications. Communication will
411 be authenticated but encrypted only if possible.
412
413 fAllowRemote - Allow debugger consoles from remote machines to connect.
414
415 timeout - Seconds to wait for attachment before giving up. Once the
416 timeout period expires, the debuggee will resume execution.
417 If None, never give up. If 0, do not wait at all.
418
419 source_provider - When script source is not available on file system it is
420 possible to specify a function that receives a "filename" and returns
421 its source. If filename specifies a file that does not fall under
422 the jurisdiction of this function it should raise IOError. If this
423 function is responsible for the specified file but the source is
424 not available it should raise IOError(SOURCE_NOT_AVAILABLE). You can
425 study the way source_provider_blender() works. Note that a misbehaving
426 function can break the debugger.
427
428 fDebug - debug output.
429
430 depth - Depth of the frame in which the debugger should be started. This
431 defaults to '0' so the top of stack will be in the code where
432 start_embedded_debugger is called.
433
434 IMPORTNAT SECURITY NOTE:
435 USING A HARDCODED PASSWORD MAY BE UNSECURE SINCE ANYONE WITH READ
436 PERMISSION TO THE SCRIPT WILL BE ABLE TO READ THE PASSWORD AND CONNECT TO
437 THE DEBUGGER AND DO WHATEVER THEY WISH VIA THE 'EXEC' DEBUGGER COMMAND.
438
439 It is safer to use: start_embedded_debugger_interactive_password()
440 """
441
442 return __start_embedded_debugger(
443 _rpdb2_pwd,
444 fAllowUnencrypted,
445 fAllowRemote,
446 timeout,
447 source_provider,
448 fDebug,
449 depth + 2
450 )
451
452
453
454 def start_embedded_debugger_interactive_password(
455 fAllowUnencrypted = True,
456 fAllowRemote = False,
457 timeout = TIMEOUT_FIVE_MINUTES,
458 source_provider = None,
459 fDebug = False,
460 stdin = sys.stdin,
461 stdout = sys.stdout,
462 depth = 0
463 ):
464
465 if g_server is not None:
466 return
467
468 while True:
469 if stdout is not None:
470 stdout.write('Please type password:')
471
472 _rpdb2_pwd = stdin.readline().rstrip('\n')
473 _rpdb2_pwd = as_unicode(_rpdb2_pwd, detect_encoding(stdin), fstrict = True)
474
475 try:
476 return __start_embedded_debugger(
477 _rpdb2_pwd,
478 fAllowUnencrypted,
479 fAllowRemote,
480 timeout,
481 source_provider,
482 fDebug,
483 depth + 2
484 )
485
486 except BadArgument:
487 stdout.write(STR_PASSWORD_BAD)
488
489
490
491 def settrace():
492 """
493 Trace threads that were created with thread.start_new_thread()
494 To trace, call this function from the thread target function.
495
496 NOTE: The main thread and any threads created with the threading module
497 are automatically traced, and there is no need to invoke this function
498 for them.
499
500 Note: This call does not pause the script.
501 """
502
503 return __settrace()
504
505
506
507 def setbreak(depth = 0):
508 """
509 Pause the script for inspection at next script statement.
510 """
511
512 return __setbreak(depth + 2)
513
514
515
516 def set_temp_breakpoint(path, scopename = '', lineno = 1):
517 """
518 Set a temporary breakpoint in a file. path must be an absolute path.
519 scopename can either be an empty string or a fully qualified scope name
520 (For example u'g_debugger.m_bp_manager.set_temp_breakpoint'). lineno is
521 either relative to file start or to scope start.
522
523 To set a temporary breakpoint to hit when a file is first
524 imported or exec-uted call set_temp_breakpoint(path)
525
526 This function may throw a varaiety of exceptions.
527 """
528
529 path = as_unicode(path, fstrict = True)
530 scopename = as_unicode(scopename, fstrict = True)
531
532 return __set_temp_breakpoint(path, scopename, lineno)
533
534
535
536 #
537 #----------------------------------- Interfaces ------------------------------
538 #
539
540
541
542 VERSION = (2, 4, 8, 0, 'Tychod')
543 RPDB_TITLE = "RPDB 2.4.8 - Tychod"
544 RPDB_VERSION = "RPDB_2_4_8"
545 RPDB_COMPATIBILITY_VERSION = "RPDB_2_4_0"
546
547
548
549 def get_version():
550 return RPDB_VERSION
551
552
553
554 def get_interface_compatibility_version():
555 return RPDB_COMPATIBILITY_VERSION
556
557
558
559 class CSimpleSessionManager:
560 """
561 This is a wrapper class that simplifies launching and controlling of a
562 debuggee from within another program. For example, an IDE that launches
563 a script for debugging puposes can use this class to launch, debug and
564 stop a script.
565 """
566
567 def __init__(self, fAllowUnencrypted = True):
568 self.__sm = CSessionManagerInternal(
569 _rpdb2_pwd = None,
570 fAllowUnencrypted = fAllowUnencrypted,
571 fAllowRemote = False,
572 host = LOCALHOST
573 )
574
575 self.m_fRunning = False
576
577 event_type_dict = {CEventUnhandledException: {}}
578 self.__sm.register_callback(self.__unhandled_exception, event_type_dict, fSingleUse = False)
579
580 event_type_dict = {CEventState: {}}
581 self.__sm.register_callback(self.__state_calback, event_type_dict, fSingleUse = False)
582
583 event_type_dict = {CEventExit: {}}
584 self.__sm.register_callback(self.__termination_callback, event_type_dict, fSingleUse = False)
585
586
587 def shutdown(self):
588 self.__sm.shutdown()
589
590
591 def launch(self, fchdir, command_line, encoding = 'utf-8', fload_breakpoints = False):
592 command_line = as_unicode(command_line, encoding, fstrict = True)
593
594 self.m_fRunning = False
595
596 self.__sm.launch(fchdir, command_line, fload_breakpoints)
597
598
599 def request_go(self):
600 self.__sm.request_go()
601
602
603 def detach(self):
604 self.__sm.detach()
605
606
607 def stop_debuggee(self):
608 self.__sm.stop_debuggee()
609
610
611 def get_session_manager(self):
612 return self.__sm
613
614
615 def prepare_attach(self):
616 """
617 Use this method to attach a debugger to the debuggee after an
618 exception is caught.
619 """
620
621 _rpdb2_pwd = self.__sm.get_password()
622
623 si = self.__sm.get_server_info()
624 rid = si.m_rid
625
626 if os.name == 'posix':
627 #
628 # On posix systems the password is set at the debuggee via
629 # a special temporary file.
630 #
631 create_pwd_file(rid, _rpdb2_pwd)
632 _rpdb2_pwd = None
633
634 return (rid, _rpdb2_pwd)
635
636
637 #
638 # Override these callbacks to react to the related events.
639 #
640
641 def unhandled_exception_callback(self):
642 _print('unhandled_exception_callback')
643 self.request_go()
644
645
646 def script_paused(self):
647 _print('script_paused')
648 self.request_go()
649
650
651 def script_terminated_callback(self):
652 _print('script_terminated_callback')
653
654
655 #
656 # Private Methods
657 #
658
659 def __unhandled_exception(self, event):
660 self.unhandled_exception_callback()
661
662
663 def __termination_callback(self, event):
664 self.script_terminated_callback()
665
666
667 def __state_calback(self, event):
668 """
669 Handle state change notifications from the debugge.
670 """
671
672 if event.m_state != STATE_BROKEN:
673 return
674
675 if not self.m_fRunning:
676 #
677 # First break comes immediately after launch.
678 #
679 print_debug('Simple session manager continues on first break.')
680 self.m_fRunning = True
681 self.request_go()
682 return
683
684 if self.__sm.is_unhandled_exception():
685 return
686
687 sl = self.__sm.get_stack(tid_list = [], fAll = False)
688 if len(sl) == 0:
689 self.request_go()
690 return
691
692 st = sl[0]
693 s = st.get(DICT_KEY_STACK, [])
694 if len(s) == 0:
695 self.request_go()
696 return
697
698 e = s[-1]
699
700 function_name = e[2]
701 filename = os.path.basename(e[0])
702
703 if filename != DEBUGGER_FILENAME:
704 #
705 # This is a user breakpoint (e.g. rpdb2.setbreak())
706 #
707 self.script_paused()
708 return
709
710 #
711 # This is the setbreak() before a fork, exec or program
712 # termination.
713 #
714 self.request_go()
715 return
716
717
718
719 class CSessionManager:
720 """
721 Interface to the session manager.
722 This is the interface through which the debugger controls and
723 communicates with the debuggee.
724
725 Accepted strings are either utf-8 or Unicode unless specified otherwise.
726 Returned strings are Unicode (also when embedded in data structures).
727
728 You can study the way it is used in StartClient()
729 """
730
731 def __init__(self, _rpdb2_pwd, fAllowUnencrypted, fAllowRemote, host):
732 if _rpdb2_pwd != None:
733 assert(is_valid_pwd(_rpdb2_pwd))
734 _rpdb2_pwd = as_unicode(_rpdb2_pwd, fstrict = True)
735
736 self.__smi = CSessionManagerInternal(
737 _rpdb2_pwd,
738 fAllowUnencrypted,
739 fAllowRemote,
740 host
741 )
742
743
744 def shutdown(self):
745 return self.__smi.shutdown()
746
747
748 def set_printer(self, printer):
749 """
750 'printer' is a function that takes one argument and prints it.
751 You can study CConsoleInternal.printer() as example for use
752 and rational.
753 """
754
755 return self.__smi.set_printer(printer)
756
757
758 def report_exception(self, type, value, tb):
759 """
760 Sends exception information to the printer.
761 """
762
763 return self.__smi.report_exception(type, value, tb)
764
765
766 def register_callback(self, callback, event_type_dict, fSingleUse):
767 """
768 Receive events from the session manager.
769 The session manager communicates it state mainly by firing events.
770 You can study CConsoleInternal.__init__() as example for use.
771 For details see CEventDispatcher.register_callback()
772 """
773
774 return self.__smi.register_callback(
775 callback,
776 event_type_dict,
777 fSingleUse
778 )
779
780
781 def remove_callback(self, callback):
782 return self.__smi.remove_callback(callback)
783
784
785 def refresh(self):
786 """
787 Fire again all relevant events needed to establish the current state.
788 """
789
790 return self.__smi.refresh()
791
792
793 def launch(self, fchdir, command_line, encoding = 'utf-8', fload_breakpoints = True):
794 """
795 Launch debuggee in a new process and attach.
796 fchdir - Change current directory to that of the debuggee.
797 command_line - command line arguments pass to the script as a string.
798 fload_breakpoints - Load breakpoints of last session.
799
800 if command line is not a unicode string it will be decoded into unicode
801 with the given encoding
802 """
803
804 command_line = as_unicode(command_line, encoding, fstrict = True)
805
806 return self.__smi.launch(fchdir, command_line, fload_breakpoints)
807
808
809 def restart(self):
810 """
811 Restart debug session with same command_line and fchdir arguments
812 which were used in last launch.
813 """
814
815 return self.__smi.restart()
816
817
818 def get_launch_args(self):
819 """
820 Return command_line and fchdir arguments which were used in last
821 launch as (last_fchdir, last_command_line).
822 Returns (None, None) if there is no info.
823 """
824
825 return self.__smi.get_launch_args()
826
827
828 def attach(self, key, name = None, encoding = 'utf-8'):
829 """
830 Attach to a debuggee (establish communication with the debuggee-server)
831 key - a string specifying part of the filename or PID of the debuggee.
832
833 if key is not a unicode string it will be decoded into unicode
834 with the given encoding
835 """
836
837 key = as_unicode(key, encoding, fstrict = True)
838
839 return self.__smi.attach(key, name)
840
841
842 def detach(self):
843 """
844 Let the debuggee go...
845 """
846
847 return self.__smi.detach()
848
849
850 def request_break(self):
851 return self.__smi.request_break()
852
853
854 def request_go(self):
855 return self.__smi.request_go()
856
857
858 def request_go_breakpoint(self, filename, scope, lineno):
859 """
860 Go (run) until the specified location is reached.
861 """
862
863 filename = as_unicode(filename, fstrict = True)
864 scope = as_unicode(scope, fstrict = True)
865
866 return self.__smi.request_go_breakpoint(filename, scope, lineno)
867
868
869 def request_step(self):
870 """
871 Go until the next line of code is reached.
872 """
873
874 return self.__smi.request_step()
875
876
877 def request_next(self):
878 """
879 Go until the next line of code in the same scope is reached.
880 """
881
882 return self.__smi.request_next()
883
884
885 def request_return(self):
886 """
887 Go until end of scope is reached.
888 """
889
890 return self.__smi.request_return()
891
892
893 def request_jump(self, lineno):
894 """
895 Jump to the specified line number in the same scope.
896 """
897
898 return self.__smi.request_jump(lineno)
899
900
901 #
902 # REVIEW: should return breakpoint ID
903 #
904 def set_breakpoint(self, filename, scope, lineno, fEnabled, expr):
905 """
906 Set a breakpoint.
907
908 filename - (Optional) can be either a file name or a module name,
909 full path, relative path or no path at all.
910 If filname is None or '', then the current module is
911 used.
912 scope - (Optional) Specifies a dot delimited scope for the
913 breakpoint, such as: foo or myClass.foo
914 lineno - (Optional) Specify a line within the selected file or
915 if a scope is specified, an zero-based offset from the
916 start of the scope.
917 expr - (Optional) A Python expression that will be evaluated
918 locally when the breakpoint is hit. The break will
919 occur only if the expression evaluates to true.
920 """
921
922 filename = as_unicode(filename, fstrict = True)
923 scope = as_unicode(scope, fstrict = True)
924 expr = as_unicode(expr, fstrict = True)
925
926 return self.__smi.set_breakpoint(
927 filename,
928 scope,
929 lineno,
930 fEnabled,
931 expr
932 )
933
934
935 def disable_breakpoint(self, id_list, fAll):
936 """
937 Disable breakpoints
938
939 id_list - (Optional) A list of breakpoint ids.
940 fAll - disable all breakpoints regardless of id_list.
941 """
942
943 return self.__smi.disable_breakpoint(id_list, fAll)
944
945
946 def enable_breakpoint(self, id_list, fAll):
947 """
948 Enable breakpoints
949
950 id_list - (Optional) A list of breakpoint ids.
951 fAll - disable all breakpoints regardless of id_list.
952 """
953
954 return self.__smi.enable_breakpoint(id_list, fAll)
955
956
957 def delete_breakpoint(self, id_list, fAll):
958 """
959 Delete breakpoints
960
961 id_list - (Optional) A list of breakpoint ids.
962 fAll - disable all breakpoints regardless of id_list.
963 """
964
965 return self.__smi.delete_breakpoint(id_list, fAll)
966
967
968 def get_breakpoints(self):
969 """
970 Return breakpoints in a dictionary of id keys to CBreakPoint values
971 """
972
973 return self.__smi.get_breakpoints()
974
975
976 def save_breakpoints(self, _filename = ''):
977 """
978 Save breakpoints to file, locally (on the client side)
979 """
980
981 return self.__smi.save_breakpoints(_filename)
982
983
984 def load_breakpoints(self, _filename = ''):
985 """
986 Load breakpoints from file, locally (on the client side)
987 """
988
989 return self.__smi.load_breakpoints(_filename)
990
991
992 def set_trap_unhandled_exceptions(self, ftrap):
993 """
994 Set trap-unhandled-exceptions mode.
995 ftrap with a value of False means unhandled exceptions will be ignored.
996 The session manager default is True.
997 """
998
999 return self.__smi.set_trap_unhandled_exceptions(ftrap)
1000
1001
1002 def get_trap_unhandled_exceptions(self):
1003 """
1004 Get trap-unhandled-exceptions mode.
1005 """
1006
1007 return self.__smi.get_trap_unhandled_exceptions()
1008
1009
1010 def set_fork_mode(self, ffork_into_child, ffork_auto):
1011 """
1012 Determine how to handle os.fork().
1013
1014 ffork_into_child - True|False - If True, the debugger will debug the
1015 child process after a fork, otherwise the debugger will continue
1016 to debug the parent process.
1017
1018 ffork_auto - True|False - If True, the debugger will not pause before
1019 a fork and will automatically make a decision based on the
1020 value of the ffork_into_child flag.
1021 """
1022
1023 return self.__smi.set_fork_mode(ffork_into_child, ffork_auto)
1024
1025
1026 def get_fork_mode(self):
1027 """
1028 Return the fork mode in the form of a (ffork_into_child, ffork_auto)
1029 flags tuple.
1030 """
1031
1032 return self.__smi.get_fork_mode()
1033
1034
1035 def get_stack(self, tid_list, fAll):
1036 return self.__smi.get_stack(tid_list, fAll)
1037
1038
1039 def get_source_file(self, filename, lineno, nlines):
1040 filename = as_unicode(filename, fstrict = True)
1041
1042 return self.__smi.get_source_file(filename, lineno, nlines)
1043
1044
1045 def get_source_lines(self, nlines, fAll):
1046 return self.__smi.get_source_lines(nlines, fAll)
1047
1048
1049 def set_frame_index(self, frame_index):
1050 """
1051 Set frame index. 0 is the current executing frame, and 1, 2, 3,
1052 are deeper into the stack.
1053 """
1054
1055 return self.__smi.set_frame_index(frame_index)
1056
1057
1058 def get_frame_index(self):
1059 """
1060 Get frame index. 0 is the current executing frame, and 1, 2, 3,
1061 are deeper into the stack.
1062 """
1063
1064 return self.__smi.get_frame_index()
1065
1066
1067 def set_analyze(self, fAnalyze):
1068 """
1069 Toggle analyze mode. In analyze mode the stack switches to the
1070 exception stack for examination.
1071 """
1072
1073 return self.__smi.set_analyze(fAnalyze)
1074
1075
1076 def set_host(self, host):
1077 """
1078 Set host to specified host (string) for attaching to debuggies on
1079 specified host. host can be a host name or ip address in string form.
1080 """
1081
1082 return self.__smi.set_host(host)
1083
1084
1085 def get_host(self):
1086 return self.__smi.get_host()
1087
1088
1089 def calc_server_list(self):
1090 """
1091 Calc servers (debuggable scripts) list on specified host.
1092 Returns a tuple of a list and a dictionary.
1093 The list is a list of CServerInfo objects sorted by their age
1094 ordered oldest last.
1095 The dictionary is a dictionary of errors that were encountered
1096 during the building of the list. The dictionary has error (exception)
1097 type as keys and number of occurances as values.
1098 """
1099
1100 return self.__smi.calc_server_list()
1101
1102
1103 def get_server_info(self):
1104 """
1105 Return CServerInfo server info object that corresponds to the
1106 server (debugged script) to which the session manager is
1107 attached.
1108 """
1109
1110 return self.__smi.get_server_info()
1111
1112
1113 def get_namespace(self, nl, filter_level, repr_limit = 128, fFilter = "DEPRECATED"):
1114 """
1115 get_namespace is designed for locals/globals panes that let
1116 the user inspect a namespace tree in GUI debuggers such as Winpdb.
1117 You can study the way it is used in Winpdb.
1118
1119 nl - List of tuples, where each tuple is made of a python expression
1120 as string and a flag that controls whether to "expand" the
1121 value, that is, to return its children as well in case it has
1122 children e.g. lists, dictionaries, etc...
1123
1124 filter_level - 0, 1, or 2. Filter out methods and functions from
1125 classes and objects. (0 - None, 1 - Medium, 2 - Maximum).
1126
1127 repr_limit - Length limit (approximated) to be imposed on repr() of
1128 returned items.
1129
1130 examples of expression lists:
1131
1132 [('x', false), ('y', false)]
1133 [('locals()', true)]
1134 [('a.b.c', false), ('my_object.foo', false), ('another_object', true)]
1135
1136 Return value is a list of dictionaries, where every element
1137 in the list corresponds to an element in the input list 'nl'.
1138
1139 Each dictionary has the following keys and values:
1140 DICT_KEY_EXPR - the original expression string.
1141 DICT_KEY_REPR - A repr of the evaluated value of the expression.
1142 DICT_KEY_IS_VALID - A boolean that indicates if the repr value is
1143 valid for the purpose of re-evaluation.
1144 DICT_KEY_TYPE - A string representing the type of the experession's
1145 evaluated value.
1146 DICT_KEY_N_SUBNODES - If the evaluated value has children like items
1147 in a list or in a dictionary or members of a class,
1148 etc, this key will have their number as value.
1149 DICT_KEY_SUBNODES - If the evaluated value has children and the
1150 "expand" flag was set for this expression, then the
1151 value of this key will be a list of dictionaries as
1152 described below.
1153 DICT_KEY_ERROR - If an error prevented evaluation of this expression
1154 the value of this key will be a repr of the
1155 exception info: repr(sys.exc_info())
1156
1157 Each dictionary for child items has the following keys and values:
1158 DICT_KEY_EXPR - The Python expression that designates this child.
1159 e.g. 'my_list[0]' designates the first child of the
1160 list 'my_list'
1161 DICT_KEY_NAME - a repr of the child name, e.g '0' for the first item
1162 in a list.
1163 DICT_KEY_REPR - A repr of the evaluated value of the expression.
1164 DICT_KEY_IS_VALID - A boolean that indicates if the repr value is
1165 valid for the purpose of re-evaluation.
1166 DICT_KEY_TYPE - A string representing the type of the experession's
1167 evaluated value.
1168 DICT_KEY_N_SUBNODES - If the evaluated value has children like items
1169 in a list or in a dictionary or members of a class,
1170 etc, this key will have their number as value.
1171 """
1172
1173 if fFilter != "DEPRECATED":
1174 filter_level = fFilter
1175
1176 filter_level = int(filter_level)
1177
1178 return self.__smi.get_namespace(nl, filter_level, repr_limit)
1179
1180
1181 #
1182 # REVIEW: remove warning item.
1183 #
1184 def evaluate(self, expr):
1185 """
1186 Evaluate a python expression in the context of the current thread
1187 and frame.
1188
1189 Return value is a tuple (v, w, e) where v is a repr of the evaluated
1190 expression value, w is always '', and e is an error string if an error
1191 occurred.
1192
1193 NOTE: This call might not return since debugged script logic can lead
1194 to tmporary locking or even deadlocking.
1195 """
1196
1197 expr = as_unicode(expr, fstrict = True)
1198
1199 return self.__smi.evaluate(expr)
1200
1201
1202 def execute(self, suite):
1203 """
1204 Execute a python statement in the context of the current thread
1205 and frame.
1206
1207 Return value is a tuple (w, e) where w and e are warning and
1208 error strings (respectively) if an error occurred.
1209
1210 NOTE: This call might not return since debugged script logic can lead
1211 to tmporary locking or even deadlocking.
1212 """
1213
1214 suite = as_unicode(suite, fstrict = True)
1215
1216 return self.__smi.execute(suite)
1217
1218
1219 def complete_expression(self, expr):
1220 """
1221 Return matching completions for expression.
1222 Accepted expressions are of the form a.b.c
1223
1224 Dictionary lookups or functions call are not evaluated. For
1225 example: 'getobject().complete' or 'dict[item].complete' are
1226 not processed.
1227
1228 On the other hand partial expressions and statements are
1229 accepted. For example: 'foo(arg1, arg2.member.complete' will
1230 be accepted and the completion for 'arg2.member.complete' will
1231 be calculated.
1232
1233 Completions are returned as a tuple of two items. The first item
1234 is a prefix to expr and the second item is a list of completions.
1235 For example if expr is 'foo(self.comp' the returned tuple can
1236 be ('foo(self.', ['complete', 'completion', etc...])
1237 """
1238
1239 expr = as_unicode(expr, fstrict = True)
1240
1241 return self.__smi.complete_expression(expr)
1242
1243
1244 def set_encoding(self, encoding, fraw = False):
1245 """
1246 Set the encoding that will be used as source encoding for execute()
1247 evaluate() commands and in strings returned by get_namespace().
1248
1249 The encoding value can be either 'auto' or any encoding accepted by
1250 the codecs module. If 'auto' is specified, the encoding used will be
1251 the source encoding of the active scope, which is utf-8 by default.
1252
1253 The default encoding value is 'auto'.
1254
1255 If fraw is True, strings returned by evaluate() and get_namespace()
1256 will represent non ASCII characters as an escape sequence.
1257 """
1258
1259 return self.__smi.set_encoding(encoding, fraw)
1260
1261
1262 def get_encoding(self):
1263 """
1264 return the (encoding, fraw) tuple.
1265 """
1266 return self.__smi.get_encoding()
1267
1268
1269 def set_synchronicity(self, fsynchronicity):
1270 """
1271 Set the synchronicity mode.
1272
1273 Traditional Python debuggers that use the inspected thread (usually
1274 the main thread) to query or modify the script name-space have to
1275 wait until the script hits a break-point. Synchronicity allows the
1276 debugger to query and modify the script name-space even if its
1277 threads are still running or blocked in C library code by using
1278 special worker threads. In some rare cases querying or modifying data
1279 in synchronicity can crash the script. For example in some Linux
1280 builds of wxPython querying the state of wx objects from a thread
1281 other than the GUI thread can crash the script. If this happens or
1282 if you want to restrict these operations to the inspected thread,
1283 turn synchronicity off.
1284
1285 On the other hand when synchronicity is off it is possible to
1286 accidentally deadlock or block indefinitely the script threads by
1287 querying or modifying particular data structures.
1288
1289 The default is on (True).
1290 """
1291
1292 return self.__smi.set_synchronicity(fsynchronicity)
1293
1294
1295 def get_synchronicity(self):
1296 return self.__smi.get_synchronicity()
1297
1298
1299 def get_state(self):
1300 """
1301 Get the session manager state. Return one of the STATE_* constants
1302 defined below, for example STATE_DETACHED, STATE_BROKEN, etc...
1303 """
1304
1305 return self.__smi.get_state()
1306
1307
1308 #
1309 # REVIEW: Improve data strucutre.
1310 #
1311 def get_thread_list(self):
1312 return self.__smi.get_thread_list()
1313
1314
1315 def set_thread(self, tid):
1316 """
1317 Set the focused thread to the soecified thread.
1318 tid - either the OS thread id or the zero based index of the thread
1319 in the thread list returned by get_thread_list().
1320 """
1321
1322 return self.__smi.set_thread(tid)
1323
1324
1325 def set_password(self, _rpdb2_pwd):
1326 """
1327 Set the password that will govern the authentication and encryption
1328 of client-server communication.
1329 """
1330
1331 _rpdb2_pwd = as_unicode(_rpdb2_pwd, fstrict = True)
1332
1333 return self.__smi.set_password(_rpdb2_pwd)
1334
1335
1336 def get_password(self):
1337 """
1338 Get the password that governs the authentication and encryption
1339 of client-server communication.
1340 """
1341
1342 return self.__smi.get_password()
1343
1344
1345 def get_encryption(self):
1346 """
1347 Get the encryption mode. Return True if unencrypted connections are
1348 not allowed. When launching a new debuggee the debuggee will inherit
1349 the encryption mode. The encryption mode can be set via command-line
1350 only.
1351 """
1352
1353 return self.__smi.get_encryption()
1354
1355
1356 def set_remote(self, fAllowRemote):
1357 """
1358 Set the remote-connections mode. if True, connections from remote
1359 machine are allowed. When launching a new debuggee the debuggee will
1360 inherit this mode. This mode is only relevant to the debuggee.
1361 """
1362
1363 return self.__smi.set_remote(fAllowRemote)
1364
1365
1366 def get_remote(self):
1367 """
1368 Get the remote-connections mode. Return True if connections from
1369 remote machine are allowed. When launching a new debuggee the
1370 debuggee will inherit this mode. This mode is only relevant to the
1371 debuggee.
1372 """
1373
1374 return self.__smi.get_remote()
1375
1376
1377 def set_environ(self, envmap):
1378 """
1379 Set the environment variables mapping. This mapping is used
1380 when a new script is launched to modify its environment.
1381
1382 Example for a mapping on Windows: [('Path', '%Path%;c:\\mydir')]
1383 Example for a mapping on Linux: [('PATH', '$PATH:~/mydir')]
1384
1385 The mapping should be a list of tupples where each tupple is
1386 composed of a key and a value. Keys and Values must be either
1387 strings or Unicode strings. Other types will raise the BadArgument
1388 exception.
1389
1390 Invalid arguments will be silently ignored.
1391 """
1392
1393 return self.__smi.set_environ(envmap)
1394
1395
1396 def get_environ(self):
1397 """
1398 Return the current environment mapping.
1399 """
1400
1401 return self.__smi.get_environ()
1402
1403
1404 def stop_debuggee(self):
1405 """
1406 Stop the debuggee immediately.
1407 """
1408
1409 return self.__smi.stop_debuggee()
1410
1411
1412
1413 class CConsole:
1414 """
1415 Interface to a debugger console.
1416 """
1417
1418 def __init__(
1419 self,
1420 session_manager,
1421 stdin = None,
1422 stdout = None,
1423 fSplit = False
1424 ):
1425
1426 """
1427 Constructor of CConsole
1428
1429 session_manager - session manager object.
1430 stdin, stdout - redirection for IO.
1431 fsplit - Set flag to True when Input and Ouput belong to different
1432 panes. For example take a look at Winpdb.
1433 """
1434
1435 self.m_ci = CConsoleInternal(
1436 session_manager,
1437 stdin,
1438 stdout,
1439 fSplit
1440 )
1441
1442
1443 def start(self):
1444 return self.m_ci.start()
1445
1446
1447 def join(self):
1448 """
1449 Wait until the console ends.
1450 """
1451
1452 return self.m_ci.join()
1453
1454
1455 def set_filename(self, filename):
1456 """
1457 Set current filename for the console. The current filename can change
1458 from outside the console when the console is embeded in other
1459 components, for example take a look at Winpdb.
1460 """
1461
1462 filename = as_unicode(filename)
1463
1464 return self.m_ci.set_filename(filename)
1465
1466
1467 def complete(self, text, state):
1468 """
1469 Return the next possible completion for 'text'.
1470 If a command has not been entered, then complete against command list.
1471 Otherwise try to call complete_<command> to get list of completions.
1472 """
1473
1474 text = as_unicode(text)
1475
1476 return self.m_ci.complete(text, state)
1477
1478
1479 def printer(self, text):
1480 text = as_unicode(text)
1481
1482 return self.m_ci.printer(text)
1483
1484
1485
1486 #
1487 # ---------------------------- Exceptions ----------------------------------
1488 #
1489
1490
1491
1492
1493 class CException(Exception):
1494 """
1495 Base exception class for the debugger.
1496 """
1497
1498 def __init__(self, *args):
1499 Exception.__init__(self, *args)
1500
1501
1502
1503 class BadMBCSPath(CException):
1504 """
1505 Raised on Windows systems when the python executable or debugger script
1506 path can not be encoded with the file system code page. This means that
1507 the Windows code page is misconfigured.
1508 """
1509
1510
1511
1512 class NotPythonSource(CException):
1513 """
1514 Raised when an attempt to load non Python source is made.
1515 """
1516
1517
1518
1519 class InvalidScopeName(CException):
1520 """
1521 Invalid scope name.
1522 This exception might be thrown when a request was made to set a breakpoint
1523 to an unknown scope.
1524 """
1525
1526
1527
1528 class BadArgument(CException):
1529 """
1530 Bad Argument.
1531 """
1532
1533
1534
1535 class ThreadNotFound(CException):
1536 """
1537 Thread not found.
1538 """
1539
1540
1541
1542 class NoThreads(CException):
1543 """
1544 No Threads.
1545 """
1546
1547
1548
1549 class ThreadDone(CException):
1550 """
1551 Thread Done.
1552 """
1553
1554
1555
1556 class DebuggerNotBroken(CException):
1557 """
1558 Debugger is not broken.
1559 This exception is thrown when an operation that can only be performed
1560 while the debuggee is broken, is requested while the debuggee is running.
1561 """
1562
1563
1564
1565 class InvalidFrame(CException):
1566 """
1567 Invalid Frame.
1568 This exception is raised if an operation is requested on a stack frame
1569 that does not exist.
1570 """
1571
1572
1573
1574 class NoExceptionFound(CException):
1575 """
1576 No Exception Found.
1577 This exception is raised when exception information is requested, but no
1578 exception is found, or has been thrown.
1579 """
1580
1581
1582
1583 class CConnectionException(CException):
1584 def __init__(self, *args):
1585 CException.__init__(self, *args)
1586
1587
1588
1589 class FirewallBlock(CConnectionException):
1590 """Firewall is blocking socket communication."""
1591
1592
1593
1594 class BadVersion(CConnectionException):
1595 """Bad Version."""
1596 def __init__(self, version):
1597 CConnectionException.__init__(self)
1598
1599 self.m_version = version
1600
1601 def __str__(self):
1602 return repr(self.m_version)
1603
1604
1605
1606 class UnexpectedData(CConnectionException):
1607 """Unexpected data."""
1608
1609
1610
1611 class AlreadyAttached(CConnectionException):
1612 """Already Attached."""
1613
1614
1615
1616 class NotAttached(CConnectionException):
1617 """Not Attached."""
1618
1619
1620
1621 class SpawnUnsupported(CConnectionException):
1622 """Spawn Unsupported."""
1623
1624
1625
1626 class UnknownServer(CConnectionException):
1627 """Unknown Server."""
1628
1629
1630
1631 class CSecurityException(CConnectionException):
1632 def __init__(self, *args):
1633 CConnectionException.__init__(self, *args)
1634
1635
1636
1637 class UnsetPassword(CSecurityException):
1638 """Unset Password."""
1639
1640
1641
1642 class EncryptionNotSupported(CSecurityException):
1643 """Encryption Not Supported."""
1644
1645
1646
1647 class EncryptionExpected(CSecurityException):
1648 """Encryption Expected."""
1649
1650
1651 class DecryptionFailure(CSecurityException):
1652 """Decryption Failure."""
1653
1654
1655
1656 class AuthenticationBadData(CSecurityException):
1657 """Authentication Bad Data."""
1658
1659
1660
1661 class AuthenticationFailure(CSecurityException):
1662 """Authentication Failure."""
1663
1664
1665
1666 class AuthenticationBadIndex(CSecurityException):
1667 """Authentication Bad Index."""
1668 def __init__(self, max_index = 0, anchor = 0):
1669 CSecurityException.__init__(self)
1670
1671 self.m_max_index = max_index
1672 self.m_anchor = anchor
1673
1674 def __str__(self):
1675 return repr((self.m_max_index, self.m_anchor))
1676
1677
1678
1679 #
1680 #----------------- unicode handling for compatibility with py3k ----------------
1681 #
1682
1683
1684
1685 def is_py3k():
1686 return sys.version_info[0] >= 3
1687
1688
1689
1690 def is_unicode(s):
1691 if is_py3k() and type(s) == str:
1692 return True
1693
1694 if type(s) == unicode:
1695 return True
1696
1697 return False
1698
1699
1700
1701 def as_unicode(s, encoding = 'utf-8', fstrict = False):
1702 if is_unicode(s):
1703 return s
1704
1705 if fstrict:
1706 u = s.decode(encoding)
1707 else:
1708 u = s.decode(encoding, 'replace')
1709
1710 return u
1711
1712
1713
1714 def as_string(s, encoding = 'utf-8', fstrict = False):
1715 if is_py3k():
1716 if is_unicode(s):
1717 return s
1718
1719 if fstrict:
1720 e = s.decode(encoding)
1721 else:
1722 e = s.decode(encoding, 'replace')
1723
1724 return e
1725
1726 if not is_unicode(s):
1727 return s
1728
1729 if fstrict:
1730 e = s.encode(encoding)
1731 else:
1732 e = s.encode(encoding, 'replace')
1733
1734 return e
1735
1736
1737
1738 def as_bytes(s, encoding = 'utf-8', fstrict = True):
1739 if not is_unicode(s):
1740 return s
1741
1742 if fstrict:
1743 b = s.encode(encoding)
1744 else:
1745 b = s.encode(encoding, 'replace')
1746
1747 return b
1748
1749
1750
1751 #
1752 #----------------------- Infinite List of Globals ---------------------------
1753 #
1754
1755
1756
1757 #
1758 # According to PEP-8: "Use 4 spaces per indentation level."
1759 #
1760 PYTHON_TAB_WIDTH = 4
1761
1762 GNOME_DEFAULT_TERM = 'gnome-terminal'
1763 NT_DEBUG = 'nt_debug'
1764 SCREEN = 'screen'
1765 MAC = 'mac'
1766 DARWIN = 'darwin'
1767 POSIX = 'posix'
1768
1769 #
1770 # Map between OS type and relevant command to initiate a new OS console.
1771 # entries for other OSs can be added here.
1772 # '%s' serves as a place holder.
1773 #
1774 # Currently there is no difference between 'nt' and NT_DEBUG, since now
1775 # both of them leave the terminal open after termination of debuggee to
1776 # accommodate scenarios of scripts with child processes.
1777 #
1778 osSpawn = {
1779 'nt': 'start "rpdb2 - Version ' + get_version() + ' - Debuggee Console" cmd.exe /K ""%(exec)s" %(options)s"',
1780 NT_DEBUG: 'start "rpdb2 - Version ' + get_version() + ' - Debuggee Console" cmd.exe /K ""%(exec)s" %(options)s"',
1781 POSIX: "%(term)s -e %(shell)s -c '%(exec)s %(options)s; %(shell)s' &",
1782 'Terminal': "Terminal --disable-server -x %(shell)s -c '%(exec)s %(options)s; %(shell)s' &",
1783 GNOME_DEFAULT_TERM: "gnome-terminal -x %(shell)s -c '%(exec)s %(options)s; %(shell)s' &",
1784 MAC: '%(exec)s %(options)s',
1785 DARWIN: '%(exec)s %(options)s',
1786 SCREEN: 'screen -t debuggee_console %(exec)s %(options)s'
1787 }
1788
1789 RPDBTERM = 'RPDBTERM'
1790 COLORTERM = 'COLORTERM'
1791 TERM = 'TERM'
1792 KDE_PREFIX = 'KDE'
1793 GNOME_PREFIX = 'GNOME'
1794
1795 KDE_DEFAULT_TERM_QUERY = "kreadconfig --file kdeglobals --group General --key TerminalApplication --default konsole"
1796 XTERM = 'xterm'
1797 RXVT = 'rxvt'
1798
1799 RPDB_SETTINGS_FOLDER = '.rpdb2_settings'
1800 RPDB_PWD_FOLDER = os.path.join(RPDB_SETTINGS_FOLDER, 'passwords')
1801 RPDB_BPL_FOLDER = os.path.join(RPDB_SETTINGS_FOLDER, 'breakpoints')
1802 RPDB_BPL_FOLDER_NT = 'rpdb2_breakpoints'
1803 MAX_BPL_FILES = 100
1804
1805 EMBEDDED_SYNC_THRESHOLD = 1.0
1806 EMBEDDED_SYNC_TIMEOUT = 5.0
1807
1808 HEARTBEAT_TIMEOUT = 16
1809 IDLE_MAX_RATE = 2.0
1810 PING_TIMEOUT = 4.0
1811 LOCAL_TIMEOUT = 1.0
1812 COMMUNICATION_RETRIES = 5
1813
1814 WAIT_FOR_BREAK_TIMEOUT = 3.0
1815
1816 SHUTDOWN_TIMEOUT = 4.0
1817 STARTUP_TIMEOUT = 3.0
1818 STARTUP_RETRIES = 3
1819
1820 LOOPBACK = '127.0.0.1'
1821 LOCALHOST = 'localhost'
1822
1823 SERVER_PORT_RANGE_START = 51000
1824 SERVER_PORT_RANGE_LENGTH = 24
1825
1826 SOURCE_EVENT_CALL = 'C'
1827 SOURCE_EVENT_LINE = 'L'
1828 SOURCE_EVENT_RETURN = 'R'
1829 SOURCE_EVENT_EXCEPTION = 'E'
1830 SOURCE_STATE_UNBROKEN = '*'
1831 SOURCE_BP_ENABLED = 'B'
1832 SOURCE_BP_DISABLED = 'D'
1833
1834 SYMBOL_MARKER = '>'
1835 SYMBOL_ALL = '*'
1836 SOURCE_MORE = '+'
1837 SOURCE_LESS = '-'
1838 SOURCE_ENTIRE_FILE = '^'
1839 CONSOLE_PRINTER = '*** '
1840 CONSOLE_WRAP_INDEX = 78
1841 CONSOLE_PROMPT = '\n> '
1842 CONSOLE_PROMPT_ANALYZE = '\nAnalayze> '
1843 CONSOLE_INTRO = ("""RPDB2 - The Remote Python Debugger, version %s,
1844 Copyright (C) 2005-2009 Nir Aides.
1845 Type "help", "copyright", "license", "credits" for more information.""" % (RPDB_VERSION))
1846
1847 PRINT_NOTICE_PROMPT = "Hit Return for more, or q (and Return) to quit:"
1848 PRINT_NOTICE_LINES_PER_SECTION = 20
1849
1850 STR_NO_THREADS = "Operation failed since no traced threads were found."
1851 STR_STARTUP_NOTICE = "Attaching to debuggee..."
1852 STR_SPAWN_UNSUPPORTED = "The debugger does not know how to open a new console on this system. You can start the debuggee manually with the -d flag on a separate console and then use the 'attach' command to attach to it."
1853 STR_SPAWN_UNSUPPORTED_SCREEN_SUFFIX = """Alternatively, you can use the screen utility and invoke rpdb2 in screen mode with the -s command-line flag as follows:
1854 screen rpdb2 -s some-script.py script-arg1 script-arg2..."""
1855 STR_AUTOMATIC_LAUNCH_UNKNOWN = STR_SPAWN_UNSUPPORTED
1856 STR_STARTUP_SPAWN_NOTICE = "Starting debuggee..."
1857 STR_KILL_NOTICE = "Stopping debuggee..."
1858 STR_STARTUP_FAILURE = "Debuggee failed to start in a timely manner."
1859 STR_OUTPUT_WARNING = "Textual output will be done at the debuggee."
1860 STR_OUTPUT_WARNING_ASYNC = "The operation will continue to run in the background."
1861 STR_ANALYZE_GLOBALS_WARNING = "In analyze mode the globals and locals dictionaries are read only."
1862 STR_BREAKPOINTS_LOADED = "Breakpoints were loaded."
1863 STR_BREAKPOINTS_SAVED = "Breakpoints were saved."
1864 STR_BREAKPOINTS_SAVE_PROBLEM = "A problem occurred while saving the breakpoints."
1865 STR_BREAKPOINTS_LOAD_PROBLEM = "A problem occurred while loading the breakpoints."
1866 STR_BREAKPOINTS_NOT_SAVED = "Breakpoints were not saved."
1867 STR_BREAKPOINTS_NOT_LOADED = "Breakpoints were not loaded."
1868 STR_BREAKPOINTS_FILE_NOT_FOUND = "Breakpoints file was not found."
1869 STR_BREAKPOINTS_NOT_FOUND = "No Breakpoints were found."
1870 STR_BAD_FILENAME = "Bad File Name."
1871 STR_SOME_BREAKPOINTS_NOT_LOADED = "Some breakpoints were not loaded, because of an error."
1872 STR_BAD_EXPRESSION = "Bad expression '%s'."
1873 STR_FILE_NOT_FOUND = "File '%s' not found."
1874 STR_DISPLAY_ERROR = """If the X server (Windowing system) is not started you need to use rpdb2 with the screen utility and invoke rpdb2 in screen mode with the -s command-line flag as follows:
1875 screen rpdb2 -s some-script.py script-arg1 script-arg2..."""
1876 STR_EXCEPTION_NOT_FOUND = "No exception was found."
1877 STR_SCOPE_NOT_FOUND = "Scope '%s' not found."
1878 STR_NO_SUCH_BREAKPOINT = "Breakpoint not found."
1879 STR_THREAD_NOT_FOUND = "Thread was not found."
1880 STR_NO_THREADS_FOUND = "No threads were found."
1881 STR_THREAD_NOT_BROKEN = "Thread is running."
1882 STR_THREAD_FOCUS_SET = "Focus was set to chosen thread."
1883 STR_ILEGAL_ANALYZE_MODE_ARG = "Argument is not allowed in analyze mode. Type 'help analyze' for more info."
1884 STR_ILEGAL_ANALYZE_MODE_CMD = "Command is not allowed in analyze mode. Type 'help analyze' for more info."
1885 STR_ANALYZE_MODE_TOGGLE = "Analyze mode was set to: %s."
1886 STR_BAD_ARGUMENT = "Bad Argument."
1887 STR_BAD_SYNTAX = 'Unknown syntax: %s\nDid you forget to use the exec or eval console commands?'
1888 STR_PSYCO_WARNING = "The psyco module was detected. The debugger is incompatible with the psyco module and will not function correctly as long as the psyco module is imported and used."
1889 STR_CONFLICTING_MODULES = "The modules: %s, which are incompatible with the debugger were detected and can possibly cause the debugger to fail."
1890 STR_SIGNAL_INTERCEPT = "The signal %s(%d) was intercepted inside debugger tracing logic. It will be held pending until the debugger continues. Any exceptions raised by the handler will be ignored!"
1891 STR_SIGNAL_EXCEPTION = "Exception %s raised by handler of signal %s(%d) inside debugger tracing logic was ignored!"
1892 STR_DEBUGGEE_TERMINATED = "Debuggee has terminated."
1893 STR_DEBUGGEE_NOT_BROKEN = "Debuggee has to be waiting at break point to complete this command."
1894 STR_DEBUGGER_HAS_BROKEN = "Debuggee is waiting at break point for further commands."
1895 STR_ALREADY_ATTACHED = "Already attached. Detach from debuggee and try again."
1896 STR_NOT_ATTACHED = "Not attached to any script. Attach to a script and try again."
1897 STR_COMMUNICATION_FAILURE = "Failed to communicate with debugged script."
1898 STR_ERROR_OTHER = "Command returned the following error:\n%(type)s, %(value)s.\nPlease check stderr for stack trace and report to support."
1899 STR_BAD_MBCS_PATH = "The debugger can not launch the script since the path to the Python executable or the debugger scripts can not be encoded into the default system code page. Please check the settings of 'Language for non-Unicode programs' in the Advanced tab of the Windows Regional and Language Options dialog."
1900 STR_LOST_CONNECTION = "Lost connection to debuggee."
1901 STR_FIREWALL_BLOCK = "A firewall is blocking the local communication chanel (socket) that is required between the debugger and the debugged script. Please make sure that the firewall allows that communication."
1902 STR_BAD_VERSION = "A debuggee was found with incompatible debugger version %(value)s."
1903 STR_BAD_VERSION2 = "While attempting to find the specified debuggee at least one debuggee was found that uses incompatible version of RPDB2."
1904 STR_UNEXPECTED_DATA = "Unexpected data received."
1905 STR_ACCESS_DENIED = "While attempting to find debuggee, at least one debuggee denied connection because of mismatched passwords. Please verify your password."
1906 STR_ACCESS_DENIED2 = "Communication is denied because of un-matching passwords."
1907 STR_ENCRYPTION_EXPECTED = "While attempting to find debuggee, at least one debuggee denied connection since it accepts encrypted connections only."
1908 STR_ENCRYPTION_EXPECTED2 = "Debuggee will only talk over an encrypted channel."
1909 STR_DECRYPTION_FAILURE = "Bad packet was received by the debuggee."
1910 STR_DEBUGGEE_NO_ENCRYPTION = "Debuggee does not support encrypted mode. Either install the python-crypto package on the debuggee machine or allow unencrypted connections."
1911 STR_RANDOM_PASSWORD = "Password has been set to a random password."
1912 STR_PASSWORD_INPUT = "Please type a password:"
1913 STR_PASSWORD_CONFIRM = "Password has been set."
1914 STR_PASSWORD_NOT_SUPPORTED = "The --pwd flag is only supported on NT systems."
1915 STR_PASSWORD_MUST_BE_SET = "A password should be set to secure debugger client-server communication."
1916 STR_BAD_DATA = "Bad data received from debuggee."
1917 STR_BAD_FILE_DATA = "Bad data received from file."
1918 STR_ATTACH_FAILED = "Failed to attach"
1919 STR_ATTACH_FAILED_NAME = "Failed to attach to '%s'."
1920 STR_ATTACH_CRYPTO_MODE = "Debug Channel is%s encrypted."
1921 STR_ATTACH_CRYPTO_MODE_NOT = "NOT"
1922 STR_ATTACH_SUCCEEDED = "Successfully attached to '%s'."
1923 STR_ATTEMPTING_TO_STOP = "Requesting script to stop."
1924 STR_ATTEMPTING_TO_DETACH = "Detaching from script..."
1925 STR_DETACH_SUCCEEDED = "Detached from script."
1926 STR_DEBUGGEE_UNKNOWN = "Failed to find script."
1927 STR_MULTIPLE_DEBUGGEES = "WARNING: There is more than one debuggee '%s'."
1928 MSG_ERROR_HOST_TEXT = """The debugger was not able to set the host to '%s'.
1929 The following error was returned:
1930 %s"""
1931 STR_SOURCE_NOT_FOUND = "Failed to get source from debuggee."
1932 STR_SCRIPTS_CONNECTING = "Connecting to '%s'..."
1933 STR_SCRIPTS_NO_SCRIPTS = "No scripts to debug on '%s'"
1934 STR_SCRIPTS_TO_DEBUG = """Scripts to debug on '%s':
1935
1936 pid name
1937 --------------------------"""
1938 STR_STACK_TRACE = """Stack trace for thread %d:
1939
1940 Frame File Name Line Function
1941 ------------------------------------------------------------------------------"""
1942 STR_SOURCE_LINES = """Source lines for thread %d from file '%s':
1943 """
1944 STR_ACTIVE_THREADS = """List of active threads known to the debugger:
1945
1946 No Tid Name State
1947 -----------------------------------------------"""
1948 STR_BREAKPOINTS_LIST = """List of breakpoints:
1949
1950 Id State Line Filename-Scope-Condition-Encoding
1951 ------------------------------------------------------------------------------"""
1952
1953 STR_BREAKPOINTS_TEMPLATE = """ %2d %-8s %5d %s
1954 %s
1955 %s
1956 %s"""
1957
1958 STR_ENCRYPTION_SUPPORT_ERROR = "Encryption is not supported since the python-crypto package was not found. Either install the python-crypto package or allow unencrypted connections."
1959 STR_PASSWORD_NOT_SET = 'Password is not set.'
1960 STR_PASSWORD_SET = 'Password is set to: "%s"'
1961 STR_PASSWORD_BAD = 'The password should begin with a letter and continue with any combination of digits, letters or underscores (\'_\'). Only English characters are accepted for letters.'
1962 STR_ENCRYPT_MODE = 'Force encryption mode: %s'
1963 STR_REMOTE_MODE = 'Allow remote machines mode: %s'
1964 STR_ENCODING_MODE = 'Encoding is set to: %s'
1965 STR_ENCODING_MODE_SET = 'Encoding was set to: %s'
1966 STR_ENCODING_BAD = 'The specified encoding was not recognized by the debugger.'
1967 STR_ENVIRONMENT = 'The current environment mapping is:'
1968 STR_ENVIRONMENT_EMPTY = 'The current environment mapping is not set.'
1969 STR_SYNCHRONICITY_BAD = "Can not process command when thread is running unless synchronicity mode is turned on. Type 'help synchro' at the command prompt for more information."
1970 STR_SYNCHRONICITY_MODE = 'The synchronicity mode is set to: %s'
1971 STR_TRAP_MODE = 'Trap unhandled exceptions mode is set to: %s'
1972 STR_TRAP_MODE_SET = "Trap unhandled exceptions mode was set to: %s."
1973 STR_FORK_MODE = "Fork mode is set to: %s, %s."
1974 STR_FORK_MODE_SET = "Fork mode was set to: %s, %s."
1975 STR_LOCAL_NAMESPACE_WARNING = 'Debugger modifications to the original bindings of the local namespace of this frame will be committed before the execution of the next statement of the frame. Any code using these variables executed before that point will see the original values.'
1976 STR_WARNING = 'Warning: %s'
1977
1978 STR_MAX_NAMESPACE_WARNING_TITLE = 'Namespace Warning'
1979 STR_MAX_NAMESPACE_WARNING_TYPE = '*** WARNING ***'
1980 STR_MAX_NAMESPACE_WARNING_MSG = 'Number of items exceeds capacity of namespace browser.'
1981 STR_MAX_EVALUATE_LENGTH_WARNING = 'Output length exeeds maximum capacity.'
1982
1983 FORK_CHILD = 'child'
1984 FORK_PARENT = 'parent'
1985 FORK_MANUAL = 'manual'
1986 FORK_AUTO = 'auto'
1987
1988 ENCRYPTION_ENABLED = 'encrypted'
1989 ENCRYPTION_DISABLED = 'plain-text'
1990
1991 STATE_ENABLED = 'enabled'
1992 STATE_DISABLED = 'disabled'
1993
1994 BREAKPOINTS_FILE_EXT = '.bpl'
1995 PYTHON_FILE_EXTENSION = '.py'
1996 PYTHONW_FILE_EXTENSION = '.pyw'
1997 PYTHONW_SO_EXTENSION = '.so'
1998 PYTHON_EXT_LIST = ['.py', '.pyw', '.pyc', '.pyd', '.pyo', '.so']
1999
2000 MODULE_SCOPE = '?'
2001 MODULE_SCOPE2 = '<module>'
2002
2003 BLENDER_SOURCE_NOT_AVAILABLE = as_unicode('Blender script source code is not available.')
2004 SOURCE_NOT_AVAILABLE = as_unicode('Source code is not available.')
2005
2006 SCOPE_SEP = '.'
2007
2008 BP_FILENAME_SEP = ':'
2009 BP_EVAL_SEP = ','
2010
2011 DEBUGGER_FILENAME = 'rpdb2.py'
2012 THREADING_FILENAME = 'threading.py'
2013
2014 STR_STATE_BROKEN = 'waiting at break point'
2015
2016 STATE_BROKEN = 'broken'
2017 STATE_RUNNING = 'running'
2018
2019 STATE_ANALYZE = 'analyze'
2020 STATE_DETACHED = 'detached'
2021 STATE_DETACHING = 'detaching'
2022 STATE_SPAWNING = 'spawning'
2023 STATE_ATTACHING = 'attaching'
2024
2025 DEFAULT_NUMBER_OF_LINES = 20
2026
2027 DICT_KEY_TID = 'tid'
2028 DICT_KEY_STACK = 'stack'
2029 DICT_KEY_CODE_LIST = 'code_list'
2030 DICT_KEY_CURRENT_TID = 'current tid'
2031 DICT_KEY_BROKEN = 'broken'
2032 DICT_KEY_BREAKPOINTS = 'breakpoints'
2033 DICT_KEY_LINES = 'lines'
2034 DICT_KEY_FILENAME = 'filename'
2035 DICT_KEY_FIRST_LINENO = 'first_lineno'
2036 DICT_KEY_FRAME_LINENO = 'frame_lineno'
2037 DICT_KEY_EVENT = 'event'
2038 DICT_KEY_EXPR = 'expr'
2039 DICT_KEY_NAME = 'name'
2040 DICT_KEY_REPR = 'repr'
2041 DICT_KEY_IS_VALID = 'fvalid'
2042 DICT_KEY_TYPE = 'type'
2043 DICT_KEY_SUBNODES = 'subnodes'
2044 DICT_KEY_N_SUBNODES = 'n_subnodes'
2045 DICT_KEY_ERROR = 'error'
2046
2047 RPDB_EXEC_INFO = as_unicode('rpdb_exception_info')
2048
2049 MODE_ON = 'ON'
2050 MODE_OFF = 'OFF'
2051
2052 ENCODING_UTF8_PREFIX_1 = '\xef\xbb\xbf'
2053 ENCODING_SOURCE = '# -*- coding: %s -*-\n'
2054 ENCODING_AUTO = as_unicode('auto')
2055 ENCODING_RAW = as_unicode('raw')
2056 ENCODING_RAW_I = as_unicode('__raw')
2057
2058 MAX_EVALUATE_LENGTH = 256 * 1024
2059 MAX_NAMESPACE_ITEMS = 1024
2060 MAX_SORTABLE_LENGTH = 256 * 1024
2061 REPR_ID_LENGTH = 4096
2062
2063 MAX_NAMESPACE_WARNING = {
2064 DICT_KEY_EXPR: STR_MAX_NAMESPACE_WARNING_TITLE,
2065 DICT_KEY_NAME: STR_MAX_NAMESPACE_WARNING_TITLE,
2066 DICT_KEY_REPR: STR_MAX_NAMESPACE_WARNING_MSG,
2067 DICT_KEY_IS_VALID: False,
2068 DICT_KEY_TYPE: STR_MAX_NAMESPACE_WARNING_TYPE,
2069 DICT_KEY_N_SUBNODES: 0
2070 }
2071
2072 MAX_EVENT_LIST_LENGTH = 1000
2073
2074 EVENT_EXCLUDE = 'exclude'
2075 EVENT_INCLUDE = 'include'
2076
2077 INDEX_TABLE_SIZE = 100
2078
2079 DISPACHER_METHOD = 'dispatcher_method'
2080
2081 CONFLICTING_MODULES = ['psyco', 'pdb', 'bdb', 'doctest']
2082
2083 XML_DATA = """<?xml version='1.0'?>
2084 <methodCall>
2085 <methodName>dispatcher_method</methodName>
2086 <params>
2087 <param>
2088 <value><string>%s</string></value>
2089 </param>
2090 </params>
2091 </methodCall>""" % RPDB_COMPATIBILITY_VERSION
2092
2093 N_WORK_QUEUE_THREADS = 8
2094
2095 DEFAULT_PATH_SUFFIX_LENGTH = 55
2096
2097 ELLIPSIS_UNICODE = as_unicode('...')
2098 ELLIPSIS_BYTES = as_bytes('...')
2099
2100 ERROR_NO_ATTRIBUTE = 'Error: No attribute.'
2101
2102
2103 g_server_lock = threading.RLock()
2104 g_server = None
2105 g_debugger = None
2106
2107 g_fScreen = False
2108 g_fDefaultStd = True
2109
2110 #
2111 # In debug mode errors and tracebacks are printed to stdout
2112 #
2113 g_fDebug = False
2114
2115 #
2116 # Lock for the traceback module to prevent it from interleaving
2117 # output from different threads.
2118 #
2119 g_traceback_lock = threading.RLock()
2120
2121 g_source_provider_aux = None
2122 g_lines_cache = {}
2123
2124 g_initial_cwd = []
2125
2126 g_error_mapping = {
2127 socket.error: STR_COMMUNICATION_FAILURE,
2128
2129 CConnectionException: STR_LOST_CONNECTION,
2130 FirewallBlock: STR_FIREWALL_BLOCK,
2131 BadVersion: STR_BAD_VERSION,
2132 UnexpectedData: STR_UNEXPECTED_DATA,
2133 SpawnUnsupported: STR_SPAWN_UNSUPPORTED,
2134 UnknownServer: STR_DEBUGGEE_UNKNOWN,
2135 UnsetPassword: STR_PASSWORD_MUST_BE_SET,
2136 EncryptionNotSupported: STR_DEBUGGEE_NO_ENCRYPTION,
2137 EncryptionExpected: STR_ENCRYPTION_EXPECTED,
2138 DecryptionFailure: STR_DECRYPTION_FAILURE,
2139 AuthenticationBadData: STR_ACCESS_DENIED,
2140 AuthenticationFailure: STR_ACCESS_DENIED,
2141 BadMBCSPath: STR_BAD_MBCS_PATH,
2142
2143 AlreadyAttached: STR_ALREADY_ATTACHED,
2144 NotAttached: STR_NOT_ATTACHED,
2145 DebuggerNotBroken: STR_DEBUGGEE_NOT_BROKEN,
2146 NoThreads: STR_NO_THREADS,
2147 NoExceptionFound: STR_EXCEPTION_NOT_FOUND,
2148 }
2149
2150 #
2151 # These globals are related to handling the os.fork() os._exit() and exec
2152 # pattern.
2153 #
2154 g_forkpid = None
2155 g_forktid = None
2156 g_fignorefork = False
2157
2158 g_exectid = None
2159 g_execpid = None
2160
2161 g_fos_exit = False
2162
2163
2164 #
2165 # To hold a reference to __main__ to prevent its release if an unhandled
2166 # exception is raised.
2167 #
2168 g_module_main = None
2169
2170 g_found_conflicting_modules = []
2171
2172 g_fignore_atexit = False
2173 g_ignore_broken_pipe = 0
2174
2175
2176 #
2177 # Unicode version of path names that do not encode well witn the windows
2178 # 'mbcs' encoding. This dict is used to work with such path names on
2179 # windows.
2180 #
2181 g_found_unicode_files = {}
2182
2183 g_frames_path = {}
2184
2185 g_signal_handlers = {}
2186 g_signals_pending = []
2187
2188 #g_profile = None
2189
2190 g_fFirewallTest = True
2191
2192
2193
2194 if is_py3k():
2195 g_safe_base64_to = bytes.maketrans(as_bytes('/+='), as_bytes('_-#'))
2196 g_safe_base64_from = bytes.maketrans(as_bytes('_-#'), as_bytes('/+='))
2197 else:
2198 g_safe_base64_to = string.maketrans(as_bytes('/+='), as_bytes('_-#'))
2199 g_safe_base64_from = string.maketrans(as_bytes('_-#'), as_bytes('/+='))
2200
2201
2202
2203 g_alertable_waiters = {}
2204
2205
2206
2207 g_builtins_module = sys.modules.get('__builtin__', sys.modules.get('builtins'))
2208
2209
2210
2211 #
2212 # ---------------------------- General Utils ------------------------------
2213 #
2214
2215
2216
2217 def job_wrapper(event, foo, *args, **kwargs):
2218 try:
2219 #print_debug('Thread %d doing job %s' % (thread.get_ident(), foo.__name__))
2220 foo(*args, **kwargs)
2221 finally:
2222 event.set()
2223
2224
2225
2226 def send_job(tid, timeout, foo, *args, **kwargs):
2227 #
2228 # Attempt to send job to thread tid.
2229 # Will throw KeyError if thread tid is not available for jobs.
2230 #
2231
2232 (lock, jobs) = g_alertable_waiters[tid]
2233
2234 event = threading.Event()
2235 f = lambda: job_wrapper(event, foo, *args, **kwargs)
2236 jobs.append(f)
2237
2238 try:
2239 lock.acquire()
2240 lock_notify_all(lock)
2241 finally:
2242 lock.release()
2243
2244 safe_wait(event, timeout)
2245
2246
2247
2248 def alertable_wait(lock, timeout = None):
2249 jobs = []
2250 tid = thread.get_ident()
2251 g_alertable_waiters[tid] = (lock, jobs)
2252
2253 try:
2254 safe_wait(lock, timeout)
2255
2256 while len(jobs) != 0:
2257 job = jobs.pop(0)
2258 try:
2259 job()
2260 except:
2261 pass
2262
2263 if len(jobs) == 0:
2264 time.sleep(0.1)
2265
2266 finally:
2267 del g_alertable_waiters[tid]
2268
2269
2270
2271 def safe_wait(lock, timeout = None):
2272 #
2273 # workaround windows bug where signal handlers might raise exceptions
2274 # even if they return normally.
2275 #
2276
2277 while True:
2278 try:
2279 t0 = time.time()
2280 return lock.wait(timeout)
2281
2282 except:
2283 if timeout == None:
2284 continue
2285
2286 timeout -= (time.time() - t0)
2287 if timeout <= 0:
2288 return
2289
2290
2291
2292 #
2293 # The following code is related to the ability of the debugger
2294 # to work both on Python 2.5 and 3.0.
2295 #
2296
2297 def lock_notify_all(lock):
2298 try:
2299 if is_py3k():
2300 return lock.notify_all()
2301
2302 except AttributeError:
2303 pass
2304
2305 return lock.notifyAll()
2306
2307
2308
2309 def event_is_set(event):
2310 try:
2311 if is_py3k():
2312 return event.is_set()
2313
2314 except AttributeError:
2315 pass
2316
2317 return event.isSet()
2318
2319
2320
2321 def thread_set_daemon(thread, fdaemon):
2322 try:
2323 if is_py3k():
2324 return thread.set_daemon(fdaemon)
2325
2326 except AttributeError:
2327 pass
2328
2329 return thread.setDaemon(fdaemon)
2330
2331
2332
2333 def thread_is_alive(thread):
2334 try:
2335 if is_py3k():
2336 return thread.is_alive()
2337
2338 except AttributeError:
2339 pass
2340
2341 return thread.isAlive()
2342
2343
2344
2345 def thread_set_name(thread, name):
2346 try:
2347 if is_py3k():
2348 return thread.set_name(name)
2349
2350 except AttributeError:
2351 pass
2352
2353 return thread.setName(name)
2354
2355
2356
2357 def thread_get_name(thread):
2358 try:
2359 if is_py3k():
2360 return thread.get_name()
2361
2362 except AttributeError:
2363 pass
2364
2365 return thread.getName()
2366
2367
2368
2369 def current_thread():
2370 try:
2371 if is_py3k():
2372 return threading.current_thread()
2373
2374 except AttributeError:
2375 pass
2376
2377 return threading.currentThread()
2378
2379
2380
2381 class _stub_type:
2382 pass
2383
2384
2385
2386 def _rpdb2_bytes(s, e):
2387 return s.encode(e)
2388
2389
2390
2391 if not hasattr(g_builtins_module, 'unicode'):
2392 unicode = _stub_type
2393
2394 if not hasattr(g_builtins_module, 'long'):
2395 long = _stub_type
2396
2397 if not hasattr(g_builtins_module, 'str8'):
2398 str8 = _stub_type
2399
2400 if not hasattr(g_builtins_module, 'bytearray'):
2401 bytearray = _stub_type
2402
2403 if not hasattr(g_builtins_module, 'bytes'):
2404 bytes = _stub_type
2405
2406 #
2407 # Pickle on Python 2.5 should know how to handle byte strings
2408 # that arrive from Python 3.0 over sockets.
2409 #
2410 g_builtins_module.bytes = _rpdb2_bytes
2411
2412
2413 if is_py3k():
2414 class sets:
2415 Set = _stub_type
2416 BaseSet = _stub_type
2417 ImmutableSet = _stub_type
2418
2419
2420
2421 if sys.version_info[:2] <= (2, 3):
2422 set = sets.Set
2423
2424
2425
2426 def _raw_input(s):
2427 if is_py3k():
2428 return input(s)
2429
2430 i = raw_input(s)
2431 i = as_unicode(i, detect_encoding(sys.stdin), fstrict = True)
2432
2433 return i
2434
2435
2436
2437 def _print(s, f = sys.stdout, feol = True):
2438 s = as_unicode(s)
2439
2440 encoding = detect_encoding(f)
2441
2442 s = as_bytes(s, encoding, fstrict = False)
2443 s = as_string(s, encoding)
2444
2445 if feol:
2446 f.write(s + '\n')
2447 else:
2448 f.write(s)
2449
2450
2451
2452 def detect_encoding(file):
2453 try:
2454 encoding = file.encoding
2455 if encoding == None:
2456 return detect_locale()
2457
2458 except:
2459 return detect_locale()
2460
2461 try:
2462 codecs.lookup(encoding)
2463 return encoding
2464
2465 except:
2466 pass
2467
2468 if encoding.lower().startswith('utf_8'):
2469 return 'utf-8'
2470
2471 return 'ascii'
2472
2473
2474
2475 def detect_locale():
2476 encoding = locale.getdefaultlocale()[1]
2477
2478 if encoding == None:
2479 return 'ascii'
2480
2481 try:
2482 codecs.lookup(encoding)
2483 return encoding
2484
2485
2486 except:
2487 pass
2488
2489 if encoding.lower().startswith('utf_8'):
2490 return 'utf-8'
2491
2492 return 'ascii'
2493
2494
2495
2496 def class_name(c):
2497 s = safe_str(c)
2498
2499 if "'" in s:
2500 s = s.split("'")[1]
2501
2502 assert(s.startswith(__name__ + '.'))
2503
2504 return s
2505
2506
2507
2508 def clip_filename(path, n = DEFAULT_PATH_SUFFIX_LENGTH):
2509 suffix = calc_suffix(path, n)
2510 if not suffix.startswith('...'):
2511 return suffix
2512
2513 index = suffix.find(os.sep)
2514 if index == -1:
2515 return suffix
2516
2517 clip = '...' + suffix[index:]
2518
2519 return clip
2520
2521
2522
2523 def safe_str(x):
2524 try:
2525 return str(x)
2526
2527 except:
2528 return 'N/A'
2529
2530
2531
2532 def safe_repr(x):
2533 try:
2534 return repr(x)
2535
2536 except:
2537 return 'N/A'
2538
2539
2540
2541 def parse_type(t):
2542 rt = safe_repr(t)
2543 if not "'" in rt:
2544 return rt
2545
2546 st = rt.split("'")[1]
2547 return st
2548
2549
2550 def repr_list(pattern, l, length, encoding, is_valid):
2551 length = max(0, length - len(pattern) + 2)
2552
2553 s = ''
2554
2555 index = 0
2556
2557 try:
2558 for i in l:
2559 #
2560 # Remove any trace of session password from data structures that
2561 # go over the network.
2562 #
2563 if type(i) == str and i in ['_rpdb2_args', '_rpdb2_pwd', 'm_rpdb2_pwd']:
2564 continue
2565
2566 s += repr_ltd(i, length - len(s), encoding, is_valid)
2567
2568 index += 1
2569
2570 if index < len(l) and len(s) > length:
2571 is_valid[0] = False
2572 if not s.endswith('...'):
2573 s += '...'
2574 break
2575
2576 if index < len(l) or (index == 1 and pattern[0] == '('):
2577 s += ', '
2578
2579 except AttributeError:
2580 is_valid[0] = False
2581
2582 return as_unicode(pattern % s)
2583
2584
2585
2586 def repr_dict(pattern, d, length, encoding, is_valid):
2587 length = max(0, length - len(pattern) + 2)
2588
2589 s = ''
2590
2591 index = 0
2592
2593 try:
2594 for k in d:
2595 #
2596 # Remove any trace of session password from data structures that
2597 # go over the network.
2598 #
2599 if type(k) == str and k in ['_rpdb2_args', '_rpdb2_pwd', 'm_rpdb2_pwd']:
2600 continue
2601
2602 v = d[k]
2603
2604 s += repr_ltd(k, length - len(s), encoding, is_valid)
2605
2606 if len(s) > length:
2607 is_valid[0] = False
2608 if not s.endswith('...'):
2609 s += '...'
2610 break
2611
2612 s += ': ' + repr_ltd(v, length - len(s), encoding, is_valid)
2613
2614 index += 1
2615
2616 if index < len(d) and len(s) > length:
2617 is_valid[0] = False
2618 if not s.endswith('...'):
2619 s += '...'
2620 break
2621
2622 if index < len(d):
2623 s += ', '
2624
2625 except AttributeError:
2626 is_valid[0] = False
2627
2628 return as_unicode(pattern % s)
2629
2630
2631
2632 def repr_bytearray(s, length, encoding, is_valid):
2633 try:
2634 s = s.decode(encoding)
2635 r = repr_unicode(s, length, is_valid)
2636 return 'bytearray(b' + r[1:] + ')'
2637
2638 except:
2639 #
2640 # If a string is not encoded as utf-8 its repr() will be done with
2641 # the regular repr() function.
2642 #
2643 return repr_str_raw(s, length, is_valid)
2644
2645
2646
2647 def repr_bytes(s, length, encoding, is_valid):
2648 try:
2649 s = s.decode(encoding)
2650 r = repr_unicode(s, length, is_valid)
2651 return 'b' + r[1:]
2652
2653 except:
2654 #
2655 # If a string is not encoded as utf-8 its repr() will be done with
2656 # the regular repr() function.
2657 #
2658 return repr_str_raw(s, length, is_valid)
2659
2660
2661
2662 def repr_str8(s, length, encoding, is_valid):
2663 try:
2664 s = s.decode(encoding)
2665 r = repr_unicode(s, length, is_valid)
2666 return 's' + r[1:]
2667
2668 except:
2669 #
2670 # If a string is not encoded as utf-8 its repr() will be done with
2671 # the regular repr() function.
2672 #
2673 return repr_str_raw(s, length, is_valid)
2674
2675
2676
2677 def repr_str(s, length, encoding, is_valid):
2678 try:
2679 s = as_unicode(s, encoding, fstrict = True)
2680 r = repr_unicode(s, length, is_valid)
2681 return r[1:]
2682
2683 except:
2684 #
2685 # If a string is not encoded as utf-8 its repr() will be done with
2686 # the regular repr() function.
2687 #
2688 return repr_str_raw(s, length, is_valid)
2689
2690
2691
2692 def repr_unicode(s, length, is_valid):
2693 index = [2, 1][is_py3k()]
2694
2695 rs = ''
2696
2697 for c in s:
2698 if len(rs) > length:
2699 is_valid[0] = False
2700 rs += '...'
2701 break
2702
2703 if ord(c) < 128:
2704 rs += repr(c)[index: -1]
2705 else:
2706 rs += c
2707
2708 if not "'" in rs:
2709 return as_unicode("u'%s'" % rs)
2710
2711 if not '"' in rs:
2712 return as_unicode('u"%s"' % rs)
2713
2714 return as_unicode("u'%s'" % rs.replace("'", "\\'"))
2715
2716
2717
2718 def repr_str_raw(s, length, is_valid):
2719 if is_unicode(s):
2720 eli = ELLIPSIS_UNICODE
2721 else:
2722 eli = ELLIPSIS_BYTES
2723
2724 if len(s) > length:
2725 is_valid[0] = False
2726 s = s[: length] + eli
2727
2728 return as_unicode(repr(s))
2729
2730
2731
2732 def repr_base(v, length, is_valid):
2733 r = repr(v)
2734
2735 if len(r) > length:
2736 is_valid[0] = False
2737 r = r[: length] + '...'
2738
2739 return as_unicode(r)
2740
2741
2742
2743 def repr_ltd(x, length, encoding, is_valid = [True]):
2744 try:
2745 length = max(0, length)
2746
2747 try:
2748 if isinstance(x, frozenset):
2749 return repr_list('frozenset([%s])', x, length, encoding, is_valid)
2750
2751 if isinstance(x, set):
2752 return repr_list('set([%s])', x, length, encoding, is_valid)
2753
2754 except NameError:
2755 pass
2756
2757 if isinstance(x, sets.Set):
2758 return repr_list('sets.Set([%s])', x, length, encoding, is_valid)
2759
2760 if isinstance(x, sets.ImmutableSet):
2761 return repr_list('sets.ImmutableSet([%s])', x, length, encoding, is_valid)
2762
2763 if isinstance(x, list):
2764 return repr_list('[%s]', x, length, encoding, is_valid)
2765
2766 if isinstance(x, tuple):
2767 return repr_list('(%s)', x, length, encoding, is_valid)
2768
2769 if isinstance(x, dict):
2770 return repr_dict('{%s}', x, length, encoding, is_valid)
2771
2772 if encoding == ENCODING_RAW_I and [True for t in [str, unicode, bytearray, bytes, str8] if t is type(x)]:
2773 return repr_str_raw(x, length, is_valid)
2774
2775 if type(x) is unicode:
2776 return repr_unicode(x, length, is_valid)
2777
2778 if type(x) is bytearray:
2779 return repr_bytearray(x, length, encoding, is_valid)
2780
2781 if type(x) is bytes:
2782 return repr_bytes(x, length, encoding, is_valid)
2783
2784 if type(x) is str8:
2785 return repr_str8(x, length, encoding, is_valid)
2786
2787 if type(x) is str:
2788 return repr_str(x, length, encoding, is_valid)
2789
2790 if [True for t in [bool, int, float, long, type(None)] if t is type(x)]:
2791 return repr_base(x, length, is_valid)
2792
2793 is_valid[0] = False
2794
2795 y = safe_repr(x)[: length]
2796 if len(y) == length:
2797 y += '...'
2798
2799 if encoding == ENCODING_RAW_I:
2800 encoding = 'utf-8'
2801
2802 try:
2803 y = as_unicode(y, encoding, fstrict = True)
2804 return y
2805
2806 except:
2807 pass
2808
2809 encoding = sys.getfilesystemencoding()
2810 y = as_unicode(y, encoding)
2811
2812 return y
2813
2814 except:
2815 print_debug_exception()
2816 return as_unicode('N/A')
2817
2818
2819
2820 def print_debug(_str):
2821 if not g_fDebug:
2822 return
2823
2824 t = time.time()
2825 l = time.localtime(t)
2826 s = time.strftime('%H:%M:%S', l) + '.%03d' % ((t - int(t)) * 1000)
2827
2828 f = sys._getframe(1)
2829
2830 filename = os.path.basename(f.f_code.co_filename)
2831 lineno = f.f_lineno
2832 name = f.f_code.co_name
2833
2834 str = '%s %s:%d in %s: %s' % (s, filename, lineno, name, _str)
2835
2836 _print(str, sys.__stderr__)
2837
2838
2839
2840 def print_debug_exception(fForce = False):
2841 """
2842 Print exceptions to stdout when in debug mode.
2843 """
2844
2845 if not g_fDebug and not fForce:
2846 return
2847
2848 (t, v, tb) = sys.exc_info()
2849 print_exception(t, v, tb, fForce)
2850
2851
2852
2853 class CFileWrapper:
2854 def __init__(self, f):
2855 self.m_f = f
2856
2857
2858 def write(self, s):
2859 _print(s, self.m_f, feol = False)
2860
2861
2862 def __getattr__(self, name):
2863 return self.m_f.__getattr__(name)
2864
2865
2866
2867 def print_exception(t, v, tb, fForce = False):
2868 """
2869 Print exceptions to stderr when in debug mode.
2870 """
2871
2872 if not g_fDebug and not fForce:
2873 return
2874
2875 try:
2876 g_traceback_lock.acquire()
2877 traceback.print_exception(t, v, tb, file = CFileWrapper(sys.stderr))
2878
2879 finally:
2880 g_traceback_lock.release()
2881
2882
2883
2884 def print_stack():
2885 """
2886 Print exceptions to stdout when in debug mode.
2887 """
2888
2889 if g_fDebug == True:
2890 try:
2891 g_traceback_lock.acquire()
2892 traceback.print_stack(file = CFileWrapper(sys.stderr))
2893
2894 finally:
2895 g_traceback_lock.release()
2896
2897
2898
2899 #
2900 # myisfile() is similar to os.path.isfile() but also works with
2901 # Python eggs.
2902 #
2903 def myisfile(path):
2904 try:
2905 mygetfile(path, False)
2906 return True
2907
2908 except:
2909 return False
2910
2911
2912
2913 #
2914 # Read a file even if inside a Python egg.
2915 #
2916 def mygetfile(path, fread_file = True):
2917 if os.path.isfile(path):
2918 if not fread_file:
2919 return
2920
2921 if sys.platform == 'OpenVMS':
2922 #
2923 # OpenVMS filesystem does not support byte stream.
2924 #
2925 mode = 'r'
2926 else:
2927 mode = 'rb'
2928
2929 f = open(path, mode)
2930 data = f.read()
2931 f.close()
2932 return data
2933
2934 d = os.path.dirname(path)
2935
2936 while True:
2937 if os.path.exists(d):
2938 break
2939
2940 _d = os.path.dirname(d)
2941 if _d in [d, '']:
2942 raise IOError
2943
2944 d = _d
2945
2946 if not zipfile.is_zipfile(d):
2947 raise IOError
2948
2949 z = zipimport.zipimporter(d)
2950
2951 try:
2952 data = z.get_data(path[len(d) + 1:])
2953 return data
2954
2955 except:
2956 raise IOError
2957
2958
2959
2960 def split_command_line_path_filename_args(command_line):
2961 """
2962 Split command line to a 3 elements tuple (path, filename, args)
2963 """
2964
2965 command_line = command_line.strip()
2966 if len(command_line) == 0:
2967 return ('', '', '')
2968
2969 if myisfile(command_line):
2970 (_path, _filename) = split_path(command_line)
2971 return (_path, _filename, '')
2972
2973 if command_line[0] in ['"', "'"]:
2974 _command_line = command_line[1:]
2975 i = _command_line.find(command_line[0])
2976 if i == -1:
2977 (_path, filename) = split_path(_command_line)
2978 return (_path, filename, '')
2979 else:
2980 (_path, filename) = split_path(_command_line[: i])
2981 args = _command_line[i + 1:].strip()
2982 return (_path, filename, args)
2983 else:
2984 i = command_line.find(' ')
2985 if i == -1:
2986 (_path, filename) = split_path(command_line)
2987 return (_path, filename, '')
2988 else:
2989 args = command_line[i + 1:].strip()
2990 (_path, filename) = split_path(command_line[: i])
2991 return (_path, filename, args)
2992
2993
2994
2995 def split_path(path):
2996 (_path, filename) = os.path.split(path)
2997
2998 #
2999 # Make sure path separator (e.g. '/') ends the splitted path if it was in
3000 # the original path.
3001 #
3002 if (_path[-1:] not in [os.path.sep, os.path.altsep]) and \
3003 (path[len(_path): len(_path) + 1] in [os.path.sep, os.path.altsep]):
3004 _path = _path + path[len(_path): len(_path) + 1]
3005
3006 return (_path, filename)
3007
3008
3009
3010 def my_os_path_join(dirname, basename):
3011 if is_py3k() or (type(dirname) == str and type(basename) == str):
3012 return os.path.join(dirname, basename)
3013
3014 encoding = sys.getfilesystemencoding()
3015
3016 if type(dirname) == str:
3017 dirname = dirname.decode(encoding)
3018
3019 if type(basename) == str:
3020 basename = basename.decode(encoding)
3021
3022 return os.path.join(dirname, basename)
3023
3024
3025
3026 def calc_frame_path(frame):
3027 globals_filename = frame.f_globals.get('__file__', None)
3028 filename = frame.f_code.co_filename
3029
3030 if filename.startswith('<'):
3031 if globals_filename == None:
3032 return filename
3033 else:
3034 filename = CalcScriptName(os.path.basename(globals_filename))
3035
3036 if filename in g_frames_path:
3037 return g_frames_path[filename]
3038
3039 if globals_filename != None:
3040 dirname = os.path.dirname(globals_filename)
3041 basename = os.path.basename(filename)
3042 path = my_os_path_join(dirname, basename)
3043
3044 if os.path.isabs(path):
3045 abspath = my_abspath(path)
3046 lowered = winlower(abspath)
3047 g_frames_path[filename] = lowered
3048 return lowered
3049
3050 try:
3051 abspath = FindFile(path, fModules = True)
3052 lowered = winlower(abspath)
3053 g_frames_path[filename] = lowered
3054 return lowered
3055
3056 except IOError:
3057 pass
3058
3059 if os.path.isabs(filename):
3060 abspath = my_abspath(filename)
3061 lowered = winlower(abspath)
3062 g_frames_path[filename] = lowered
3063 return lowered
3064
3065 try:
3066 abspath = FindFile(filename, fModules = True)
3067 lowered = winlower(abspath)
3068 g_frames_path[filename] = lowered
3069 return lowered
3070
3071 except IOError:
3072 lowered = winlower(filename)
3073 return lowered
3074
3075
3076
3077 def my_abspath(path):
3078 """
3079 We need our own little version of os.path.abspath since the original
3080 code imports modules in the 'nt' code path which can cause our debugger
3081 to deadlock in unexpected locations.
3082 """
3083
3084 if path[:1] == '<':
3085 #
3086 # 'path' may also be '<stdin>' in which case it is left untouched.
3087 #
3088 return path
3089
3090 if os.name == 'nt':
3091 return my_abspath1(path)
3092
3093 return os.path.abspath(path)
3094
3095
3096
3097 #
3098 # MOD
3099 #
3100 def my_abspath1(path):
3101 """
3102 Modification of ntpath.abspath() that avoids doing an import.
3103 """
3104
3105 if path:
3106 try:
3107 path = _getfullpathname(path)
3108 except WindowsError:
3109 pass
3110 else:
3111 try:
3112 path = getcwd()
3113
3114 except UnicodeDecodeError:
3115 #
3116 # This exception can be raised in py3k (alpha) on nt.
3117 #
3118 path = getcwdu()
3119
3120 np = os.path.normpath(path)
3121
3122 if (len(np) >= 2) and (np[1:2] == ':'):
3123 np = np[:1].upper() + np[1:]
3124
3125 return np
3126
3127
3128
3129 def IsPythonSourceFile(path):
3130 if path.endswith(PYTHON_FILE_EXTENSION):
3131 return True
3132
3133 if path.endswith(PYTHONW_FILE_EXTENSION):
3134 return True
3135
3136 path = g_found_unicode_files.get(path, path)
3137
3138 for lineno in range(1, 10):
3139 line = get_source_line(path, lineno)
3140
3141 if line.startswith('#!') and 'python' in line:
3142 return True
3143
3144 if is_py3k():
3145 #
3146 # py3k does not have compiler.parseFile, so return
3147 # True anyway...
3148 #
3149 return True
3150
3151 try:
3152 compiler.parseFile(path)
3153 return True
3154
3155 except:
3156 return False
3157
3158
3159
3160 def CalcModuleName(filename):
3161 _basename = os.path.basename(filename)
3162 (modulename, ext) = os.path.splitext(_basename)
3163
3164 if ext in PYTHON_EXT_LIST:
3165 return modulename
3166
3167 return _basename
3168
3169
3170
3171 def CalcScriptName(filename, fAllowAnyExt = True):
3172 if filename.endswith(PYTHON_FILE_EXTENSION):
3173 return filename
3174
3175 if filename.endswith(PYTHONW_FILE_EXTENSION):
3176 return filename
3177
3178 if filename.endswith(PYTHONW_SO_EXTENSION):
3179 scriptname = filename[:-3] + PYTHON_FILE_EXTENSION
3180 return scriptname
3181
3182 if filename[:-1].endswith(PYTHON_FILE_EXTENSION):
3183 scriptname = filename[:-1]
3184 return scriptname
3185
3186 if fAllowAnyExt:
3187 return filename
3188
3189 scriptname = filename + PYTHON_FILE_EXTENSION
3190
3191 return scriptname
3192
3193
3194
3195 def FindModuleDir(module_name):
3196 if module_name == '':
3197 raise IOError
3198
3199 dot_index = module_name.rfind('.')
3200 if dot_index != -1:
3201 parent = module_name[: dot_index]
3202 child = module_name[dot_index + 1:]
3203 else:
3204 parent = ''
3205 child = module_name
3206
3207 m = sys.modules[module_name]
3208
3209 if not hasattr(m, '__file__') or m.__file__ == None:
3210 parent_dir = FindModuleDir(parent)
3211 module_dir = my_os_path_join(parent_dir, winlower(child))
3212 return module_dir
3213
3214 if not os.path.isabs(m.__file__):
3215 parent_dir = FindModuleDir(parent)
3216 module_dir = my_os_path_join(parent_dir, winlower(child))
3217 return module_dir
3218
3219 (root, ext) = os.path.splitext(m.__file__)
3220 if root.endswith('__init__'):
3221 root = os.path.dirname(root)
3222
3223 abspath = my_abspath(root)
3224 lowered = winlower(abspath)
3225
3226 return lowered
3227
3228
3229
3230 def FindFileAsModule(filename):
3231 lowered = winlower(filename)
3232 (root, ext) = os.path.splitext(lowered)
3233
3234 root_dotted = root.replace('\\', '.').replace('/', '.').replace(':', '.')
3235
3236 match_list = []
3237 for (module_name, m) in list(sys.modules.items()):
3238 lowered_module_name = winlower(module_name)
3239 if (root_dotted + '.').startswith(lowered_module_name + '.'):
3240 match_list.append((len(module_name), module_name))
3241
3242 if lowered_module_name == root_dotted:
3243 break
3244
3245 match_list.sort()
3246 match_list.reverse()
3247
3248 for (matched_len, matched_module) in match_list:
3249 try:
3250 module_dir = FindModuleDir(matched_module)
3251 except IOError:
3252 continue
3253
3254 suffix = root[matched_len:]
3255 if suffix == '':
3256 path = module_dir + ext
3257 else:
3258 path = my_os_path_join(module_dir, suffix.strip('\\')) + ext
3259
3260 scriptname = CalcScriptName(path, fAllowAnyExt = False)
3261 if myisfile(scriptname):
3262 return scriptname
3263
3264 #
3265 # Check .pyw files
3266 #
3267 scriptname += 'w'
3268 if scriptname.endswith(PYTHONW_FILE_EXTENSION) and myisfile(scriptname):
3269 return scriptname
3270
3271 raise IOError
3272
3273
3274
3275 def getcwd():
3276 try:
3277 return os.getcwd()
3278
3279 except UnicodeDecodeError:
3280 print_debug_exception(True)
3281 raise
3282
3283
3284
3285 def getcwdu():
3286 if hasattr(os, 'getcwdu'):
3287 return os.getcwdu()
3288
3289 return getcwd()
3290
3291
3292
3293 def FindFile(
3294 filename,
3295 sources_paths = [],
3296 fModules = False,
3297 fAllowAnyExt = True
3298 ):
3299
3300 """
3301 FindFile looks for the full path of a script in a rather non-strict
3302 and human like behavior.
3303
3304 ENCODING:
3305 filename should be either Unicode or encoded with sys.getfilesystemencoding()!
3306 Returned value is encoded with sys.getfilesystemencoding().
3307
3308 It will always look for .py or .pyw files even if a .pyc or no
3309 extension is given.
3310
3311 1. It will check against loaded modules if asked.
3312 1. full path (if exists).
3313 2. sources_paths.
3314 2. current path.
3315 3. PYTHONPATH
3316 4. PATH
3317 """
3318
3319 if filename in g_found_unicode_files:
3320 return filename
3321
3322 if filename.startswith('<'):
3323 raise IOError
3324
3325 filename = filename.strip('\'"')
3326 filename = os.path.expanduser(filename)
3327
3328 if fModules and not (os.path.isabs(filename) or filename.startswith('.')):
3329 try:
3330 return winlower(FindFileAsModule(filename))
3331 except IOError:
3332 pass
3333
3334 if fAllowAnyExt:
3335 try:
3336 abspath = FindFile(
3337 filename,
3338 sources_paths,
3339 fModules = False,
3340 fAllowAnyExt = False
3341 )
3342 return abspath
3343 except IOError:
3344 pass
3345
3346 if os.path.isabs(filename) or filename.startswith('.'):
3347 try:
3348 scriptname = None
3349
3350 abspath = my_abspath(filename)
3351 lowered = winlower(abspath)
3352 scriptname = CalcScriptName(lowered, fAllowAnyExt)
3353
3354 if myisfile(scriptname):
3355 return scriptname
3356
3357 #
3358 # Check .pyw files
3359 #
3360 scriptname += 'w'
3361 if scriptname.endswith(PYTHONW_FILE_EXTENSION) and myisfile(scriptname):
3362 return scriptname
3363
3364 scriptname = None
3365 raise IOError
3366
3367 finally:
3368 if not is_py3k() and is_unicode(scriptname):
3369 fse = sys.getfilesystemencoding()
3370 _l = as_string(scriptname, fse)
3371 if '?' in _l:
3372 g_found_unicode_files[_l] = scriptname
3373 return _l
3374
3375 scriptname = CalcScriptName(filename, fAllowAnyExt)
3376
3377 try:
3378 cwd = [getcwd(), getcwdu()]
3379
3380 except UnicodeDecodeError:
3381 #
3382 # This exception can be raised in py3k (alpha) on nt.
3383 #
3384 cwd = [getcwdu()]
3385
3386 env_path = os.environ['PATH']
3387 paths = sources_paths + cwd + g_initial_cwd + sys.path + env_path.split(os.pathsep)
3388
3389 try:
3390 lowered = None
3391
3392 for p in paths:
3393 f = my_os_path_join(p, scriptname)
3394 abspath = my_abspath(f)
3395 lowered = winlower(abspath)
3396
3397 if myisfile(lowered):
3398 return lowered
3399
3400 #
3401 # Check .pyw files
3402 #
3403 lowered += 'w'
3404 if lowered.endswith(PYTHONW_FILE_EXTENSION) and myisfile(lowered):
3405 return lowered
3406
3407 lowered = None
3408 raise IOError
3409
3410 finally:
3411 if not is_py3k() and is_unicode(lowered):
3412 fse = sys.getfilesystemencoding()
3413 _l = as_string(lowered, fse)
3414 if '?' in _l:
3415 g_found_unicode_files[_l] = lowered
3416 return _l
3417
3418
3419
3420 def IsFileInPath(filename):
3421 if filename == '':
3422 return False
3423
3424 try:
3425 FindFile(filename)
3426 return True
3427
3428 except IOError:
3429 return False
3430
3431
3432
3433 def IsPrefixInEnviron(_str):
3434 for e in os.environ.keys():
3435 if e.startswith(_str):
3436 return True
3437
3438 return False
3439
3440
3441
3442 def CalcTerminalCommand():
3443 """
3444 Calc the unix command to start a new terminal, for example: xterm
3445 """
3446
3447 if RPDBTERM in os.environ:
3448 term = os.environ[RPDBTERM]
3449 if IsFileInPath(term):
3450 return term
3451
3452 if COLORTERM in os.environ:
3453 term = os.environ[COLORTERM]
3454 if IsFileInPath(term):
3455 return term
3456
3457 if IsPrefixInEnviron(KDE_PREFIX):
3458 (s, term) = commands.getstatusoutput(KDE_DEFAULT_TERM_QUERY)
3459 if (s == 0) and IsFileInPath(term):
3460 return term
3461
3462 elif IsPrefixInEnviron(GNOME_PREFIX):
3463 if IsFileInPath(GNOME_DEFAULT_TERM):
3464 return GNOME_DEFAULT_TERM
3465
3466 if IsFileInPath(XTERM):
3467 return XTERM
3468
3469 if IsFileInPath(RXVT):
3470 return RXVT
3471
3472 raise SpawnUnsupported
3473
3474
3475
3476 def CalcMacTerminalCommand(command):
3477 """
3478 Calculate what to put in popen to start a given script.
3479 Starts a tiny Applescript that performs the script action.
3480 """
3481
3482 #
3483 # Quoting is a bit tricky; we do it step by step.
3484 # Make Applescript string: put backslashes before double quotes and
3485 # backslashes.
3486 #
3487 command = command.replace('\\', '\\\\').replace('"', '\\"')
3488
3489 #
3490 # Make complete Applescript command.
3491 #
3492 command = 'tell application "Terminal" to do script "%s"' % command
3493
3494 #
3495 # Make a shell single quoted string (put backslashed single quotes
3496 # outside string).
3497 #
3498 command = command.replace("'", "'\\''")
3499
3500 #
3501 # Make complete shell command.
3502 #
3503 return "osascript -e '%s'" % command
3504
3505
3506
3507 def winlower(path):
3508 """
3509 return lowercase version of 'path' on NT systems.
3510
3511 On NT filenames are case insensitive so lowercase filenames
3512 for comparison purposes on NT.
3513 """
3514
3515 if os.name == 'nt':
3516 return path.lower()
3517
3518 return path
3519
3520
3521
3522
3523 def source_provider_blender(filename):
3524 """
3525 Return source code of the file referred by filename.
3526
3527 Support for debugging of Blender Python scripts.
3528 Blender scripts are not always saved on disk, and their
3529 source has to be queried directly from the Blender API.
3530 http://www.blender.org
3531 """
3532
3533 if not 'Blender.Text' in sys.modules:
3534 raise IOError
3535
3536 if filename.startswith('<'):
3537 #
3538 # This specifies blender source whose source is not
3539 # available.
3540 #
3541 raise IOError(BLENDER_SOURCE_NOT_AVAILABLE)
3542
3543 _filename = os.path.basename(filename)
3544
3545 try:
3546 t = sys.modules['Blender.Text'].get(_filename)
3547 lines = t.asLines()
3548 return '\n'.join(lines) + '\n'
3549
3550 except NameError:
3551 f = winlower(_filename)
3552 tlist = sys.modules['Blender.Text'].get()
3553
3554 t = None
3555 for _t in tlist:
3556 n = winlower(_t.getName())
3557 if n == f:
3558 t = _t
3559 break
3560
3561 if t == None:
3562 #
3563 # filename does not specify a blender file. Raise IOError
3564 # so that search can continue on file system.
3565 #
3566 raise IOError
3567
3568 lines = t.asLines()
3569 return '\n'.join(lines) + '\n'
3570
3571
3572
3573 def source_provider_filesystem(filename):
3574 l = mygetfile(filename)
3575
3576 if l[:3] == as_bytes(ENCODING_UTF8_PREFIX_1):
3577 l = l[3:]
3578
3579 return l
3580
3581
3582
3583 def source_provider(filename):
3584 source = None
3585 ffilesystem = False
3586
3587 try:
3588 if g_source_provider_aux != None:
3589 source = g_source_provider_aux(filename)
3590
3591 except IOError:
3592 v = sys.exc_info()[1]
3593 if SOURCE_NOT_AVAILABLE in v.args:
3594 raise
3595
3596 try:
3597 if source == None:
3598 source = source_provider_blender(filename)
3599
3600 except IOError:
3601 v = sys.exc_info()[1]
3602 if BLENDER_SOURCE_NOT_AVAILABLE in v.args:
3603 raise
3604
3605 if source == None:
3606 source = source_provider_filesystem(filename)
3607 ffilesystem = True
3608
3609 encoding = ParseEncoding(source)
3610
3611 if not is_unicode(source):
3612 source = as_unicode(source, encoding)
3613
3614 return source, encoding, ffilesystem
3615
3616
3617
3618 def lines_cache(filename):
3619 filename = g_found_unicode_files.get(filename, filename)
3620
3621 if filename in g_lines_cache:
3622 return g_lines_cache[filename]
3623
3624 (source, encoding, ffilesystem) = source_provider(filename)
3625 source = source.replace(as_unicode('\r\n'), as_unicode('\n'))
3626
3627 lines = source.split(as_unicode('\n'))
3628
3629 g_lines_cache[filename] = (lines, encoding, ffilesystem)
3630
3631 return (lines, encoding, ffilesystem)
3632
3633
3634
3635 def get_source(filename):
3636 (lines, encoding, ffilesystem) = lines_cache(filename)
3637 source = as_unicode('\n').join(lines)
3638
3639 return (source, encoding)
3640
3641
3642
3643 def get_source_line(filename, lineno):
3644 (lines, encoding, ffilesystem) = lines_cache(filename)
3645
3646 if lineno > len(lines):
3647 return as_unicode('')
3648
3649 return lines[lineno - 1] + as_unicode('\n')
3650
3651
3652
3653 def is_provider_filesystem(filename):
3654 try:
3655 (lines, encoding, ffilesystem) = lines_cache(filename)
3656 return ffilesystem
3657
3658 except IOError:
3659 v = sys.exc_info()[1]
3660 return not (BLENDER_SOURCE_NOT_AVAILABLE in v.args or SOURCE_NOT_AVAILABLE in v.args)
3661
3662
3663
3664 def get_file_encoding(filename):
3665 (lines, encoding, ffilesystem) = lines_cache(filename)
3666 return encoding
3667
3668
3669
3670 def ParseLineEncoding(l):
3671 if l.startswith('# -*- coding: '):
3672 e = l[len('# -*- coding: '):].split()[0]
3673 return e
3674
3675 if l.startswith('# vim:fileencoding='):
3676 e = l[len('# vim:fileencoding='):].strip()
3677 return e
3678
3679 return None
3680
3681
3682
3683 def ParseEncoding(txt):
3684 """
3685 Parse document encoding according to:
3686 http://docs.python.org/ref/encodings.html
3687 """
3688
3689 eol = '\n'
3690 if not is_unicode(txt):
3691 eol = as_bytes('\n')
3692
3693 l = txt.split(eol, 20)[:-1]
3694
3695 for line in l:
3696 line = as_unicode(line)
3697 encoding = ParseLineEncoding(line)
3698 if encoding is not None:
3699 try:
3700 codecs.lookup(encoding)
3701 return encoding
3702
3703 except:
3704 return 'utf-8'
3705
3706 return 'utf-8'
3707
3708
3709
3710 def _getpid():
3711 try:
3712 return os.getpid()
3713 except:
3714 return -1
3715
3716
3717
3718 def calcURL(host, port):
3719 """
3720 Form HTTP URL from 'host' and 'port' arguments.
3721 """
3722
3723 url = "http://" + str(host) + ":" + str(port)
3724 return url
3725
3726
3727
3728 def GetSocketError(e):
3729 if (not isinstance(e.args, tuple)) or (len(e.args) == 0):
3730 return -1
3731
3732 return e.args[0]
3733
3734
3735
3736 def ControlRate(t_last_call, max_rate):
3737 """
3738 Limits rate at which this function is called by sleeping.
3739 Returns the time of invocation.
3740 """
3741
3742 p = 1.0 / max_rate
3743 t_current = time.time()
3744 dt = t_current - t_last_call
3745
3746 if dt < p:
3747 time.sleep(p - dt)
3748
3749 return t_current
3750
3751
3752
3753 def generate_rid():
3754 """
3755 Return a 7 digits random id.
3756 """
3757
3758 rid = repr(random.randint(1000000, 9999999))
3759 rid = as_unicode(rid)
3760
3761 return rid
3762
3763
3764
3765 def generate_random_char(_str):
3766 """
3767 Return a random character from string argument.
3768 """
3769
3770 if _str == '':
3771 return ''
3772
3773 i = random.randint(0, len(_str) - 1)
3774 return _str[i]
3775
3776
3777
3778 def generate_random_password():
3779 """
3780 Generate an 8 characters long password.
3781 """
3782
3783 s = 'abdefghijmnqrt' + 'ABDEFGHJLMNQRTY'
3784 ds = '23456789_' + s
3785
3786 _rpdb2_pwd = generate_random_char(s)
3787
3788 for i in range(0, 7):
3789 _rpdb2_pwd += generate_random_char(ds)
3790
3791 _rpdb2_pwd = as_unicode(_rpdb2_pwd)
3792
3793 return _rpdb2_pwd
3794
3795
3796
3797 def is_valid_pwd(_rpdb2_pwd):
3798 if _rpdb2_pwd in [None, '']:
3799 return False
3800
3801 try:
3802 if not is_unicode(_rpdb2_pwd):
3803 _rpdb2_pwd = _rpdb2_pwd.decode('ascii')
3804
3805 _rpdb2_pwd.encode('ascii')
3806
3807 except:
3808 return False
3809
3810 for c in _rpdb2_pwd:
3811 if c.isalnum():
3812 continue
3813
3814 if c == '_':
3815 continue
3816
3817 return False
3818
3819 return True
3820
3821
3822
3823 def is_encryption_supported():
3824 """
3825 Is the Crypto module imported/available.
3826 """
3827
3828 return 'DES' in globals()
3829
3830
3831
3832 def calc_suffix(_str, n):
3833 """
3834 Return an n charaters suffix of the argument string of the form
3835 '...suffix'.
3836 """
3837
3838 if len(_str) <= n:
3839 return _str
3840
3841 return '...' + _str[-(n - 3):]
3842
3843
3844
3845 def calc_prefix(_str, n):
3846 """
3847 Return an n charaters prefix of the argument string of the form
3848 'prefix...'.
3849 """
3850
3851 if len(_str) <= n:
3852 return _str
3853
3854 return _str[: (n - 3)] + '...'
3855
3856
3857
3858 def create_rpdb_settings_folder():
3859 """
3860 Create the settings folder on Posix systems:
3861 '~/.rpdb2_settings' with mode 700.
3862 """
3863
3864 if os.name != POSIX:
3865 return
3866
3867 home = os.path.expanduser('~')
3868
3869 rsf = os.path.join(home, RPDB_SETTINGS_FOLDER)
3870 if not os.path.exists(rsf):
3871 os.mkdir(rsf, int('0700', 8))
3872
3873 pwds = os.path.join(home, RPDB_PWD_FOLDER)
3874 if not os.path.exists(pwds):
3875 os.mkdir(pwds, int('0700', 8))
3876
3877 bpl = os.path.join(home, RPDB_BPL_FOLDER)
3878 if not os.path.exists(bpl):
3879 os.mkdir(bpl, int('0700', 8))
3880
3881
3882
3883 def cleanup_bpl_folder(path):
3884 if random.randint(0, 10) > 0:
3885 return
3886
3887 l = os.listdir(path)
3888 if len(l) < MAX_BPL_FILES:
3889 return
3890
3891 try:
3892 ll = [(os.stat(os.path.join(path, f))[stat.ST_ATIME], f) for f in l]
3893 except:
3894 return
3895
3896 ll.sort()
3897
3898 for (t, f) in ll[: -MAX_BPL_FILES]:
3899 try:
3900 os.remove(os.path.join(path, f))
3901 except:
3902 pass
3903
3904
3905
3906 def calc_bpl_filename(filename):
3907 key = as_bytes(filename)
3908 tmp_filename = hmac.new(key).hexdigest()[:10]
3909
3910 if os.name == POSIX:
3911 home = os.path.expanduser('~')
3912 bpldir = os.path.join(home, RPDB_BPL_FOLDER)
3913 cleanup_bpl_folder(bpldir)
3914 path = os.path.join(bpldir, tmp_filename) + BREAKPOINTS_FILE_EXT
3915 return path
3916
3917 #
3918 # gettempdir() is used since it works with unicode user names on
3919 # Windows.
3920 #
3921
3922 tmpdir = tempfile.gettempdir()
3923 bpldir = os.path.join(tmpdir, RPDB_BPL_FOLDER_NT)
3924
3925 if not os.path.exists(bpldir):
3926 #
3927 # Folder creation is done here since this is a temp folder.
3928 #
3929 try:
3930 os.mkdir(bpldir, int('0700', 8))
3931 except:
3932 print_debug_exception()
3933 raise CException
3934
3935 else:
3936 cleanup_bpl_folder(bpldir)
3937
3938 path = os.path.join(bpldir, tmp_filename) + BREAKPOINTS_FILE_EXT
3939 return path
3940
3941
3942
3943 def calc_pwd_file_path(rid):
3944 """
3945 Calc password file path for Posix systems:
3946 '~/.rpdb2_settings/<rid>'
3947 """
3948
3949 home = os.path.expanduser('~')
3950 rsf = os.path.join(home, RPDB_PWD_FOLDER)
3951 pwd_file_path = os.path.join(rsf, rid)
3952
3953 return pwd_file_path
3954
3955
3956
3957 def create_pwd_file(rid, _rpdb2_pwd):
3958 """
3959 Create password file for Posix systems.
3960 """
3961
3962 if os.name != POSIX:
3963 return
3964
3965 path = calc_pwd_file_path(rid)
3966
3967 fd = os.open(path, os.O_WRONLY | os.O_CREAT, int('0600', 8))
3968
3969 os.write(fd, as_bytes(_rpdb2_pwd))
3970 os.close(fd)
3971
3972
3973
3974 def read_pwd_file(rid):
3975 """
3976 Read password from password file for Posix systems.
3977 """
3978
3979 assert(os.name == POSIX)
3980
3981 path = calc_pwd_file_path(rid)
3982
3983 p = open(path, 'r')
3984 _rpdb2_pwd = p.read()
3985 p.close()
3986
3987 _rpdb2_pwd = as_unicode(_rpdb2_pwd, fstrict = True)
3988
3989 return _rpdb2_pwd
3990
3991
3992
3993 def delete_pwd_file(rid):
3994 """
3995 Delete password file for Posix systems.
3996 """
3997
3998 if os.name != POSIX:
3999 return
4000
4001 path = calc_pwd_file_path(rid)
4002
4003 try:
4004 os.remove(path)
4005 except:
4006 pass
4007
4008
4009
4010 def CalcUserShell():
4011 try:
4012 s = os.getenv('SHELL')
4013 if s != None:
4014 return s
4015
4016 import getpass
4017 username = getpass.getuser()
4018
4019 f = open('/etc/passwd', 'r')
4020 l = f.read()
4021 f.close()
4022
4023 ll = l.split('\n')
4024 d = dict([(e.split(':', 1)[0], e.split(':')[-1]) for e in ll])
4025
4026 return d[username]
4027
4028 except:
4029 return 'sh'
4030
4031
4032
4033 def IsFilteredAttribute(a):
4034 if not (a.startswith('__') and a.endswith('__')):
4035 return False
4036
4037 if a in ['__class__', '__bases__', '__file__', '__doc__', '__name__', '__all__', '__builtins__']:
4038 return False
4039
4040 return True
4041
4042
4043
4044 def IsFilteredAttribute2(r, a):
4045 try:
4046 o = getattr(r, a)
4047 r = parse_type(type(o))
4048
4049 if 'function' in r or 'method' in r or r == 'type':
4050 return True
4051
4052 return False
4053
4054 except:
4055 return False
4056
4057
4058
4059 def CalcFilteredDir(r, filter_level):
4060 d = dir(r)
4061
4062 if 'finfo' in d and parse_type(type(r)) == 'mp_request':
4063 #
4064 # Workaround mod_python segfault in type(req.finfo) by
4065 # removing this attribute from the namespace viewer.
4066 #
4067 d.remove('finfo')
4068
4069 if filter_level == 0:
4070 return d
4071
4072 fd = [a for a in d if not IsFilteredAttribute(a)]
4073
4074 return fd
4075
4076
4077
4078 def CalcIdentity(r, filter_level):
4079 if filter_level == 0:
4080 return r
4081
4082 if not hasattr(r, 'im_func'):
4083 return r
4084
4085 return r.im_func
4086
4087
4088
4089 def getattr_nothrow(o, a):
4090 try:
4091 return getattr(o, a)
4092
4093 except AttributeError:
4094 return ERROR_NO_ATTRIBUTE
4095
4096 except:
4097 print_debug_exception()
4098 return ERROR_NO_ATTRIBUTE
4099
4100
4101
4102 def calc_attribute_list(r, filter_level):
4103 d = CalcFilteredDir(r, filter_level)
4104 rs = set(d)
4105
4106 c = getattr_nothrow(r, '__class__')
4107 if not c is ERROR_NO_ATTRIBUTE:
4108 d = CalcFilteredDir(c, False)
4109 cs = set(d)
4110 s = rs & cs
4111
4112 for e in s:
4113 o1 = getattr_nothrow(r, e)
4114 o2 = getattr_nothrow(c, e)
4115
4116 if o1 is ERROR_NO_ATTRIBUTE or CalcIdentity(o1, filter_level) is CalcIdentity(o2, filter_level):
4117 rs.discard(e)
4118
4119 try:
4120 if filter_level == 1 and getattr(o1, '__self__') is getattr(o2, '__self__'):
4121 rs.discard(e)
4122 except:
4123 pass
4124
4125 bl = getattr_nothrow(r, '__bases__')
4126 if type(bl) == tuple:
4127 for b in bl:
4128 d = CalcFilteredDir(b, False)
4129 bs = set(d)
4130 s = rs & bs
4131
4132 for e in s:
4133 o1 = getattr_nothrow(r, e)
4134 o2 = getattr_nothrow(b, e)
4135
4136 if o1 is ERROR_NO_ATTRIBUTE or CalcIdentity(o1, filter_level) is CalcIdentity(o2, filter_level):
4137 rs.discard(e)
4138
4139 try:
4140 if filter_level == 1 and getattr(o1, '__self__') is getattr(o2, '__self__'):
4141 rs.discard(e)
4142 except:
4143 pass
4144
4145 l = [a for a in rs if (filter_level < 2 or not IsFilteredAttribute2(r, a))]
4146
4147 if hasattr(r, '__class__') and not '__class__' in l:
4148 l = ['__class__'] + l
4149
4150 if hasattr(r, '__bases__') and not '__bases__' in l:
4151 l = ['__bases__'] + l
4152
4153 al = [a for a in l if hasattr(r, a)]
4154
4155 return al
4156
4157
4158
4159 class _RPDB2_FindRepr:
4160 def __init__(self, o, repr_limit):
4161 self.m_object = o
4162 self.m_repr_limit = repr_limit
4163
4164
4165 def __getitem__(self, key):
4166 index = 0
4167 for i in self.m_object:
4168 if repr_ltd(i, self.m_repr_limit, encoding = ENCODING_RAW_I).replace('"', '&quot') == key:
4169 if isinstance(self.m_object, dict):
4170 return self.m_object[i]
4171
4172 return i
4173
4174 index += 1
4175 if index > MAX_SORTABLE_LENGTH:
4176 return None
4177
4178
4179 def __setitem__(self, key, value):
4180 if not isinstance(self.m_object, dict):
4181 return
4182
4183 index = 0
4184 for i in self.m_object:
4185 if repr_ltd(i, self.m_repr_limit, encoding = ENCODING_RAW_I).replace('"', '&quot') == key:
4186 self.m_object[i] = value
4187 return
4188
4189 index += 1
4190 if index > MAX_SORTABLE_LENGTH:
4191 return
4192
4193
4194
4195 #
4196 # Since on Python 3000 the comparison of different types raises exceptions and
4197 # the __cmp__ method was removed, sorting of namespace items is based on
4198 # lexicographic order except for numbers which are sorted normally and appear
4199 # before all other types.
4200 #
4201 def sort(s):
4202 if sys.version_info[:2] == (2, 3):
4203 #
4204 # On Python 2.3 the key parameter is not supported.
4205 #
4206 s.sort(sort_cmp)
4207 return
4208
4209 s.sort(key = sort_key)
4210
4211
4212
4213 def sort_key(e):
4214 if is_py3k() and isinstance(e, numbers.Number):
4215 return (0, e)
4216
4217 if not is_py3k() and operator.isNumberType(e):
4218 return (0, e)
4219
4220 return (1, repr_ltd(e, 256, encoding = ENCODING_RAW_I))
4221
4222
4223
4224 def sort_cmp(x, y):
4225 skx = sort_key(x)
4226 sky = sort_key(y)
4227
4228 return cmp(skx, sky)
4229
4230
4231
4232 def recalc_sys_path(old_pythonpath):
4233 opl = old_pythonpath.split(os.path.pathsep)
4234 del sys.path[1: 1 + len(opl)]
4235
4236 pythonpath = os.environ.get('PYTHONPATH', '')
4237 ppl = pythonpath.split(os.path.pathsep)
4238
4239 for i, p in enumerate(ppl):
4240 abspath = my_abspath(p)
4241 lowered = winlower(abspath)
4242
4243 sys.path.insert(1 + i, lowered)
4244
4245
4246
4247 def calc_signame(signum):
4248 for k, v in vars(signal).items():
4249 if not k.startswith('SIG') or k in ['SIG_IGN', 'SIG_DFL', 'SIGRTMIN', 'SIGRTMAX']:
4250 continue
4251
4252 if v == signum:
4253 return k
4254
4255 return '?'
4256
4257
4258
4259 #
4260 # Similar to traceback.extract_stack() but fixes path with calc_frame_path()
4261 #
4262 def my_extract_stack(f):
4263 if f == None:
4264 return []
4265
4266 try:
4267 g_traceback_lock.acquire()
4268 _s = traceback.extract_stack(f)
4269
4270 finally:
4271 g_traceback_lock.release()
4272
4273 _s.reverse()
4274
4275 s = []
4276 for (p, ln, fn, text) in _s:
4277 path = as_unicode(calc_frame_path(f), sys.getfilesystemencoding())
4278 if text == None:
4279 text = ''
4280
4281 s.append((path, ln, as_unicode(fn), as_unicode(text)))
4282
4283 f = f.f_back
4284 if f == None:
4285 break
4286
4287 s.reverse()
4288 return s
4289
4290
4291
4292
4293 #
4294 # Similar to traceback.extract_tb() but fixes path with calc_frame_path()
4295 #
4296 def my_extract_tb(tb):
4297 try:
4298 g_traceback_lock.acquire()
4299 _s = traceback.extract_tb(tb)
4300
4301 finally:
4302 g_traceback_lock.release()
4303
4304 s = []
4305 for (p, ln, fn, text) in _s:
4306 path = as_unicode(calc_frame_path(tb.tb_frame), sys.getfilesystemencoding())
4307 if text == None:
4308 text = ''
4309
4310 s.append((path, ln, as_unicode(fn), as_unicode(text)))
4311
4312 tb = tb.tb_next
4313 if tb == None:
4314 break
4315
4316 return s
4317
4318
4319
4320 def get_traceback(frame, ctx):
4321 if is_py3k():
4322 if ctx.get_exc_info() != None:
4323 return ctx.get_exc_info()[2]
4324 else:
4325 if frame.f_exc_traceback != None:
4326 return frame.f_exc_traceback
4327
4328 locals = copy.copy(frame.f_locals)
4329 if not 'traceback' in locals:
4330 return None
4331
4332 tb = locals['traceback']
4333 if dir(tb) == ['tb_frame', 'tb_lasti', 'tb_lineno', 'tb_next']:
4334 return tb
4335
4336
4337
4338 class CFirewallTest:
4339 m_port = None
4340 m_thread_server = None
4341 m_thread_client = None
4342 m_lock = threading.RLock()
4343
4344
4345 def __init__(self, fremote = False, timeout = 4):
4346 if fremote:
4347 self.m_loopback = ''
4348 else:
4349 self.m_loopback = LOOPBACK
4350
4351 self.m_timeout = timeout
4352
4353 self.m_result = None
4354
4355 self.m_last_server_error = None
4356 self.m_last_client_error = None
4357
4358
4359 def run(self):
4360 CFirewallTest.m_lock.acquire()
4361
4362 try:
4363 #
4364 # If either the server or client are alive after a timeout
4365 # it means they are blocked by a firewall. Return False.
4366 #
4367 server = CFirewallTest.m_thread_server
4368 if server != None and thread_is_alive(server):
4369 server.join(self.m_timeout * 1.5)
4370 if thread_is_alive(server):
4371 return False
4372
4373 client = CFirewallTest.m_thread_client
4374 if client != None and thread_is_alive(client):
4375 client.join(self.m_timeout * 1.5)
4376 if thread_is_alive(client):
4377 return False
4378
4379 CFirewallTest.m_port = None
4380 self.m_result = None
4381
4382 t0 = time.time()
4383 server = threading.Thread(target = self.__server)
4384 server.start()
4385 CFirewallTest.m_thread_server = server
4386
4387 #
4388 # If server exited or failed to setup after a timeout
4389 # it means it was blocked by a firewall.
4390 #
4391 while CFirewallTest.m_port == None and thread_is_alive(server):
4392 if time.time() - t0 > self.m_timeout * 1.5:
4393 return False
4394
4395 time.sleep(0.1)
4396
4397 if not thread_is_alive(server):
4398 return False
4399
4400 t0 = time.time()
4401 client = threading.Thread(target = self.__client)
4402 client.start()
4403 CFirewallTest.m_thread_client = client
4404
4405 while self.m_result == None and thread_is_alive(client):
4406 if time.time() - t0 > self.m_timeout * 1.5:
4407 return False
4408
4409 time.sleep(0.1)
4410
4411 return self.m_result
4412
4413 finally:
4414 CFirewallTest.m_lock.release()
4415
4416
4417 def __client(self):
4418 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
4419 s.settimeout(self.m_timeout)
4420
4421 try:
4422 try:
4423 s.connect((LOOPBACK, CFirewallTest.m_port))
4424
4425 s.send(as_bytes('Hello, world'))
4426 data = self.__recv(s, 1024)
4427 self.m_result = True
4428
4429 except socket.error:
4430 e = sys.exc_info()[1]
4431 self.m_last_client_error = e
4432 self.m_result = False
4433
4434 finally:
4435 s.close()
4436
4437
4438 def __server(self):
4439 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
4440 s.settimeout(self.m_timeout)
4441
4442 if os.name == POSIX:
4443 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
4444
4445 port = SERVER_PORT_RANGE_START
4446
4447 while True:
4448 try:
4449 s.bind((self.m_loopback, port))
4450 break
4451
4452 except socket.error:
4453 e = sys.exc_info()[1]
4454
4455 if self.__GetSocketError(e) != errno.EADDRINUSE:
4456 self.m_last_server_error = e
4457 s.close()
4458 return
4459
4460 if port >= SERVER_PORT_RANGE_START + SERVER_PORT_RANGE_LENGTH - 1:
4461 self.m_last_server_error = e
4462 s.close()
4463 return
4464
4465 port += 1
4466
4467 CFirewallTest.m_port = port
4468
4469 try:
4470 try:
4471 conn = None
4472 s.listen(1)
4473 conn, addr = s.accept()
4474
4475 while True:
4476 data = self.__recv(conn, 1024)
4477 if not data:
4478 return
4479
4480 conn.send(data)
4481
4482 except socket.error:
4483 e = sys.exc_info()[1]
4484 self.m_last_server_error = e
4485
4486 finally:
4487 if conn != None:
4488 conn.close()
4489 s.close()
4490
4491
4492 def __recv(self, s, len):
4493 t0 = time.time()
4494
4495 while True:
4496 try:
4497 data = s.recv(1024)
4498 return data
4499
4500 except socket.error:
4501 e = sys.exc_info()[1]
4502 if self.__GetSocketError(e) != errno.EWOULDBLOCK:
4503 print_debug('socket error was caught, %s' % repr(e))
4504 raise
4505
4506 if time.time() - t0 > self.m_timeout:
4507 raise
4508
4509 continue
4510
4511
4512 def __GetSocketError(self, e):
4513 if (not isinstance(e.args, tuple)) or (len(e.args) == 0):
4514 return -1
4515
4516 return e.args[0]
4517
4518
4519
4520 #
4521 # ---------------------------------- CThread ---------------------------------------
4522 #
4523
4524
4525
4526 class CThread (threading.Thread):
4527 m_fstop = False
4528 m_threads = {}
4529
4530 m_lock = threading.RLock()
4531 m_id = 0
4532
4533
4534 def __init__(self, name = None, target = None, args = (), shutdown = None):
4535 threading.Thread.__init__(self, name = name, target = target, args = args)
4536
4537 self.m_fstarted = False
4538 self.m_shutdown_callback = shutdown
4539
4540 self.m_id = self.__getId()
4541
4542
4543 def __del__(self):
4544 #print_debug('Destructor called for ' + thread_get_name(self))
4545
4546 #threading.Thread.__del__(self)
4547
4548 if self.m_fstarted:
4549 try:
4550 del CThread.m_threads[self.m_id]
4551 except KeyError:
4552 pass
4553
4554
4555 def start(self):
4556 if CThread.m_fstop:
4557 return
4558
4559 CThread.m_threads[self.m_id] = weakref.ref(self)
4560
4561 if CThread.m_fstop:
4562 del CThread.m_threads[self.m_id]
4563 return
4564
4565 self.m_fstarted = True
4566
4567 threading.Thread.start(self)
4568
4569
4570 def run(self):
4571 sys.settrace(None)
4572 sys.setprofile(None)
4573
4574 threading.Thread.run(self)
4575
4576
4577 def join(self, timeout = None):
4578 try:
4579 threading.Thread.join(self, timeout)
4580 except AssertionError:
4581 pass
4582
4583
4584 def shutdown(self):
4585 if self.m_shutdown_callback:
4586 self.m_shutdown_callback()
4587
4588
4589 def joinAll(cls):
4590 print_debug('Shutting down debugger threads...')
4591
4592 CThread.m_fstop = True
4593
4594 for tid, w in list(CThread.m_threads.items()):
4595 t = w()
4596 if not t:
4597 continue
4598
4599 try:
4600 #print_debug('Calling shutdown of thread %s.' % thread_get_name(t))
4601 t.shutdown()
4602 except:
4603 pass
4604
4605 t = None
4606
4607 t0 = time.time()
4608
4609 while len(CThread.m_threads) > 0:
4610 if time.time() - t0 > SHUTDOWN_TIMEOUT:
4611 print_debug('Shut down of debugger threads has TIMED OUT!')
4612 return
4613
4614 #print_debug(repr(CThread.m_threads))
4615 time.sleep(0.1)
4616
4617 print_debug('Shut down debugger threads, done.')
4618
4619 joinAll = classmethod(joinAll)
4620
4621
4622 def clearJoin(cls):
4623 CThread.m_fstop = False
4624
4625 clearJoin = classmethod(clearJoin)
4626
4627
4628 def __getId(self):
4629 CThread.m_lock.acquire()
4630 id = CThread.m_id
4631 CThread.m_id += 1
4632 CThread.m_lock.release()
4633
4634 return id
4635
4636
4637
4638 #
4639 #--------------------------------------- Crypto ---------------------------------------
4640 #
4641
4642
4643
4644 class CCrypto:
4645 """
4646 Handle authentication and encryption of data, using password protection.
4647 """
4648
4649 m_keys = {}
4650
4651 def __init__(self, _rpdb2_pwd, fAllowUnencrypted, rid):
4652 assert(is_unicode(_rpdb2_pwd))
4653 assert(is_unicode(rid))
4654
4655 self.m_rpdb2_pwd = _rpdb2_pwd
4656 self.m_key = self.__calc_key(_rpdb2_pwd)
4657
4658 self.m_fAllowUnencrypted = fAllowUnencrypted
4659 self.m_rid = rid
4660
4661 self.m_failure_lock = threading.RLock()
4662
4663 self.m_lock = threading.RLock()
4664
4665 self.m_index_anchor_in = random.randint(0, 1000000000)
4666 self.m_index_anchor_ex = 0
4667
4668 self.m_index = 0
4669 self.m_index_table = {}
4670 self.m_index_table_size = INDEX_TABLE_SIZE
4671 self.m_max_index = 0
4672
4673
4674 def __calc_key(self, _rpdb2_pwd):
4675 """
4676 Create and return a key from a password.
4677 A Weak password means a weak key.
4678 """
4679
4680 if _rpdb2_pwd in CCrypto.m_keys:
4681 return CCrypto.m_keys[_rpdb2_pwd]
4682
4683 key = as_bytes(_rpdb2_pwd)
4684 suffix = key[:16]
4685
4686 d = hmac.new(key, digestmod = _md5)
4687
4688 #
4689 # The following loop takes around a second to complete
4690 # and should strengthen the password by ~12 bits.
4691 # a good password is ~30 bits strong so we are looking
4692 # at ~42 bits strong key
4693 #
4694 for i in range(2 ** 12):
4695 d.update((key + suffix) * 16)
4696 key = d.digest()
4697
4698 CCrypto.m_keys[_rpdb2_pwd] = key
4699
4700 return key
4701
4702
4703 def set_index(self, i, anchor):
4704 try:
4705 self.m_lock.acquire()
4706
4707 self.m_index = i
4708 self.m_index_anchor_ex = anchor
4709
4710 finally:
4711 self.m_lock.release()
4712
4713
4714 def get_max_index(self):
4715 return self.m_max_index
4716
4717
4718 def do_crypto(self, args, fencrypt):
4719 """
4720 Sign args and possibly encrypt.
4721 Return signed/encrypted string.
4722 """
4723
4724 if not fencrypt and not self.m_fAllowUnencrypted:
4725 raise EncryptionExpected
4726
4727 if fencrypt and not is_encryption_supported():
4728 raise EncryptionNotSupported
4729
4730 (digest, s) = self.__sign(args)
4731
4732 fcompress = False
4733
4734 if len(s) > 50000:
4735 _s = zlib.compress(s)
4736
4737 if len(_s) < len(s) * 0.4:
4738 s = _s
4739 fcompress = True
4740
4741 if fencrypt:
4742 s = self.__encrypt(s)
4743
4744 s = base64.encodestring(s)
4745 u = as_unicode(s)
4746
4747 return (fcompress, digest, u)
4748
4749
4750 def undo_crypto(self, fencrypt, fcompress, digest, msg, fVerifyIndex = True):
4751 """
4752 Take crypto string, verify its signature and decrypt it, if
4753 needed.
4754 """
4755
4756 if not fencrypt and not self.m_fAllowUnencrypted:
4757 raise EncryptionExpected
4758
4759 if fencrypt and not is_encryption_supported():
4760 raise EncryptionNotSupported
4761
4762 s = as_bytes(msg)
4763 s = base64.decodestring(s)
4764
4765 if fencrypt:
4766 s = self.__decrypt(s)
4767
4768 if fcompress:
4769 s = zlib.decompress(s)
4770
4771 args, id = self.__verify_signature(digest, s, fVerifyIndex)
4772
4773 return (args, id)
4774
4775
4776 def __encrypt(self, s):
4777 s_padded = s + as_bytes('\x00') * (DES.block_size - (len(s) % DES.block_size))
4778
4779 key_padded = (self.m_key + as_bytes('0') * (DES.key_size - (len(self.m_key) % DES.key_size)))[:DES.key_size]
4780 iv = '0' * DES.block_size
4781
4782 d = DES.new(key_padded, DES.MODE_CBC, iv)
4783 r = d.encrypt(s_padded)
4784
4785 return r
4786
4787
4788 def __decrypt(self, s):
4789 try:
4790 key_padded = (self.m_key + as_bytes('0') * (DES.key_size - (len(self.m_key) % DES.key_size)))[:DES.key_size]
4791 iv = '0' * DES.block_size
4792
4793 d = DES.new(key_padded, DES.MODE_CBC, iv)
4794 _s = d.decrypt(s).strip(as_bytes('\x00'))
4795
4796 return _s
4797
4798 except:
4799 self.__wait_a_little()
4800 raise DecryptionFailure
4801
4802
4803 def __sign(self, args):
4804 i = self.__get_next_index()
4805 pack = (self.m_index_anchor_ex, i, self.m_rid, args)
4806
4807 #print_debug('***** 1' + repr(args)[:50])
4808 s = pickle.dumps(pack, 2)
4809 #print_debug('***** 2' + repr(args)[:50])
4810
4811 h = hmac.new(self.m_key, s, digestmod = _md5)
4812 d = h.hexdigest()
4813
4814 #if 'coding:' in s:
4815 # print_debug('%s, %s, %s\n\n==========\n\n%s' % (len(s), d, repr(args), repr(s)))
4816
4817 return (d, s)
4818
4819
4820 def __get_next_index(self):
4821 try:
4822 self.m_lock.acquire()
4823
4824 self.m_index += 1
4825 return self.m_index
4826
4827 finally:
4828 self.m_lock.release()
4829
4830
4831 def __verify_signature(self, digest, s, fVerifyIndex):
4832 try:
4833 h = hmac.new(self.m_key, s, digestmod = _md5)
4834 d = h.hexdigest()
4835
4836 #if 'coding:' in s:
4837 # print_debug('%s, %s, %s, %s' % (len(s), digest, d, repr(s)))
4838
4839 if d != digest:
4840 self.__wait_a_little()
4841 raise AuthenticationFailure
4842
4843 pack = pickle.loads(s)
4844 (anchor, i, id, args) = pack
4845
4846 except AuthenticationFailure:
4847 raise
4848
4849 except:
4850 print_debug_exception()
4851 self.__wait_a_little()
4852 raise AuthenticationBadData
4853
4854 if fVerifyIndex:
4855 self.__verify_index(anchor, i, id)
4856
4857 return args, id
4858
4859
4860 def __verify_index(self, anchor, i, id):
4861 """
4862 Manage messages ids to prevent replay of old messages.
4863 """
4864
4865 try:
4866 try:
4867 self.m_lock.acquire()
4868
4869 if anchor != self.m_index_anchor_in:
4870 raise AuthenticationBadIndex(self.m_max_index, self.m_index_anchor_in)
4871
4872 if i > self.m_max_index + INDEX_TABLE_SIZE // 2:
4873 raise AuthenticationBadIndex(self.m_max_index, self.m_index_anchor_in)
4874
4875 i_mod = i % INDEX_TABLE_SIZE
4876 (iv, idl) = self.m_index_table.get(i_mod, (None, None))
4877
4878 #print >> sys.__stderr__, i, i_mod, iv, self.m_max_index
4879
4880 if (iv is None) or (i > iv):
4881 idl = [id]
4882 elif (iv == i) and (not id in idl):
4883 idl.append(id)
4884 else:
4885 raise AuthenticationBadIndex(self.m_max_index, self.m_index_anchor_in)
4886
4887 self.m_index_table[i_mod] = (i, idl)
4888
4889 if i > self.m_max_index:
4890 self.m_max_index = i
4891
4892 return self.m_index
4893
4894 finally:
4895 self.m_lock.release()
4896
4897 except:
4898 self.__wait_a_little()
4899 raise
4900
4901
4902 def __wait_a_little(self):
4903 self.m_failure_lock.acquire()
4904 time.sleep((1.0 + random.random()) / 2)
4905 self.m_failure_lock.release()
4906
4907
4908
4909 #
4910 # --------------------------------- Events List --------------------------
4911 #
4912
4913
4914
4915 class CEvent(object):
4916 """
4917 Base class for events.
4918 """
4919
4920 def __reduce__(self):
4921 rv = (copy_reg.__newobj__, (type(self), ), vars(self), None, None)
4922 return rv
4923
4924
4925 def is_match(self, arg):
4926 pass
4927
4928
4929
4930 class CEventNull(CEvent):
4931 """
4932 Sent to release event listeners (Internal, speeds up shutdown).
4933 """
4934
4935 pass
4936
4937
4938
4939 class CEventEmbeddedSync(CEvent):
4940 """
4941 Sent when an embedded interpreter becomes active if it needs to
4942 determine if there are pending break requests. (Internal)
4943 """
4944
4945 pass
4946
4947
4948
4949 class CEventClearSourceCache(CEvent):
4950 """
4951 Sent when the source cache is cleared.
4952 """
4953
4954 pass
4955
4956
4957
4958 class CEventSignalIntercepted(CEvent):
4959 """
4960 This event is sent when a signal is intercepted inside tracing code.
4961 Such signals are held pending until tracing code is returned from.
4962 """
4963
4964 def __init__(self, signum):
4965 self.m_signum = signum
4966 self.m_signame = calc_signame(signum)
4967
4968
4969
4970 class CEventSignalException(CEvent):
4971 """
4972 This event is sent when the handler of a previously intercepted signal
4973 raises an exception. Such exceptions are ignored because of technical
4974 limitations.
4975 """
4976
4977 def __init__(self, signum, description):
4978 self.m_signum = signum
4979 self.m_signame = calc_signame(signum)
4980 self.m_description = description
4981
4982
4983
4984 class CEventEncoding(CEvent):
4985 """
4986 The encoding has been set.
4987 """
4988
4989 def __init__(self, encoding, fraw):
4990 self.m_encoding = encoding
4991 self.m_fraw = fraw
4992
4993
4994
4995 class CEventPsycoWarning(CEvent):
4996 """
4997 The psyco module was detected. rpdb2 is incompatible with this module.
4998 """
4999
5000 pass
5001
5002
5003
5004 class CEventConflictingModules(CEvent):
5005 """
5006 Conflicting modules were detected. rpdb2 is incompatible with these modules.
5007 """
5008
5009 def __init__(self, modules_list):
5010 self.m_modules_list = modules_list
5011
5012
5013
5014 class CEventSyncReceivers(CEvent):
5015 """
5016 A base class for events that need to be received by all listeners at
5017 the same time. The synchronization mechanism is internal to rpdb2.
5018 """
5019
5020 def __init__(self, sync_n):
5021 self.m_sync_n = sync_n
5022
5023
5024
5025 class CEventForkSwitch(CEventSyncReceivers):
5026 """
5027 Debuggee is about to fork. Try to reconnect.
5028 """
5029
5030 pass
5031
5032
5033
5034 class CEventExecSwitch(CEventSyncReceivers):
5035 """
5036 Debuggee is about to exec. Try to reconnect.
5037 """
5038
5039 pass
5040
5041
5042
5043 class CEventExit(CEvent):
5044 """
5045 Debuggee is terminating.
5046 """
5047
5048 pass
5049
5050
5051
5052 class CEventState(CEvent):
5053 """
5054 State of the debugger.
5055 Value of m_state can be one of the STATE_* globals.
5056 """
5057
5058 def __init__(self, state):
5059 self.m_state = as_unicode(state)
5060
5061
5062 def is_match(self, arg):
5063 return self.m_state == as_unicode(arg)
5064
5065
5066
5067 class CEventSynchronicity(CEvent):
5068 """
5069 Mode of synchronicity.
5070 Sent when mode changes.
5071 """
5072
5073 def __init__(self, fsynchronicity):
5074 self.m_fsynchronicity = fsynchronicity
5075
5076
5077 def is_match(self, arg):
5078 return self.m_fsynchronicity == arg
5079
5080
5081
5082 class CEventTrap(CEvent):
5083 """
5084 Mode of "trap unhandled exceptions".
5085 Sent when the mode changes.
5086 """
5087
5088 def __init__(self, ftrap):
5089 self.m_ftrap = ftrap
5090
5091
5092 def is_match(self, arg):
5093 return self.m_ftrap == arg
5094
5095
5096
5097 class CEventForkMode(CEvent):
5098 """
5099 Mode of fork behavior has changed.
5100 Sent when the mode changes.
5101 """
5102
5103 def __init__(self, ffork_into_child, ffork_auto):
5104 self.m_ffork_into_child = ffork_into_child
5105 self.m_ffork_auto = ffork_auto
5106
5107
5108
5109 class CEventUnhandledException(CEvent):
5110 """
5111 Unhandled Exception
5112 Sent when an unhandled exception is caught.
5113 """
5114
5115
5116
5117 class CEventNamespace(CEvent):
5118 """
5119 Namespace has changed.
5120 This tells the debugger it should query the namespace again.
5121 """
5122
5123 pass
5124
5125
5126
5127 class CEventNoThreads(CEvent):
5128 """
5129 No threads to debug.
5130 Debuggee notifies the debugger that it has no threads. This can
5131 happen in embedded debugging and in a python interpreter session.
5132 """
5133
5134 pass
5135
5136
5137
5138 class CEventThreads(CEvent):
5139 """
5140 State of threads.
5141 """
5142
5143 def __init__(self, _current_thread, thread_list):
5144 self.m_current_thread = _current_thread
5145 self.m_thread_list = thread_list
5146
5147
5148
5149 class CEventThreadBroken(CEvent):
5150 """
5151 A thread has broken.
5152 """
5153
5154 def __init__(self, tid, name):
5155 self.m_tid = tid
5156 self.m_name = as_unicode(name)
5157
5158
5159
5160 class CEventStack(CEvent):
5161 """
5162 Stack of current thread.
5163 """
5164
5165 def __init__(self, stack):
5166 self.m_stack = stack
5167
5168
5169
5170 class CEventStackFrameChange(CEvent):
5171 """
5172 Stack frame has changed.
5173 This event is sent when the debugger goes up or down the stack.
5174 """
5175
5176 def __init__(self, frame_index):
5177 self.m_frame_index = frame_index
5178
5179
5180
5181 class CEventStackDepth(CEvent):
5182 """
5183 Stack depth has changed.
5184 """
5185
5186 def __init__(self, stack_depth, stack_depth_exception):
5187 self.m_stack_depth = stack_depth
5188 self.m_stack_depth_exception = stack_depth_exception
5189
5190
5191
5192 class CEventBreakpoint(CEvent):
5193 """
5194 A breakpoint or breakpoints changed.
5195 """
5196
5197 DISABLE = as_unicode('disable')
5198 ENABLE = as_unicode('enable')
5199 REMOVE = as_unicode('remove')
5200 SET = as_unicode('set')
5201
5202 def __init__(self, bp, action = SET, id_list = [], fAll = False):
5203 self.m_bp = breakpoint_copy(bp)
5204 self.m_action = action
5205 self.m_id_list = id_list
5206 self.m_fAll = fAll
5207
5208
5209
5210 class CEventSync(CEvent):
5211 """
5212 Internal (not sent to the debugger) event that trigers the
5213 firing of other events that help the debugger synchronize with
5214 the state of the debuggee.
5215 """
5216
5217 def __init__(self, fException, fSendUnhandled):
5218 self.m_fException = fException
5219 self.m_fSendUnhandled = fSendUnhandled
5220
5221
5222
5223 #
5224 # --------------------------------- Event Manager --------------------------
5225 #
5226
5227
5228
5229 class CEventDispatcherRecord:
5230 """
5231 Internal structure that binds a callback to particular events.
5232 """
5233
5234 def __init__(self, callback, event_type_dict, fSingleUse):
5235 self.m_callback = callback
5236 self.m_event_type_dict = copy.copy(event_type_dict)
5237 self.m_fSingleUse = fSingleUse
5238
5239
5240 def is_match(self, event):
5241 rtl = [t for t in self.m_event_type_dict.keys() if isinstance(event, t)]
5242 if len(rtl) == 0:
5243 return False
5244
5245 #
5246 # Examine first match only.
5247 #
5248
5249 rt = rtl[0]
5250 rte = self.m_event_type_dict[rt].get(EVENT_EXCLUDE, [])
5251 if len(rte) != 0:
5252 for e in rte:
5253 if event.is_match(e):
5254 return False
5255 return True
5256
5257 rte = self.m_event_type_dict[rt].get(EVENT_INCLUDE, [])
5258 if len(rte) != 0:
5259 for e in rte:
5260 if event.is_match(e):
5261 return True
5262 return False
5263
5264 return True
5265
5266
5267
5268 class CEventDispatcher:
5269 """
5270 Events dispatcher.
5271 Dispatchers can be chained together.
5272 """
5273
5274 def __init__(self, chained_event_dispatcher = None):
5275 self.m_chained_event_dispatcher = chained_event_dispatcher
5276 self.m_chain_override_types = {}
5277
5278 self.m_registrants = {}
5279
5280
5281 def shutdown(self):
5282 for er in list(self.m_registrants.keys()):
5283 self.__remove_dispatcher_record(er)
5284
5285
5286 def register_callback(self, callback, event_type_dict, fSingleUse):
5287 er = CEventDispatcherRecord(callback, event_type_dict, fSingleUse)
5288
5289 #
5290 # If we have a chained dispatcher, register the callback on the
5291 # chained dispatcher as well.
5292 #
5293 if self.m_chained_event_dispatcher is not None:
5294 _er = self.__register_callback_on_chain(er, event_type_dict, fSingleUse)
5295 self.m_registrants[er] = _er
5296 return er
5297
5298 self.m_registrants[er] = True
5299 return er
5300
5301
5302 def remove_callback(self, callback):
5303 erl = [er for er in list(self.m_registrants.keys()) if er.m_callback == callback]
5304 for er in erl:
5305 self.__remove_dispatcher_record(er)
5306
5307
5308 def fire_events(self, event_list):
5309 for event in event_list:
5310 self.fire_event(event)
5311
5312
5313 def fire_event(self, event):
5314 for er in list(self.m_registrants.keys()):
5315 self.__fire_er(event, er)
5316
5317
5318 def __fire_er(self, event, er):
5319 if not er.is_match(event):
5320 return
5321
5322 try:
5323 er.m_callback(event)
5324 except:
5325 pass
5326
5327 if not er.m_fSingleUse:
5328 return
5329
5330 try:
5331 del self.m_registrants[er]
5332 except KeyError:
5333 pass
5334
5335
5336 def register_chain_override(self, event_type_dict):
5337 """
5338 Chain override prevents registration on chained
5339 dispatchers for specific event types.
5340 """
5341
5342 for t in list(event_type_dict.keys()):
5343 self.m_chain_override_types[t] = True
5344
5345
5346 def __register_callback_on_chain(self, er, event_type_dict, fSingleUse):
5347 _event_type_dict = copy.copy(event_type_dict)
5348 for t in self.m_chain_override_types:
5349 if t in _event_type_dict:
5350 del _event_type_dict[t]
5351
5352 if len(_event_type_dict) == 0:
5353 return False
5354
5355
5356 def callback(event, er = er):
5357 self.__fire_er(event, er)
5358
5359 _er = self.m_chained_event_dispatcher.register_callback(callback, _event_type_dict, fSingleUse)
5360 return _er
5361
5362
5363 def __remove_dispatcher_record(self, er):
5364 try:
5365 if self.m_chained_event_dispatcher is not None:
5366 _er = self.m_registrants[er]
5367 if _er != False:
5368 self.m_chained_event_dispatcher.__remove_dispatcher_record(_er)
5369
5370 del self.m_registrants[er]
5371
5372 except KeyError:
5373 pass
5374
5375
5376
5377 class CEventQueue:
5378 """
5379 Add queue semantics above an event dispatcher.
5380 Instead of firing event callbacks, new events are returned in a list
5381 upon request.
5382 """
5383
5384 def __init__(self, event_dispatcher, max_event_list_length = MAX_EVENT_LIST_LENGTH):
5385 self.m_event_dispatcher = event_dispatcher
5386
5387 self.m_event_lock = threading.Condition()
5388 self.m_max_event_list_length = max_event_list_length
5389 self.m_event_list = []
5390 self.m_event_index = 0
5391
5392 self.m_n_waiters = []
5393
5394
5395 def shutdown(self):
5396 self.m_event_dispatcher.remove_callback(self.event_handler)
5397
5398
5399 def register_event_types(self, event_type_dict):
5400 self.m_event_dispatcher.register_callback(self.event_handler, event_type_dict, fSingleUse = False)
5401
5402
5403 def event_handler(self, event):
5404 try:
5405 self.m_event_lock.acquire()
5406
5407 if isinstance(event, CEventSyncReceivers):
5408 t0 = time.time()
5409 while len(self.m_n_waiters) < event.m_sync_n and time.time() < t0 + HEARTBEAT_TIMEOUT:
5410 time.sleep(0.1)
5411
5412 self.m_event_list.append(event)
5413 if len(self.m_event_list) > self.m_max_event_list_length:
5414 self.m_event_list.pop(0)
5415
5416 self.m_event_index += 1
5417 lock_notify_all(self.m_event_lock)
5418
5419 finally:
5420 self.m_event_lock.release()
5421
5422
5423 def get_event_index(self):
5424 return self.m_event_index
5425
5426
5427 def wait_for_event(self, timeout, event_index):
5428 """
5429 Return the new events which were fired.
5430 """
5431
5432 try:
5433 self.m_n_waiters.append(0)
5434
5435 self.m_event_lock.acquire()
5436 if event_index >= self.m_event_index:
5437 safe_wait(self.m_event_lock, timeout)
5438
5439 if event_index >= self.m_event_index:
5440 return (self.m_event_index, [])
5441
5442 sub_event_list = self.m_event_list[event_index - self.m_event_index:]
5443 return (self.m_event_index, sub_event_list)
5444
5445 finally:
5446 self.m_n_waiters.pop()
5447
5448 self.m_event_lock.release()
5449
5450
5451
5452 class CStateManager:
5453 """
5454 Manage possible debugger states (broken, running, etc...)
5455
5456 The state manager can receive state changes via an input event
5457 dispatcher or via the set_state() method
5458
5459 It sends state changes forward to the output event dispatcher.
5460
5461 The state can also be queried or waited for.
5462 """
5463
5464 def __init__(self, initial_state, event_dispatcher_output = None, event_dispatcher_input = None):
5465 self.m_event_dispatcher_input = event_dispatcher_input
5466 self.m_event_dispatcher_output = event_dispatcher_output
5467
5468 if self.m_event_dispatcher_input is not None:
5469 event_type_dict = {CEventState: {}}
5470 self.m_event_dispatcher_input.register_callback(self.event_handler, event_type_dict, fSingleUse = False)
5471
5472 if self.m_event_dispatcher_output is not None:
5473 self.m_event_dispatcher_output.register_chain_override(event_type_dict)
5474
5475 self.m_state_lock = threading.Condition()
5476
5477 self.m_state_queue = []
5478 self.m_state_index = 0
5479 self.m_waiter_list = {}
5480
5481 self.set_state(initial_state)
5482
5483
5484 def shutdown(self):
5485 if self.m_event_dispatcher_input is not None:
5486 self.m_event_dispatcher_input.remove_callback(self.event_handler)
5487
5488
5489 def event_handler(self, event):
5490 self.set_state(event.m_state)
5491
5492
5493 def get_state(self):
5494 return self.m_state_queue[-1]
5495
5496
5497 def __add_state(self, state):
5498 self.m_state_queue.append(state)
5499 self.m_state_index += 1
5500
5501 self.__remove_states()
5502
5503
5504 def __remove_states(self, treshold = None):
5505 """
5506 Clean up old state changes from the state queue.
5507 """
5508
5509 index = self.__calc_min_index()
5510
5511 if (treshold is not None) and (index <= treshold):
5512 return
5513
5514 _delta = 1 + self.m_state_index - index
5515
5516 self.m_state_queue = self.m_state_queue[-_delta:]
5517
5518
5519 def __calc_min_index(self):
5520 """
5521 Calc the minimum state index.
5522 The calculated index is the oldest state of which all state
5523 waiters are aware of. That is, no one cares for older states
5524 and these can be removed from the state queue.
5525 """
5526
5527 if len(self.m_waiter_list) == 0:
5528 return self.m_state_index
5529
5530 index_list = list(self.m_waiter_list.keys())
5531 min_index = min(index_list)
5532
5533 return min_index
5534
5535
5536 def __add_waiter(self):
5537 index = self.m_state_index
5538 n = self.m_waiter_list.get(index, 0)
5539 self.m_waiter_list[index] = n + 1
5540
5541 return index
5542
5543
5544 def __remove_waiter(self, index):
5545 n = self.m_waiter_list[index]
5546 if n == 1:
5547 del self.m_waiter_list[index]
5548 self.__remove_states(index)
5549 else:
5550 self.m_waiter_list[index] = n - 1
5551
5552
5553 def __get_states(self, index):
5554 _delta = 1 + self.m_state_index - index
5555 states = self.m_state_queue[-_delta:]
5556 return states
5557
5558
5559 def set_state(self, state = None, fLock = True):
5560 try:
5561 if fLock:
5562 self.m_state_lock.acquire()
5563
5564 if state is None:
5565 state = self.get_state()
5566
5567 self.__add_state(state)
5568
5569 lock_notify_all(self.m_state_lock)
5570
5571 finally:
5572 if fLock:
5573 self.m_state_lock.release()
5574
5575 if self.m_event_dispatcher_output is not None:
5576 event = CEventState(state)
5577 self.m_event_dispatcher_output.fire_event(event)
5578
5579
5580 def wait_for_state(self, state_list):
5581 """
5582 Wait for any of the states in the state list.
5583 """
5584
5585 try:
5586 self.m_state_lock.acquire()
5587
5588 if self.get_state() in state_list:
5589 return self.get_state()
5590
5591 while True:
5592 index = self.__add_waiter()
5593
5594 alertable_wait(self.m_state_lock, PING_TIMEOUT)
5595
5596 states = self.__get_states(index)
5597 self.__remove_waiter(index)
5598
5599 for state in states:
5600 if state in state_list:
5601 return state
5602
5603 finally:
5604 self.m_state_lock.release()
5605
5606
5607 def acquire(self):
5608 self.m_state_lock.acquire()
5609
5610
5611 def release(self):
5612 self.m_state_lock.release()
5613
5614
5615
5616 #
5617 # -------------------------------------- Break Info manager ---------------------------------------
5618 #
5619
5620
5621
5622 def myord(c):
5623 try:
5624 return ord(c)
5625 except:
5626 return c
5627
5628
5629
5630 def CalcValidLines(code):
5631 l = code.co_firstlineno
5632 vl = [l]
5633
5634 bl = [myord(c) for c in code.co_lnotab[2::2]]
5635 sl = [myord(c) for c in code.co_lnotab[1::2]]
5636
5637 for (bi, si) in zip(bl, sl):
5638 l += si
5639
5640 if bi == 0:
5641 continue
5642
5643 if l != vl[-1]:
5644 vl.append(l)
5645
5646 if len(sl) > 0:
5647 l += sl[-1]
5648
5649 if l != vl[-1]:
5650 vl.append(l)
5651
5652 return vl
5653
5654
5655
5656 class CScopeBreakInfo:
5657 def __init__(self, fqn, valid_lines):
5658 self.m_fqn = fqn
5659 self.m_first_line = valid_lines[0]
5660 self.m_last_line = valid_lines[-1]
5661 self.m_valid_lines = valid_lines
5662
5663
5664 def CalcScopeLine(self, lineno):
5665 rvl = copy.copy(self.m_valid_lines)
5666 rvl.reverse()
5667
5668 for l in rvl:
5669 if lineno >= l:
5670 break
5671
5672 return l
5673
5674
5675 def __str__(self):
5676 return "('" + self.m_fqn + "', " + str(self.m_valid_lines) + ')'
5677
5678
5679
5680 class CFileBreakInfo:
5681 """
5682 Break info structure for a source file.
5683 """
5684
5685 def __init__(self, filename):
5686 self.m_filename = filename
5687 self.m_first_line = 0
5688 self.m_last_line = 0
5689 self.m_scope_break_info = []
5690
5691
5692 def CalcBreakInfo(self):
5693 (source, encoding) = get_source(self.m_filename)
5694 _source = as_string(source + as_unicode('\n'), encoding)
5695
5696 code = compile(_source, self.m_filename, "exec")
5697
5698 self.m_scope_break_info = []
5699 self.m_first_line = code.co_firstlineno
5700 self.m_last_line = 0
5701
5702 fqn = []
5703 t = [code]
5704
5705 while len(t) > 0:
5706 c = t.pop(0)
5707
5708 if type(c) == tuple:
5709 self.m_scope_break_info.append(CScopeBreakInfo(*c))
5710 fqn.pop()
5711 continue
5712
5713 fqn = fqn + [c.co_name]
5714 valid_lines = CalcValidLines(c)
5715 self.m_last_line = max(self.m_last_line, valid_lines[-1])
5716 _fqn = as_unicode('.'.join(fqn), encoding)
5717 si = (_fqn, valid_lines)
5718 subcodeslist = self.__CalcSubCodesList(c)
5719 t = subcodeslist + [si] + t
5720
5721
5722 def __CalcSubCodesList(self, code):
5723 tc = type(code)
5724 t = [(c.co_firstlineno, c) for c in code.co_consts if type(c) == tc]
5725 t.sort()
5726 scl = [c[1] for c in t]
5727 return scl
5728
5729
5730 def FindScopeByLineno(self, lineno):
5731 lineno = max(min(lineno, self.m_last_line), self.m_first_line)
5732
5733 smaller_element = None
5734 exact_element = None
5735
5736 for sbi in self.m_scope_break_info:
5737 if lineno > sbi.m_last_line:
5738 if (smaller_element is None) or (sbi.m_last_line >= smaller_element.m_last_line):
5739 smaller_element = sbi
5740 continue
5741
5742 if (lineno >= sbi.m_first_line) and (lineno <= sbi.m_last_line):
5743 exact_element = sbi
5744 break
5745
5746 assert(exact_element is not None)
5747
5748 scope = exact_element
5749 l = exact_element.CalcScopeLine(lineno)
5750
5751 if (smaller_element is not None) and (l <= smaller_element.m_last_line):
5752 scope = smaller_element
5753 l = smaller_element.CalcScopeLine(lineno)
5754
5755 return (scope, l)
5756
5757
5758 def FindScopeByName(self, name, offset):
5759 if name.startswith(MODULE_SCOPE):
5760 alt_scope = MODULE_SCOPE2 + name[len(MODULE_SCOPE):]
5761 elif name.startswith(MODULE_SCOPE2):
5762 alt_scope = MODULE_SCOPE + name[len(MODULE_SCOPE2):]
5763 else:
5764 return self.FindScopeByName(MODULE_SCOPE2 + SCOPE_SEP + name, offset)
5765
5766 for sbi in self.m_scope_break_info:
5767 if sbi.m_fqn in [name, alt_scope]:
5768 l = sbi.CalcScopeLine(sbi.m_first_line + offset)
5769 return (sbi, l)
5770
5771 print_debug('Invalid scope: %s' % repr(name))
5772
5773 raise InvalidScopeName
5774
5775
5776
5777 class CBreakInfoManager:
5778 """
5779 Manage break info dictionary per filename.
5780 """
5781
5782 def __init__(self):
5783 self.m_file_info_dic = {}
5784
5785
5786 def addFile(self, filename):
5787 mbi = CFileBreakInfo(filename)
5788 mbi.CalcBreakInfo()
5789 self.m_file_info_dic[filename] = mbi
5790
5791
5792 def getFile(self, filename):
5793 if not filename in self.m_file_info_dic:
5794 self.addFile(filename)
5795
5796 return self.m_file_info_dic[filename]
5797
5798
5799
5800 #
5801 # -------------------------------- Break Point Manager -----------------------------
5802 #
5803
5804
5805
5806 def breakpoint_copy(bp):
5807 if bp is None:
5808 return None
5809
5810 _bp = copy.copy(bp)
5811
5812 #filename = g_found_unicode_files.get(bp.m_filename, bp.m_filename)
5813
5814 _bp.m_filename = as_unicode(bp.m_filename, sys.getfilesystemencoding())
5815 _bp.m_code = None
5816
5817 return _bp
5818
5819
5820
5821 class CBreakPoint(object):
5822 def __init__(self, filename, scope_fqn, scope_first_line, lineno, fEnabled, expr, encoding, fTemporary = False):
5823 """
5824 Breakpoint constructor.
5825
5826 scope_fqn - scope fully qualified name. e.g: module.class.method
5827 """
5828
5829 self.m_id = None
5830 self.m_fEnabled = fEnabled
5831 self.m_filename = filename
5832 self.m_scope_fqn = scope_fqn
5833 self.m_scope_name = scope_fqn.split(SCOPE_SEP)[-1]
5834 self.m_scope_first_line = scope_first_line
5835 self.m_scope_offset = lineno - scope_first_line
5836 self.m_lineno = lineno
5837 self.m_expr = expr
5838 self.m_encoding = encoding
5839 self.m_code = None
5840 self.m_fTemporary = fTemporary
5841
5842 if (expr is not None) and (expr != ''):
5843 _expr = as_bytes(ENCODING_SOURCE % encoding + expr, encoding)
5844 print_debug('Breakpoint expression: %s' % repr(_expr))
5845 self.m_code = compile(_expr, '<string>', 'eval')
5846
5847
5848 def __reduce__(self):
5849 rv = (copy_reg.__newobj__, (type(self), ), vars(self), None, None)
5850 return rv
5851
5852
5853 def calc_enclosing_scope_name(self):
5854 if self.m_scope_offset != 0:
5855 return None
5856
5857 if self.m_scope_fqn in [MODULE_SCOPE, MODULE_SCOPE2]:
5858 return None
5859
5860 scope_name_list = self.m_scope_fqn.split(SCOPE_SEP)
5861 enclosing_scope_name = scope_name_list[-2]
5862
5863 return enclosing_scope_name
5864
5865
5866 def enable(self):
5867 self.m_fEnabled = True
5868
5869
5870 def disable(self):
5871 self.m_fEnabled = False
5872
5873
5874 def isEnabled(self):
5875 return self.m_fEnabled
5876
5877
5878 def __str__(self):
5879 return "('" + self.m_filename + "', '" + self.m_scope_fqn + "', " + str(self.m_scope_first_line) + ', ' + str(self.m_scope_offset) + ', ' + str(self.m_lineno) + ')'
5880
5881
5882
5883 class CBreakPointsManagerProxy:
5884 """
5885 A proxy for the breakpoint manager.
5886 While the breakpoint manager resides on the debuggee (the server),
5887 the proxy resides in the debugger (the client - session manager)
5888 """
5889
5890 def __init__(self, session_manager):
5891 self.m_session_manager = session_manager
5892
5893 self.m_break_points_by_file = {}
5894 self.m_break_points_by_id = {}
5895
5896 self.m_lock = threading.Lock()
5897
5898 #
5899 # The breakpoint proxy inserts itself between the two chained
5900 # event dispatchers in the session manager.
5901 #
5902
5903 event_type_dict = {CEventBreakpoint: {}}
5904
5905 self.m_session_manager.m_event_dispatcher_proxy.register_callback(self.update_bp, event_type_dict, fSingleUse = False)
5906 self.m_session_manager.m_event_dispatcher.register_chain_override(event_type_dict)
5907
5908
5909 def update_bp(self, event):
5910 """
5911 Handle breakpoint updates that arrive via the event dispatcher.
5912 """
5913
5914 try:
5915 self.m_lock.acquire()
5916
5917 if event.m_fAll:
5918 id_list = list(self.m_break_points_by_id.keys())
5919 else:
5920 id_list = event.m_id_list
5921
5922 if event.m_action == CEventBreakpoint.REMOVE:
5923 for id in id_list:
5924 try:
5925 bp = self.m_break_points_by_id.pop(id)
5926 bpm = self.m_break_points_by_file[bp.m_filename]
5927 del bpm[bp.m_lineno]
5928 if len(bpm) == 0:
5929 del self.m_break_points_by_file[bp.m_filename]
5930 except KeyError:
5931 pass
5932 return
5933
5934 if event.m_action == CEventBreakpoint.DISABLE:
5935 for id in id_list:
5936 try:
5937 bp = self.m_break_points_by_id[id]
5938 bp.disable()
5939 except KeyError:
5940 pass
5941 return
5942
5943 if event.m_action == CEventBreakpoint.ENABLE:
5944 for id in id_list:
5945 try:
5946 bp = self.m_break_points_by_id[id]
5947 bp.enable()
5948 except KeyError:
5949 pass
5950 return
5951
5952 bpm = self.m_break_points_by_file.get(event.m_bp.m_filename, {})
5953 bpm[event.m_bp.m_lineno] = event.m_bp
5954
5955 self.m_break_points_by_id[event.m_bp.m_id] = event.m_bp
5956
5957 finally:
5958 self.m_lock.release()
5959
5960 self.m_session_manager.m_event_dispatcher.fire_event(event)
5961
5962
5963 def sync(self):
5964 try:
5965 self.m_lock.acquire()
5966
5967 self.m_break_points_by_file = {}
5968 self.m_break_points_by_id = {}
5969
5970 finally:
5971 self.m_lock.release()
5972
5973 break_points_by_id = self.m_session_manager.getSession().getProxy().get_breakpoints()
5974
5975 try:
5976 self.m_lock.acquire()
5977
5978 self.m_break_points_by_id.update(break_points_by_id)
5979
5980 for bp in list(self.m_break_points_by_id.values()):
5981 bpm = self.m_break_points_by_file.get(bp.m_filename, {})
5982 bpm[bp.m_lineno] = bp
5983
5984 finally:
5985 self.m_lock.release()
5986
5987
5988 def clear(self):
5989 try:
5990 self.m_lock.acquire()
5991
5992 self.m_break_points_by_file = {}
5993 self.m_break_points_by_id = {}
5994
5995 finally:
5996 self.m_lock.release()
5997
5998
5999 def get_breakpoints(self):
6000 return self.m_break_points_by_id
6001
6002
6003 def get_breakpoint(self, filename, lineno):
6004 bpm = self.m_break_points_by_file[filename]
6005 bp = bpm[lineno]
6006 return bp
6007
6008
6009
6010 class CBreakPointsManager:
6011 def __init__(self):
6012 self.m_break_info_manager = CBreakInfoManager()
6013 self.m_active_break_points_by_file = {}
6014 self.m_break_points_by_function = {}
6015 self.m_break_points_by_file = {}
6016 self.m_break_points_by_id = {}
6017 self.m_lock = threading.Lock()
6018
6019 self.m_temp_bp = None
6020 self.m_fhard_tbp = False
6021
6022
6023 def get_active_break_points_by_file(self, filename):
6024 """
6025 Get active breakpoints for file.
6026 """
6027
6028 _filename = winlower(filename)
6029
6030 return self.m_active_break_points_by_file.setdefault(_filename, {})
6031
6032
6033 def __calc_active_break_points_by_file(self, filename):
6034 bpmpt = self.m_active_break_points_by_file.setdefault(filename, {})
6035 bpmpt.clear()
6036
6037 bpm = self.m_break_points_by_file.get(filename, {})
6038 for bp in list(bpm.values()):
6039 if bp.m_fEnabled:
6040 bpmpt[bp.m_lineno] = bp
6041
6042 tbp = self.m_temp_bp
6043 if (tbp is not None) and (tbp.m_filename == filename):
6044 bpmpt[tbp.m_lineno] = tbp
6045
6046
6047 def __remove_from_function_list(self, bp):
6048 function_name = bp.m_scope_name
6049
6050 try:
6051 bpf = self.m_break_points_by_function[function_name]
6052 del bpf[bp]
6053 if len(bpf) == 0:
6054 del self.m_break_points_by_function[function_name]
6055 except KeyError:
6056 pass
6057
6058 #
6059 # In some cases a breakpoint belongs to two scopes at the
6060 # same time. For example a breakpoint on the declaration line
6061 # of a function.
6062 #
6063
6064 _function_name = bp.calc_enclosing_scope_name()
6065 if _function_name is None:
6066 return
6067
6068 try:
6069 _bpf = self.m_break_points_by_function[_function_name]
6070 del _bpf[bp]
6071 if len(_bpf) == 0:
6072 del self.m_break_points_by_function[_function_name]
6073 except KeyError:
6074 pass
6075
6076
6077 def __add_to_function_list(self, bp):
6078 function_name = bp.m_scope_name
6079
6080 bpf = self.m_break_points_by_function.setdefault(function_name, {})
6081 bpf[bp] = True
6082
6083 #
6084 # In some cases a breakpoint belongs to two scopes at the
6085 # same time. For example a breakpoint on the declaration line
6086 # of a function.
6087 #
6088
6089 _function_name = bp.calc_enclosing_scope_name()
6090 if _function_name is None:
6091 return
6092
6093 _bpf = self.m_break_points_by_function.setdefault(_function_name, {})
6094 _bpf[bp] = True
6095
6096
6097 def get_breakpoint(self, filename, lineno):
6098 """
6099 Get breakpoint by file and line number.
6100 """
6101
6102 bpm = self.m_break_points_by_file[filename]
6103 bp = bpm[lineno]
6104 return bp
6105
6106
6107 def del_temp_breakpoint(self, fLock = True, breakpoint = None):
6108 """
6109 Delete a temoporary breakpoint.
6110 A temporary breakpoint is used when the debugger is asked to
6111 run-to a particular line.
6112 Hard temporary breakpoints are deleted only when actually hit.
6113 """
6114 if self.m_temp_bp is None:
6115 return
6116
6117 try:
6118 if fLock:
6119 self.m_lock.acquire()
6120
6121 if self.m_temp_bp is None:
6122 return
6123
6124 if self.m_fhard_tbp and not breakpoint is self.m_temp_bp:
6125 return
6126
6127 bp = self.m_temp_bp
6128 self.m_temp_bp = None
6129 self.m_fhard_tbp = False
6130
6131 self.__remove_from_function_list(bp)
6132 self.__calc_active_break_points_by_file(bp.m_filename)
6133
6134 finally:
6135 if fLock:
6136 self.m_lock.release()
6137
6138
6139 def set_temp_breakpoint(self, filename, scope, lineno, fhard = False):
6140 """
6141 Set a temoporary breakpoint.
6142 A temporary breakpoint is used when the debugger is asked to
6143 run-to a particular line.
6144 Hard temporary breakpoints are deleted only when actually hit.
6145 """
6146
6147 _filename = winlower(filename)
6148
6149 mbi = self.m_break_info_manager.getFile(_filename)
6150
6151 if scope != '':
6152 (s, l) = mbi.FindScopeByName(scope, lineno)
6153 else:
6154 (s, l) = mbi.FindScopeByLineno(lineno)
6155
6156 bp = CBreakPoint(_filename, s.m_fqn, s.m_first_line, l, fEnabled = True, expr = as_unicode(''), encoding = as_unicode('utf-8'), fTemporary = True)
6157
6158 try:
6159 self.m_lock.acquire()
6160
6161 self.m_fhard_tbp = False
6162 self.del_temp_breakpoint(fLock = False)
6163 self.m_fhard_tbp = fhard
6164 self.m_temp_bp = bp
6165
6166 self.__add_to_function_list(bp)
6167 self.__calc_active_break_points_by_file(bp.m_filename)
6168
6169 finally:
6170 self.m_lock.release()
6171
6172
6173 def set_breakpoint(self, filename, scope, lineno, fEnabled, expr, encoding):
6174 """
6175 Set breakpoint.
6176
6177 scope - a string (possibly empty) with the dotted scope of the
6178 breakpoint. eg. 'my_module.my_class.foo'
6179
6180 expr - a string (possibly empty) with a python expression
6181 that will be evaluated at the scope of the breakpoint.
6182 The breakpoint will be hit if the expression evaluates
6183 to True.
6184 """
6185
6186 _filename = winlower(filename)
6187
6188 mbi = self.m_break_info_manager.getFile(_filename)
6189
6190 if scope != '':
6191 (s, l) = mbi.FindScopeByName(scope, lineno)
6192 else:
6193 (s, l) = mbi.FindScopeByLineno(lineno)
6194
6195 bp = CBreakPoint(_filename, s.m_fqn, s.m_first_line, l, fEnabled, expr, encoding)
6196
6197 try:
6198 self.m_lock.acquire()
6199
6200 bpm = self.m_break_points_by_file.setdefault(_filename, {})
6201
6202 #
6203 # If a breakpoint on the same line is found we use its ID.
6204 # Since the debugger lists breakpoints by IDs, this has
6205 # a similar effect to modifying the breakpoint.
6206 #
6207
6208 try:
6209 old_bp = bpm[l]
6210 id = old_bp.m_id
6211 self.__remove_from_function_list(old_bp)
6212 except KeyError:
6213 #
6214 # Find the smallest available ID.
6215 #
6216
6217 bpids = list(self.m_break_points_by_id.keys())
6218 bpids.sort()
6219
6220 id = 0
6221 while id < len(bpids):
6222 if bpids[id] != id:
6223 break
6224 id += 1
6225
6226 bp.m_id = id
6227
6228 self.m_break_points_by_id[id] = bp
6229 bpm[l] = bp
6230 if fEnabled:
6231 self.__add_to_function_list(bp)
6232
6233 self.__calc_active_break_points_by_file(bp.m_filename)
6234
6235 return bp
6236
6237 finally:
6238 self.m_lock.release()
6239
6240
6241 def disable_breakpoint(self, id_list, fAll):
6242 """
6243 Disable breakpoint.
6244 """
6245
6246 try:
6247 self.m_lock.acquire()
6248
6249 if fAll:
6250 id_list = list(self.m_break_points_by_id.keys())
6251
6252 for id in id_list:
6253 try:
6254 bp = self.m_break_points_by_id[id]
6255 except KeyError:
6256 continue
6257
6258 bp.disable()
6259 self.__remove_from_function_list(bp)
6260 self.__calc_active_break_points_by_file(bp.m_filename)
6261
6262 finally:
6263 self.m_lock.release()
6264
6265
6266 def enable_breakpoint(self, id_list, fAll):
6267 """
6268 Enable breakpoint.
6269 """
6270
6271 try:
6272 self.m_lock.acquire()
6273
6274 if fAll:
6275 id_list = list(self.m_break_points_by_id.keys())
6276
6277 for id in id_list:
6278 try:
6279 bp = self.m_break_points_by_id[id]
6280 except KeyError:
6281 continue
6282
6283 bp.enable()
6284 self.__add_to_function_list(bp)
6285 self.__calc_active_break_points_by_file(bp.m_filename)
6286
6287 finally:
6288 self.m_lock.release()
6289
6290
6291 def delete_breakpoint(self, id_list, fAll):
6292 """
6293 Delete breakpoint.
6294 """
6295
6296 try:
6297 self.m_lock.acquire()
6298
6299 if fAll:
6300 id_list = list(self.m_break_points_by_id.keys())
6301
6302 for id in id_list:
6303 try:
6304 bp = self.m_break_points_by_id[id]
6305 except KeyError:
6306 continue
6307
6308 filename = bp.m_filename
6309 lineno = bp.m_lineno
6310
6311 bpm = self.m_break_points_by_file[filename]
6312 if bp == bpm[lineno]:
6313 del bpm[lineno]
6314
6315 if len(bpm) == 0:
6316 del self.m_break_points_by_file[filename]
6317
6318 self.__remove_from_function_list(bp)
6319 self.__calc_active_break_points_by_file(bp.m_filename)
6320
6321 del self.m_break_points_by_id[id]
6322
6323 finally:
6324 self.m_lock.release()
6325
6326
6327 def get_breakpoints(self):
6328 return self.m_break_points_by_id
6329
6330
6331
6332 #
6333 # ----------------------------------- Core Debugger ------------------------------------
6334 #
6335
6336
6337
6338 class CCodeContext:
6339 """
6340 Class represents info related to code objects.
6341 """
6342
6343 def __init__(self, frame, bp_manager):
6344 self.m_code = frame.f_code
6345 self.m_filename = calc_frame_path(frame)
6346 self.m_basename = os.path.basename(self.m_filename)
6347
6348 self.m_file_breakpoints = bp_manager.get_active_break_points_by_file(self.m_filename)
6349
6350 self.m_fExceptionTrap = False
6351
6352
6353 def is_untraced(self):
6354 """
6355 Return True if this code object should not be traced.
6356 """
6357
6358 return self.m_basename in [THREADING_FILENAME, DEBUGGER_FILENAME]
6359
6360
6361 def is_exception_trap_frame(self):
6362 """
6363 Return True if this frame should be a trap for unhandled
6364 exceptions.
6365 """
6366
6367 if self.m_basename == THREADING_FILENAME:
6368 return True
6369
6370 if self.m_basename == DEBUGGER_FILENAME and self.m_code.co_name in ['__execv', '__execve', '__function_wrapper']:
6371 return True
6372
6373 return False
6374
6375
6376
6377 class CDebuggerCoreThread:
6378 """
6379 Class represents a debugged thread.
6380 This is a core structure of the debugger. It includes most of the
6381 optimization tricks and hacks, and includes a good amount of
6382 subtle bug fixes, be carefull not to mess it up...
6383 """
6384
6385 def __init__(self, name, core_debugger, frame, event):
6386 self.m_thread_id = thread.get_ident()
6387 self.m_thread_name = name
6388 self.m_fBroken = False
6389 self.m_fUnhandledException = False
6390
6391 self.m_frame = frame
6392 self.m_event = event
6393 self.m_ue_lineno = None
6394 self.m_uef_lineno = None
6395
6396 self.m_code_context = core_debugger.get_code_context(frame)
6397
6398 self.m_locals_copy = {}
6399
6400 self.m_core = core_debugger
6401 self.m_bp_manager = core_debugger.m_bp_manager
6402
6403 self.m_frame_lock = threading.Condition()
6404 self.m_frame_external_references = 0
6405
6406 self.m_exc_info = None
6407
6408 self.m_depth = 0
6409 self.set_depth(frame)
6410
6411
6412 def set_depth(self, frame):
6413 self.m_depth = 0
6414 while frame is not None:
6415 self.m_depth += 1
6416 frame = frame.f_back
6417
6418
6419 def profile_recursion(self, frame, event, arg):
6420 if event == 'call':
6421 if self.m_depth > g_recursionlimit:
6422 print_debug('Exceeded recursion limit and caught in profile function.')
6423
6424 try:
6425 #
6426 # The allowed recursion limit was exceeded.
6427 # To view the offending script frame, go two frames
6428 # down the stack with the 'down' console command.
6429 #
6430 raise RuntimeError('maximum recursion depth exceeded')
6431
6432 except:
6433 #
6434 # Schedule the debugger to re-enable the profile hook.
6435 #
6436 self.set_tracers(fsignal_exception = True)
6437 raise
6438
6439 elif event == 'return':
6440 return self.profile(frame, event, arg)
6441
6442
6443
6444 def profile(self, frame, event, arg):
6445 """
6446 Profiler method.
6447 The Python profiling mechanism is used by the debugger
6448 mainly to handle synchronization issues related to the
6449 life time of the frame structure.
6450 """
6451 #print_debug('profile: %s, %s, %s, %s, %s' % (repr(frame), event, frame.f_code.co_name, frame.f_code.co_filename, repr(arg)[:40]))
6452
6453 if event == 'return':
6454 self.m_depth -= 1
6455
6456 if sys.excepthook != g_excepthook:
6457 set_excepthook()
6458
6459 self.m_frame = frame.f_back
6460
6461 try:
6462 self.m_code_context = self.m_core.m_code_contexts[self.m_frame.f_code]
6463 except AttributeError:
6464 if self.m_event != 'return' and self.m_core.m_ftrap:
6465 #
6466 # An exception is raised from the outer-most frame.
6467 # This means an unhandled exception.
6468 #
6469
6470 self.m_frame = frame
6471 self.m_event = 'exception'
6472
6473 self.m_uef_lineno = self.m_ue_lineno
6474
6475 self.m_fUnhandledException = True
6476 self.m_core._break(self, frame, event, arg)
6477
6478 self.m_uef_lineno = None
6479
6480 if frame in self.m_locals_copy:
6481 self.update_locals()
6482
6483 self.m_frame = None
6484
6485 self.m_core.remove_thread(self.m_thread_id)
6486 sys.setprofile(None)
6487 sys.settrace(self.m_core.trace_dispatch_init)
6488
6489 if self.m_frame_external_references == 0:
6490 return
6491
6492 #
6493 # Wait until no one references the frame object
6494 #
6495
6496 try:
6497 self.m_frame_lock.acquire()
6498
6499 while self.m_frame_external_references != 0:
6500 safe_wait(self.m_frame_lock, 1.0)
6501
6502 finally:
6503 self.m_frame_lock.release()
6504
6505
6506 def frame_acquire(self):
6507 """
6508 Aquire a reference to the frame.
6509 """
6510
6511 try:
6512 self.m_frame_lock.acquire()
6513
6514 self.m_frame_external_references += 1
6515 f = self.m_frame
6516 if f is None:
6517 raise ThreadDone
6518
6519 return f
6520
6521 finally:
6522 self.m_frame_lock.release()
6523
6524
6525 def frame_release(self):
6526 """
6527 Release a reference to the frame.
6528 """
6529
6530 try:
6531 self.m_frame_lock.acquire()
6532
6533 self.m_frame_external_references -= 1
6534 if self.m_frame_external_references == 0:
6535 self.m_frame_lock.notify()
6536
6537 finally:
6538 self.m_frame_lock.release()
6539
6540
6541 def get_frame(self, base_frame, index, fException = False):
6542 """
6543 Get frame at index depth down the stack.
6544 Starting from base_frame return the index depth frame
6545 down the stack. If fException is True use the exception
6546 stack (traceback).
6547 """
6548
6549 if fException:
6550 tb = get_traceback(base_frame, self)
6551 if tb is None:
6552 raise NoExceptionFound
6553
6554 while tb.tb_next is not None:
6555 tb = tb.tb_next
6556
6557 f = tb.tb_frame
6558 else:
6559 f = base_frame
6560
6561 while f is not None:
6562 if not g_fDebug and f.f_code.co_name == 'rpdb2_import_wrapper':
6563 f = f.f_back
6564 continue
6565
6566 if index <= 0:
6567 break
6568
6569 f = f.f_back
6570 index -= 1
6571
6572 if (index < 0) or (f is None):
6573 raise InvalidFrame
6574
6575 if (self.m_uef_lineno is not None) and (f.f_back is None):
6576 lineno = self.m_uef_lineno
6577 else:
6578 lineno = f.f_lineno
6579
6580 if fException:
6581 tb = get_traceback(base_frame, self)
6582 while tb is not None:
6583 if tb.tb_frame == f:
6584 lineno = tb.tb_lineno
6585 break
6586 tb = tb.tb_next
6587
6588 return (f, lineno)
6589
6590
6591 def get_locals_copy(self, frame_index, fException, fReadOnly):
6592 """
6593 Get globals and locals of frame.
6594 A copy scheme is used for locals to work around a bug in
6595 Python 2.3 and 2.4 that prevents modifying the local dictionary.
6596 """
6597
6598 try:
6599 base_frame = self.frame_acquire()
6600
6601 (f, lineno) = self.get_frame(base_frame, frame_index, fException)
6602
6603 if fReadOnly:
6604 gc = copy.copy(f.f_globals)
6605 else:
6606 gc = f.f_globals
6607
6608 try:
6609 (lc, olc) = self.m_locals_copy[f]
6610
6611 except KeyError:
6612 if f.f_code.co_name in [MODULE_SCOPE, MODULE_SCOPE2]:
6613 lc = gc
6614 olc = gc
6615
6616 else:
6617 lc = copy.copy(f.f_locals)
6618 olc = copy.copy(lc)
6619
6620 if not fReadOnly:
6621 self.m_locals_copy[f] = (lc, olc)
6622 self.set_local_trace(f)
6623
6624 return (gc, lc, olc)
6625
6626 finally:
6627 f = None
6628 base_frame = None
6629
6630 self.frame_release()
6631
6632
6633 def update_locals_copy(self):
6634 """
6635 Update copy of locals with changes in locals.
6636 """
6637
6638 lct = self.m_locals_copy.get(self.m_frame, None)
6639 if lct is None:
6640 return
6641
6642 (lc, base) = lct
6643 cr = copy.copy(self.m_frame.f_locals)
6644
6645 for k in cr:
6646 if not k in base:
6647 lc[k] = cr[k]
6648 continue
6649
6650 if not cr[k] is base[k]:
6651 lc[k] = cr[k]
6652
6653
6654 def update_locals(self):
6655 """
6656 Update locals with changes from copy of locals.
6657 """
6658
6659 lct = self.m_locals_copy.pop(self.m_frame, None)
6660 if lct is None:
6661 return
6662
6663 self.m_frame.f_locals.update(lct[0])
6664
6665
6666 def __eval_breakpoint(self, frame, bp):
6667 """
6668 Return True if the breakpoint is hit.
6669 """
6670
6671 if not bp.m_fEnabled:
6672 return False
6673
6674 if bp.m_expr == '':
6675 return True
6676
6677 try:
6678 if frame in self.m_locals_copy:
6679 l = self.m_locals_copy[frame][0]
6680 v = eval(bp.m_code, frame.f_globals, l)
6681 else:
6682 v = eval(bp.m_code, frame.f_globals, frame.f_locals)
6683
6684 return (v != False)
6685
6686 except:
6687 return False
6688
6689
6690 def set_local_trace(self, frame, fsignal_exception = False):
6691 """
6692 Set trace callback of frame.
6693 Specialized trace methods are selected here to save switching time
6694 during actual tracing.
6695 """
6696
6697 if not self.m_core.m_ftrace:
6698 frame.f_trace = self.trace_dispatch_stop
6699 return
6700
6701 if fsignal_exception:
6702 frame.f_trace = self.trace_dispatch_signal
6703 return
6704
6705 code_context = self.m_core.get_code_context(frame)
6706
6707 if self.m_core.is_break(self, frame):
6708 frame.f_trace = self.trace_dispatch_break
6709
6710 elif code_context.m_fExceptionTrap or (frame.f_back is None):
6711 frame.f_trace = self.trace_dispatch_trap
6712
6713 elif frame.f_code.co_name in self.m_bp_manager.m_break_points_by_function:
6714 frame.f_trace = self.trace_dispatch
6715
6716 elif frame in self.m_locals_copy:
6717 frame.f_trace = self.trace_dispatch
6718
6719 elif frame == self.m_core.m_return_frame:
6720 frame.f_trace = self.trace_dispatch
6721
6722 else:
6723 del frame.f_trace
6724
6725
6726 def set_tracers(self, fsignal_exception = False):
6727 """
6728 Set trace callbacks for all frames in stack.
6729 """
6730
6731 try:
6732 try:
6733 f = self.frame_acquire()
6734 while f is not None:
6735 self.set_local_trace(f, fsignal_exception)
6736 f = f.f_back
6737
6738 except ThreadDone:
6739 f = None
6740
6741 finally:
6742 f = None
6743 self.frame_release()
6744
6745
6746 def trace_dispatch_stop(self, frame, event, arg):
6747 """
6748 Disable tracing for this thread.
6749 """
6750
6751 if frame in self.m_locals_copy:
6752 self.update_locals()
6753
6754 sys.settrace(None)
6755 sys.setprofile(None)
6756 return None
6757
6758
6759 def trace_dispatch_break(self, frame, event, arg):
6760 """
6761 Trace method for breaking a thread.
6762 """
6763
6764 if event not in ['line', 'return', 'exception']:
6765 return frame.f_trace
6766
6767 if event == 'exception':
6768 self.set_exc_info(arg)
6769
6770 self.m_event = event
6771
6772 if frame in self.m_locals_copy:
6773 self.update_locals_copy()
6774
6775 self.m_core._break(self, frame, event, arg)
6776
6777 if frame in self.m_locals_copy:
6778 self.update_locals()
6779 self.set_local_trace(frame)
6780
6781 return frame.f_trace
6782
6783
6784 def trace_dispatch_call(self, frame, event, arg):
6785 """
6786 Initial trace method for thread.
6787 """
6788
6789 if not self.m_core.m_ftrace:
6790 return self.trace_dispatch_stop(frame, event, arg)
6791
6792 self.m_depth += 1
6793 if self.m_depth > g_recursionlimit:
6794 sys.setprofile(self.profile_recursion)
6795
6796 self.m_frame = frame
6797
6798 try:
6799 self.m_code_context = self.m_core.m_code_contexts[frame.f_code]
6800 except KeyError:
6801 self.m_code_context = self.m_core.get_code_context(frame)
6802
6803 if self.m_core.m_fBreak or (self.m_core.m_step_tid == self.m_thread_id):
6804 self.m_event = event
6805 self.m_core._break(self, frame, event, arg)
6806 if frame in self.m_locals_copy:
6807 self.update_locals()
6808 self.set_local_trace(frame)
6809 return frame.f_trace
6810
6811 if not frame.f_code.co_name in self.m_bp_manager.m_break_points_by_function:
6812 return None
6813
6814 bp = self.m_code_context.m_file_breakpoints.get(frame.f_lineno, None)
6815 if bp is not None and self.__eval_breakpoint(frame, bp):
6816 self.m_event = event
6817 self.m_core._break(self, frame, event, arg)
6818 if frame in self.m_locals_copy:
6819 self.update_locals()
6820 self.set_local_trace(frame)
6821 return frame.f_trace
6822
6823 return self.trace_dispatch
6824
6825
6826 def trace_dispatch(self, frame, event, arg):
6827 """
6828 General trace method for thread.
6829 """
6830
6831 if (event == 'line'):
6832 if frame in self.m_locals_copy:
6833 self.update_locals_copy()
6834
6835 bp = self.m_code_context.m_file_breakpoints.get(frame.f_lineno, None)
6836
6837 if bp is not None and self.__eval_breakpoint(frame, bp):
6838 self.m_event = event
6839 self.m_core._break(self, frame, event, arg)
6840
6841 if frame in self.m_locals_copy:
6842 self.update_locals()
6843 self.set_local_trace(frame)
6844
6845 return frame.f_trace
6846
6847 if event == 'return':
6848 if frame in self.m_locals_copy:
6849 self.update_locals_copy()
6850
6851 if frame == self.m_core.m_return_frame:
6852 self.m_event = event
6853 self.m_core._break(self, frame, event, arg)
6854
6855 if frame in self.m_locals_copy:
6856 self.update_locals()
6857
6858 return None
6859
6860 if event == 'exception':
6861 if frame in self.m_locals_copy:
6862 self.update_locals()
6863 self.set_local_trace(frame)
6864
6865 if not is_py3k() and not frame.f_exc_traceback is arg[2]:
6866 (frame.f_exc_type, frame.f_exc_value, frame.f_exc_traceback) = arg
6867
6868 return frame.f_trace
6869
6870 return frame.f_trace
6871
6872
6873 def trace_dispatch_trap(self, frame, event, arg):
6874 """
6875 Trace method used for frames in which unhandled exceptions
6876 should be caught.
6877 """
6878
6879 if (event == 'line'):
6880 self.m_event = event
6881
6882 if frame in self.m_locals_copy:
6883 self.update_locals_copy()
6884
6885 bp = self.m_code_context.m_file_breakpoints.get(frame.f_lineno, None)
6886 if bp is not None and self.__eval_breakpoint(frame, bp):
6887 self.m_core._break(self, frame, event, arg)
6888
6889 if frame in self.m_locals_copy:
6890 self.update_locals()
6891 self.set_local_trace(frame)
6892
6893 return frame.f_trace
6894
6895 if event == 'return':
6896 last_event = self.m_event
6897 self.m_event = event
6898
6899 if frame in self.m_locals_copy:
6900 self.update_locals_copy()
6901
6902 if frame == self.m_core.m_return_frame:
6903 self.m_core._break(self, frame, event, arg)
6904
6905 if frame in self.m_locals_copy:
6906 self.update_locals()
6907
6908 if last_event == 'exception':
6909 self.m_event = last_event
6910
6911 return None
6912
6913 if event == 'exception':
6914 self.m_event = event
6915
6916 if self.m_code_context.m_fExceptionTrap and self.m_core.m_ftrap:
6917 self.set_exc_info(arg)
6918
6919 self.m_fUnhandledException = True
6920 self.m_core._break(self, frame, event, arg)
6921
6922 if frame in self.m_locals_copy:
6923 self.update_locals()
6924
6925 return frame.f_trace
6926
6927 self.m_ue_lineno = frame.f_lineno
6928
6929 if frame in self.m_locals_copy:
6930 self.update_locals()
6931 self.set_local_trace(frame)
6932
6933 if is_py3k():
6934 self.set_exc_info(arg)
6935 elif not frame.f_exc_traceback is arg[2]:
6936 (frame.f_exc_type, frame.f_exc_value, frame.f_exc_traceback) = arg
6937
6938 return frame.f_trace
6939
6940 return frame.f_trace
6941
6942
6943 def trace_dispatch_signal(self, frame, event, arg):
6944 #print_debug('*** trace_dispatch_signal %s, %s, %s' % (frame.f_lineno, event, repr(arg)))
6945 self.set_exc_info(arg)
6946 self.set_tracers()
6947 self.set_depth(frame)
6948 sys.setprofile(self.profile)
6949
6950 return self.trace_dispatch_trap(frame, event, arg)
6951
6952
6953 def set_exc_info(self, arg):
6954 """
6955 Set exception information.
6956 """
6957
6958 if arg == None:
6959 return
6960
6961 if is_py3k():
6962 self.m_exc_info = arg
6963 return
6964
6965 (t, v, tb) = arg
6966
6967 while tb is not None:
6968 f = tb.tb_frame
6969 f.f_exc_type = t
6970 f.f_exc_value = v
6971 f.f_exc_traceback = tb
6972
6973 tb = tb.tb_next
6974
6975
6976 def get_exc_info(self):
6977 return self.m_exc_info
6978
6979
6980 def reset_exc_info(self):
6981 self.m_exc_info = None
6982
6983
6984 def is_breakpoint(self):
6985 """
6986 Calc if current line is hit by breakpoint.
6987 """
6988
6989 bp = self.m_code_context.m_file_breakpoints.get(self.m_frame.f_lineno, None)
6990 if bp is not None and self.__eval_breakpoint(self.m_frame, bp):
6991 return True
6992
6993 return False
6994
6995
6996 def get_breakpoint(self):
6997 """
6998 Return current line breakpoint if any.
6999 """
7000
7001 return self.m_code_context.m_file_breakpoints.get(self.m_frame.f_lineno, None)
7002
7003
7004
7005 class CDebuggerCore:
7006 """
7007 Base class for the debugger.
7008 Handles basic debugger functionality.
7009 """
7010
7011 def __init__(self, fembedded = False):
7012 self.m_ftrace = True
7013
7014 self.m_current_ctx = None
7015 self.m_f_first_to_break = True
7016 self.m_f_break_on_init = False
7017
7018 self.m_builtins_hack = None
7019
7020 self.m_timer_embedded_giveup = None
7021
7022 self.m_threads_lock = threading.Condition()
7023
7024 self.m_threads = {}
7025
7026 self.m_event_dispatcher = CEventDispatcher()
7027 self.m_state_manager = CStateManager(STATE_RUNNING, self.m_event_dispatcher)
7028
7029 self.m_ffork_into_child = False
7030 self.m_ffork_auto = False
7031
7032 self.m_fsynchronicity = True
7033 self.m_ftrap = True
7034 self.m_fUnhandledException = False
7035 self.m_fBreak = False
7036
7037 self.m_lastest_event = None
7038 self.m_step_tid = None
7039 self.m_next_frame = None
7040 self.m_return_frame = None
7041 self.m_saved_step = (None, None, None)
7042 self.m_saved_next = None
7043
7044 self.m_bp_manager = CBreakPointsManager()
7045
7046 self.m_code_contexts = {None: None}
7047
7048 self.m_fembedded = fembedded
7049 self.m_embedded_event = threading.Event()
7050 self.m_embedded_sync_t0 = 0
7051 self.m_embedded_sync_t1 = 0
7052
7053 self.m_heartbeats = {0: time.time() + 3600}
7054
7055
7056 def shutdown(self):
7057 self.m_event_dispatcher.shutdown()
7058 self.m_state_manager.shutdown()
7059
7060
7061 def is_embedded(self):
7062 return self.m_fembedded
7063
7064
7065 def send_fork_switch(self, sync_n):
7066 """
7067 Notify client that debuggee is forking and that it should
7068 try to reconnect to the child.
7069 """
7070
7071 print_debug('Sending fork switch event')
7072
7073 event = CEventForkSwitch(sync_n)
7074 self.m_event_dispatcher.fire_event(event)
7075
7076
7077 def send_exec_switch(self, sync_n):
7078 """
7079 Notify client that debuggee is doing an exec and that it should
7080 try to reconnect (in case the exec failed).
7081 """
7082
7083 print_debug('Sending exec switch event')
7084
7085 event = CEventExecSwitch(sync_n)
7086 self.m_event_dispatcher.fire_event(event)
7087
7088
7089 def send_event_exit(self):
7090 """
7091 Notify client that the debuggee is shutting down.
7092 """
7093
7094 event = CEventExit()
7095 self.m_event_dispatcher.fire_event(event)
7096
7097
7098 def send_events(self, event):
7099 pass
7100
7101
7102 def set_request_go_timer(self, timeout):
7103 """
7104 Set timeout thread to release debugger from waiting for a client
7105 to attach.
7106 """
7107
7108 self.cancel_request_go_timer()
7109
7110 if timeout is None:
7111 return
7112
7113 _timeout = max(1.0, timeout)
7114
7115 f = lambda: (
7116 self.record_client_heartbeat(0, False, True),
7117 self.request_go()
7118 )
7119
7120 self.m_timer_embedded_giveup = threading.Timer(_timeout, f)
7121 self.m_timer_embedded_giveup.start()
7122
7123 #
7124 # sleep() releases control and allow timer thread to actually start
7125 # before this scope returns.
7126 #
7127 time.sleep(0.1)
7128
7129
7130 def cancel_request_go_timer(self):
7131 t = self.m_timer_embedded_giveup
7132 if t is not None:
7133 self.m_timer_embedded_giveup = None
7134 t.cancel()
7135
7136
7137 def setbreak(self, f):
7138 """
7139 Set thread to break on next statement.
7140 """
7141
7142 if not self.m_ftrace:
7143 return
7144
7145 tid = thread.get_ident()
7146
7147 if not tid in self.m_threads:
7148 return self.settrace(f)
7149
7150 ctx = self.m_threads[tid]
7151 f.f_trace = ctx.trace_dispatch_break
7152 self.m_saved_next = self.m_next_frame
7153 self.m_next_frame = f
7154
7155
7156 def settrace(self, f = None, f_break_on_init = True, timeout = None, builtins_hack = None):
7157 """
7158 Start tracing mechanism for thread.
7159 """
7160
7161 if not self.m_ftrace:
7162 return
7163
7164 tid = thread.get_ident()
7165 if tid in self.m_threads:
7166 return
7167
7168 self.set_request_go_timer(timeout)
7169
7170 self.m_f_break_on_init = f_break_on_init
7171 self.m_builtins_hack = builtins_hack
7172
7173 threading.settrace(self.trace_dispatch_init)
7174 sys.settrace(self.trace_dispatch_init)
7175
7176 if f is not None:
7177 f.f_trace = self.trace_dispatch_init
7178
7179
7180 def stoptrace(self):
7181 """
7182 Stop tracing mechanism.
7183 """
7184
7185 global g_fignore_atexit
7186
7187 g_fignore_atexit = True
7188
7189 threading.settrace(None)
7190 sys.settrace(None)
7191 sys.setprofile(None)
7192
7193 self.m_ftrace = False
7194 self.set_all_tracers()
7195
7196 try:
7197 self.request_go()
7198 except DebuggerNotBroken:
7199 pass
7200
7201 #self.m_threads = {}
7202
7203
7204 def get_code_context(self, frame):
7205 try:
7206 return self.m_code_contexts[frame.f_code]
7207 except KeyError:
7208 if self.m_builtins_hack != None:
7209 if calc_frame_path(frame) == self.m_builtins_hack:
7210 self.m_builtins_hack = None
7211 frame.f_globals['__builtins__'] = g_builtins_module
7212
7213 code_context = CCodeContext(frame, self.m_bp_manager)
7214 return self.m_code_contexts.setdefault(frame.f_code, code_context)
7215
7216
7217 def get_current_ctx(self):
7218 if len(self.m_threads) == 0:
7219 raise NoThreads
7220
7221 return self.m_current_ctx
7222
7223
7224 def get_ctx(self, tid):
7225 ctx = self.m_threads.get(tid, None)
7226 if ctx == None:
7227 raise ThreadNotFound
7228
7229 return ctx
7230
7231
7232 def wait_for_first_thread(self):
7233 """
7234 Wait until at least one debuggee thread is alive.
7235 Python can have 0 threads in some circumstances as
7236 embedded Python and the Python interpreter console.
7237 """
7238
7239 if self.m_current_ctx is not None:
7240 return
7241
7242 try:
7243 self.m_threads_lock.acquire()
7244
7245 while self.m_current_ctx is None:
7246 safe_wait(self.m_threads_lock, 1.0)
7247
7248 finally:
7249 self.m_threads_lock.release()
7250
7251
7252 def notify_first_thread(self):
7253 """
7254 Notify that first thread is available for tracing.
7255 """
7256
7257 try:
7258 self.m_threads_lock.acquire()
7259 self.m_threads_lock.notify()
7260 finally:
7261 self.m_threads_lock.release()
7262
7263
7264 def set_exception_trap_frame(self, frame):
7265 """
7266 Set trap for unhandled exceptions in relevant frame.
7267 """
7268
7269 while frame is not None:
7270 code_context = self.get_code_context(frame)
7271 if code_context.is_exception_trap_frame():
7272 code_context.m_fExceptionTrap = True
7273 return
7274
7275 frame = frame.f_back
7276
7277
7278 def __set_signal_handler(self):
7279 """
7280 Set rpdb2 to wrap all signal handlers.
7281 """
7282 for key, value in list(vars(signal).items()):
7283 if not key.startswith('SIG') or key in ['SIGRTMIN', 'SIGRTMAX'] or key.startswith('SIG_'):
7284 continue
7285
7286 handler = signal.getsignal(value)
7287 if handler in [signal.SIG_IGN, signal.SIG_DFL]:
7288 continue
7289
7290 try:
7291 signal.signal(value, handler)
7292 except:
7293 print_debug('Failed to set signal handler for signal %s(%d)' % (key, value))
7294
7295
7296 def clear_source_cache(self):
7297 g_lines_cache.clear()
7298
7299 event = CEventClearSourceCache()
7300 self.m_event_dispatcher.fire_event(event)
7301
7302
7303 def trace_dispatch_init(self, frame, event, arg):
7304 """
7305 Initial tracing method.
7306 """
7307
7308 if event not in ['call', 'line', 'return']:
7309 return None
7310
7311 code_context = self.get_code_context(frame)
7312 if event == 'call' and code_context.is_untraced():
7313 return None
7314
7315 self.set_exception_trap_frame(frame)
7316
7317 try:
7318 t = current_thread()
7319 name = thread_get_name(t)
7320 except:
7321 name = ''
7322
7323 if name == 'MainThread':
7324 self.__set_signal_handler()
7325
7326 ctx = CDebuggerCoreThread(name, self, frame, event)
7327 ctx.set_tracers()
7328
7329 try:
7330 self.m_threads_lock.acquire()
7331
7332 self.m_threads[ctx.m_thread_id] = ctx
7333 nthreads = len(self.m_threads)
7334
7335 if nthreads == 1:
7336 self.prepare_embedded_sync()
7337
7338 finally:
7339 self.m_threads_lock.release()
7340
7341 if nthreads == 1:
7342 self.clear_source_cache()
7343
7344 self.m_current_ctx = ctx
7345 self.notify_first_thread()
7346
7347 if self.m_f_break_on_init:
7348 self.m_f_break_on_init = False
7349 self.request_break()
7350
7351 sys.settrace(ctx.trace_dispatch_call)
7352 sys.setprofile(ctx.profile)
7353
7354 self.wait_embedded_sync(nthreads == 1)
7355
7356 if event == 'call':
7357 return ctx.trace_dispatch_call(frame, event, arg)
7358 elif hasattr(frame, 'f_trace') and (frame.f_trace is not None):
7359 return frame.f_trace(frame, event, arg)
7360 else:
7361 return None
7362
7363
7364 def prepare_embedded_sync(self):
7365 if not self.m_fembedded:
7366 return
7367
7368 t = time.time()
7369 t0 = self.m_embedded_sync_t0
7370
7371 if t0 != 0:
7372 self.fix_heartbeats(t - t0)
7373
7374 if self.get_clients_attached() == 0:
7375 return
7376
7377 if t - t0 < EMBEDDED_SYNC_THRESHOLD:
7378 return
7379
7380 self.m_embedded_sync_t1 = t
7381 self.m_embedded_event.clear()
7382
7383
7384 def wait_embedded_sync(self, ftrigger):
7385 if not self.m_fembedded:
7386 return
7387
7388 t = time.time()
7389 t0 = self.m_embedded_sync_t0
7390 t1 = self.m_embedded_sync_t1
7391
7392 if t - t0 < EMBEDDED_SYNC_THRESHOLD:
7393 return
7394
7395 if t - t1 >= EMBEDDED_SYNC_TIMEOUT:
7396 return
7397
7398 if ftrigger:
7399 event = CEventEmbeddedSync()
7400 self.m_event_dispatcher.fire_event(event)
7401
7402 safe_wait(self.m_embedded_event, EMBEDDED_SYNC_TIMEOUT - (t - t1))
7403
7404 if ftrigger:
7405 self.m_embedded_sync_t1 = 0
7406
7407
7408 def embedded_sync(self):
7409 self.m_embedded_event.set()
7410
7411
7412 def set_all_tracers(self):
7413 """
7414 Set trace methods for all frames of all threads.
7415 """
7416
7417 for ctx in list(self.m_threads.values()):
7418 ctx.set_tracers()
7419
7420
7421 def remove_thread(self, thread_id):
7422 try:
7423 del self.m_threads[thread_id]
7424
7425 if self.m_current_ctx.m_thread_id == thread_id:
7426 self.m_current_ctx = list(self.m_threads.values())[0]
7427
7428 except (KeyError, IndexError):
7429 self.m_embedded_sync_t0 = time.time()
7430
7431
7432 def set_break_flag(self):
7433 self.m_fBreak = (self.m_state_manager.get_state() == STATE_BROKEN)
7434
7435
7436 def is_break(self, ctx, frame, event = None):
7437 if self.m_fBreak:
7438 return True
7439
7440 if ctx.m_fUnhandledException:
7441 return True
7442
7443 if self.m_step_tid == ctx.m_thread_id:
7444 return True
7445
7446 if self.m_next_frame == frame:
7447 return True
7448
7449 if (self.m_return_frame == frame) and (event == 'return'):
7450 return True
7451
7452 return False
7453
7454
7455 def record_client_heartbeat(self, id, finit, fdetach):
7456 """
7457 Record that client id is still attached.
7458 """
7459
7460 if finit:
7461 self.m_heartbeats.pop(0, None)
7462
7463 if fdetach:
7464 self.m_heartbeats.pop(id, None)
7465 return
7466
7467 if finit or id in self.m_heartbeats:
7468 self.m_heartbeats[id] = time.time()
7469
7470
7471 def fix_heartbeats(self, missing_pulse):
7472 for k, v in list(self.m_heartbeats.items()):
7473 self.m_heartbeats[k] = v + missing_pulse
7474
7475
7476 def get_clients_attached(self):
7477 n = 0
7478 t = time.time()
7479
7480 for v in list(self.m_heartbeats.values()):
7481 if t < v + HEARTBEAT_TIMEOUT:
7482 n += 1
7483
7484 return n
7485
7486
7487 def is_waiting_for_attach(self):
7488 if self.get_clients_attached() != 1:
7489 return False
7490
7491 if list(self.m_heartbeats.keys()) != [0]:
7492 return False
7493
7494 return True
7495
7496
7497 def _break(self, ctx, frame, event, arg):
7498 """
7499 Main break logic.
7500 """
7501
7502 global g_fos_exit
7503 global g_module_main
7504
7505 if not self.is_break(ctx, frame, event) and not ctx.is_breakpoint():
7506 ctx.set_tracers()
7507 return
7508
7509 ctx.m_fBroken = True
7510 f_full_notification = False
7511 f_uhe_notification = False
7512
7513 step_tid = self.m_step_tid
7514
7515 try:
7516 self.m_state_manager.acquire()
7517 if self.m_state_manager.get_state() != STATE_BROKEN:
7518 self.set_break_dont_lock()
7519
7520 if g_module_main == -1:
7521 try:
7522 g_module_main = sys.modules['__main__']
7523 except:
7524 g_module_main = None
7525
7526 if not is_py3k() and not frame.f_exc_traceback is None:
7527 ctx.set_exc_info((frame.f_exc_type, frame.f_exc_value, frame.f_exc_traceback))
7528
7529 if is_py3k() and ctx.get_exc_info() == None and sys.exc_info()[2] != None:
7530 ctx.set_exc_info(sys.exc_info())
7531
7532 try:
7533 t = current_thread()
7534 ctx.m_thread_name = thread_get_name(t)
7535 except:
7536 pass
7537
7538 if ctx.m_fUnhandledException and not self.m_fUnhandledException:
7539 self.m_fUnhandledException = True
7540 f_uhe_notification = True
7541
7542 if self.is_auto_fork_first_stage(ctx.m_thread_id):
7543 self.m_saved_step = (self.m_step_tid, self.m_saved_next, self.m_return_frame)
7544 self.m_saved_next = None
7545 self.m_bp_manager.m_fhard_tbp = True
7546
7547 if self.m_f_first_to_break or (self.m_current_ctx == ctx):
7548 self.m_current_ctx = ctx
7549 self.m_lastest_event = event
7550
7551 self.m_step_tid = None
7552 self.m_next_frame = None
7553 self.m_return_frame = None
7554 self.m_saved_next = None
7555
7556 self.m_bp_manager.del_temp_breakpoint(breakpoint = ctx.get_breakpoint())
7557
7558 self.m_f_first_to_break = False
7559 f_full_notification = True
7560
7561 finally:
7562 self.m_state_manager.release()
7563
7564 ffork_second_stage = self.handle_fork(ctx)
7565 self.handle_exec(ctx)
7566
7567 if self.is_auto_fork_first_stage(ctx.m_thread_id):
7568 self.request_go_quiet()
7569
7570 elif self.m_ffork_auto and ffork_second_stage:
7571 (self.m_step_tid, self.m_next_frame, self.m_return_frame) = self.m_saved_step
7572 self.m_saved_step = (None, None, None)
7573 self.m_bp_manager.m_fhard_tbp = False
7574 self.request_go_quiet()
7575
7576 elif self.get_clients_attached() == 0:
7577 #print_debug('state: %s' % self.m_state_manager.get_state())
7578 self.request_go_quiet()
7579
7580 elif step_tid == ctx.m_thread_id and frame.f_code.co_name == 'rpdb2_import_wrapper':
7581 self.request_step_quiet()
7582
7583 else:
7584 if f_full_notification:
7585 self.send_events(None)
7586 else:
7587 self.notify_thread_broken(ctx.m_thread_id, ctx.m_thread_name)
7588 self.notify_namespace()
7589
7590 if f_uhe_notification:
7591 self.send_unhandled_exception_event()
7592
7593 state = self.m_state_manager.wait_for_state([STATE_RUNNING])
7594
7595 self.prepare_fork_step(ctx.m_thread_id)
7596 self.prepare_exec_step(ctx.m_thread_id)
7597
7598 ctx.m_fUnhandledException = False
7599 ctx.m_fBroken = False
7600 ctx.set_tracers()
7601 ctx.reset_exc_info()
7602
7603 if g_fos_exit:
7604 g_fos_exit = False
7605 self.send_event_exit()
7606 time.sleep(1.0)
7607 self.stoptrace()
7608
7609
7610 def is_auto_fork_first_stage(self, tid):
7611 if not self.m_ffork_auto:
7612 return False
7613
7614 return tid == g_forktid and g_forkpid == None
7615
7616
7617 def prepare_fork_step(self, tid):
7618 global g_forkpid
7619 global g_ignore_broken_pipe
7620
7621 if tid != g_forktid:
7622 return
7623
7624 self.m_step_tid = tid
7625 g_forkpid = os.getpid()
7626
7627 if not self.m_ffork_into_child:
7628 return
7629
7630 n = self.get_clients_attached()
7631 self.send_fork_switch(n)
7632 time.sleep(0.5)
7633 g_server.shutdown()
7634 CThread.joinAll()
7635
7636 g_ignore_broken_pipe = time.time()
7637
7638
7639 def handle_fork(self, ctx):
7640 global g_forktid
7641 global g_forkpid
7642
7643 tid = ctx.m_thread_id
7644
7645 if g_forkpid == None or tid != g_forktid:
7646 return False
7647
7648 forkpid = g_forkpid
7649 g_forkpid = None
7650 g_forktid = None
7651
7652 if os.getpid() == forkpid:
7653 #
7654 # Parent side of fork().
7655 #
7656
7657 if not self.m_ffork_into_child:
7658 #CThread.clearJoin()
7659 #g_server.jumpstart()
7660
7661 return True
7662
7663 self.stoptrace()
7664 return False
7665
7666 #
7667 # Child side of fork().
7668 #
7669
7670 if not self.m_ffork_into_child:
7671 self.stoptrace()
7672 return False
7673
7674 self.m_threads = {tid: ctx}
7675
7676 CThread.clearJoin()
7677 g_server.jumpstart()
7678
7679 return True
7680
7681
7682 def prepare_exec_step(self, tid):
7683 global g_execpid
7684
7685 if tid != g_exectid:
7686 return
7687
7688 self.m_step_tid = tid
7689 g_execpid = os.getpid()
7690
7691 n = self.get_clients_attached()
7692 self.send_exec_switch(n)
7693 time.sleep(0.5)
7694 g_server.shutdown()
7695 CThread.joinAll()
7696
7697
7698 def handle_exec(self, ctx):
7699 global g_exectid
7700 global g_execpid
7701
7702 tid = ctx.m_thread_id
7703
7704 if g_execpid == None or tid != g_exectid:
7705 return False
7706
7707 g_execpid = None
7708 g_exectid = None
7709
7710 #
7711 # If we are here it means that the exec failed.
7712 # Jumpstart the debugger to allow debugging to continue.
7713 #
7714
7715 CThread.clearJoin()
7716 g_server.jumpstart()
7717
7718 return True
7719
7720
7721 def notify_thread_broken(self, tid, name):
7722 """
7723 Notify that thread (tid) has broken.
7724 This notification is sent for each thread that breaks after
7725 the first one.
7726 """
7727
7728 _event = CEventThreadBroken(tid, name)
7729 self.m_event_dispatcher.fire_event(_event)
7730
7731
7732 def notify_namespace(self):
7733 """
7734 Notify that a namespace update query should be done.
7735 """
7736
7737 _event = CEventNamespace()
7738 self.m_event_dispatcher.fire_event(_event)
7739
7740
7741 def get_state(self):
7742 return self.m_state_manager.get_state()
7743
7744
7745 def verify_broken(self):
7746 if self.m_state_manager.get_state() != STATE_BROKEN:
7747 raise DebuggerNotBroken
7748
7749
7750 def get_current_filename(self, frame_index, fException):
7751 """
7752 Return path of sources corresponding to the frame at depth
7753 'frame_index' down the stack of the current thread.
7754 """
7755
7756 ctx = self.get_current_ctx()
7757
7758 try:
7759 f = None
7760 base_frame = ctx.frame_acquire()
7761
7762 (f, frame_lineno) = ctx.get_frame(base_frame, frame_index, fException)
7763 frame_filename = calc_frame_path(f)
7764
7765 return frame_filename
7766
7767 finally:
7768 f = None
7769 base_frame = None
7770 ctx.frame_release()
7771
7772
7773 def get_threads(self):
7774 return self.m_threads
7775
7776
7777 def set_break_dont_lock(self):
7778 self.m_f_first_to_break = True
7779
7780 self.m_state_manager.set_state(STATE_BROKEN, fLock = False)
7781
7782 self.set_break_flag()
7783 self.set_all_tracers()
7784
7785
7786 def request_break(self):
7787 """
7788 Ask debugger to break (pause debuggee).
7789 """
7790
7791 if len(self.m_threads) == 0:
7792 self.wait_for_first_thread()
7793
7794 try:
7795 self.m_state_manager.acquire()
7796 if self.m_state_manager.get_state() == STATE_BROKEN:
7797 return
7798
7799 self.set_break_dont_lock()
7800
7801 finally:
7802 self.m_state_manager.release()
7803
7804 self.send_events(None)
7805
7806
7807 def request_go_quiet(self, fLock = True):
7808 try:
7809 self.request_go(fLock)
7810
7811 except DebuggerNotBroken:
7812 pass
7813
7814
7815 def request_go(self, fLock = True):
7816 """
7817 Let debugger run.
7818 """
7819
7820 try:
7821 if fLock:
7822 self.m_state_manager.acquire()
7823
7824 self.verify_broken()
7825
7826 self.m_fUnhandledException = False
7827 self.m_state_manager.set_state(STATE_RUNNING, fLock = False)
7828
7829 if self.m_fembedded:
7830 time.sleep(0.33)
7831
7832 self.set_break_flag()
7833
7834 finally:
7835 if fLock:
7836 self.m_state_manager.release()
7837
7838
7839 def request_go_breakpoint(self, filename, scope, lineno, frame_index, fException):
7840 """
7841 Let debugger run until temp breakpoint as defined in the arguments.
7842 """
7843
7844 assert(is_unicode(filename))
7845 assert(is_unicode(scope))
7846
7847 try:
7848 self.m_state_manager.acquire()
7849 self.verify_broken()
7850
7851 if filename in [None, '']:
7852 _filename = self.get_current_filename(frame_index, fException)
7853 elif not is_provider_filesystem(filename):
7854 _filename = as_string(filename, sys.getfilesystemencoding())
7855 else:
7856 _filename = FindFile(filename, fModules = True)
7857
7858 self.m_bp_manager.set_temp_breakpoint(_filename, scope, lineno)
7859 self.set_all_tracers()
7860 self.request_go(fLock = False)
7861
7862 finally:
7863 self.m_state_manager.release()
7864
7865
7866 def request_step_quiet(self, fLock = True):
7867 try:
7868 self.request_step(fLock)
7869
7870 except DebuggerNotBroken:
7871 pass
7872
7873
7874 def request_step(self, fLock = True):
7875 """
7876 Let debugger run until next statement is reached or a breakpoint
7877 is hit in another thread.
7878 """
7879
7880 try:
7881 if fLock:
7882 self.m_state_manager.acquire()
7883
7884 self.verify_broken()
7885
7886 try:
7887 ctx = self.get_current_ctx()
7888 except NoThreads:
7889 return
7890
7891 self.m_step_tid = ctx.m_thread_id
7892 self.m_next_frame = None
7893 self.m_return_frame = None
7894
7895 self.request_go(fLock = False)
7896
7897 finally:
7898 if fLock:
7899 self.m_state_manager.release()
7900
7901
7902 def request_next(self):
7903 """
7904 Let debugger run until next statement in the same frame
7905 is reached or a breakpoint is hit in another thread.
7906 """
7907
7908 try:
7909 self.m_state_manager.acquire()
7910 self.verify_broken()
7911
7912 try:
7913 ctx = self.get_current_ctx()
7914 except NoThreads:
7915 return
7916
7917 if self.m_lastest_event in ['return', 'exception']:
7918 return self.request_step(fLock = False)
7919
7920 self.m_next_frame = ctx.m_frame
7921 self.m_return_frame = None
7922
7923 self.request_go(fLock = False)
7924
7925 finally:
7926 self.m_state_manager.release()
7927
7928
7929 def request_return(self):
7930 """
7931 Let debugger run until end of frame frame is reached
7932 or a breakpoint is hit in another thread.
7933 """
7934
7935 try:
7936 self.m_state_manager.acquire()
7937 self.verify_broken()
7938
7939 try:
7940 ctx = self.get_current_ctx()
7941 except NoThreads:
7942 return
7943
7944 if self.m_lastest_event == 'return':
7945 return self.request_step(fLock = False)
7946
7947 self.m_next_frame = None
7948 self.m_return_frame = ctx.m_frame
7949
7950 self.request_go(fLock = False)
7951
7952 finally:
7953 self.m_state_manager.release()
7954
7955
7956 def request_jump(self, lineno):
7957 """
7958 Jump to line number 'lineno'.
7959 """
7960
7961 try:
7962 self.m_state_manager.acquire()
7963 self.verify_broken()
7964
7965 try:
7966 ctx = self.get_current_ctx()
7967 except NoThreads:
7968 return
7969
7970 frame = ctx.m_frame
7971 code = frame.f_code
7972
7973 valid_lines = CalcValidLines(code)
7974 sbi = CScopeBreakInfo(as_unicode(''), valid_lines)
7975 l = sbi.CalcScopeLine(lineno)
7976
7977 frame.f_lineno = l
7978
7979 finally:
7980 frame = None
7981 self.m_state_manager.release()
7982
7983 self.send_events(None)
7984
7985
7986 def set_thread(self, tid):
7987 """
7988 Switch focus to specified thread.
7989 """
7990
7991 try:
7992 self.m_state_manager.acquire()
7993 self.verify_broken()
7994
7995 try:
7996 if (tid >= 0) and (tid < 100):
7997 _tid = list(self.m_threads.keys())[tid]
7998 else:
7999 _tid = tid
8000
8001 ctx = self.m_threads[_tid]
8002 except (IndexError, KeyError):
8003 raise ThreadNotFound
8004
8005 self.m_current_ctx = ctx
8006 self.m_lastest_event = ctx.m_event
8007
8008 finally:
8009 self.m_state_manager.release()
8010
8011 self.send_events(None)
8012
8013
8014
8015 class CDebuggerEngine(CDebuggerCore):
8016 """
8017 Main class for the debugger.
8018 Adds functionality on top of CDebuggerCore.
8019 """
8020
8021 def __init__(self, fembedded = False):
8022 CDebuggerCore.__init__(self, fembedded)
8023
8024 event_type_dict = {
8025 CEventState: {},
8026 CEventStackDepth: {},
8027 CEventBreakpoint: {},
8028 CEventThreads: {},
8029 CEventNoThreads: {},
8030 CEventThreadBroken: {},
8031 CEventNamespace: {},
8032 CEventUnhandledException: {},
8033 CEventStack: {},
8034 CEventNull: {},
8035 CEventExit: {},
8036 CEventForkSwitch: {},
8037 CEventExecSwitch: {},
8038 CEventSynchronicity: {},
8039 CEventTrap: {},
8040 CEventForkMode: {},
8041 CEventPsycoWarning: {},
8042 CEventConflictingModules: {},
8043 CEventSignalIntercepted: {},
8044 CEventSignalException: {},
8045 CEventClearSourceCache: {},
8046 CEventEmbeddedSync: {}
8047 }
8048
8049 self.m_event_queue = CEventQueue(self.m_event_dispatcher)
8050 self.m_event_queue.register_event_types(event_type_dict)
8051
8052 event_type_dict = {CEventSync: {}}
8053 self.m_event_dispatcher.register_callback(self.send_events, event_type_dict, fSingleUse = False)
8054
8055
8056 def shutdown(self):
8057 self.m_event_queue.shutdown()
8058
8059 CDebuggerCore.shutdown(self)
8060
8061
8062
8063 def sync_with_events(self, fException, fSendUnhandled):
8064 """
8065 Send debugger state to client.
8066 """
8067
8068 if len(self.m_threads) == 0:
8069 self.wait_for_first_thread()
8070
8071 index = self.m_event_queue.get_event_index()
8072 event = CEventSync(fException, fSendUnhandled)
8073 self.m_event_dispatcher.fire_event(event)
8074 return index
8075
8076
8077 def trap_conflicting_modules(self):
8078 modules_list = []
8079
8080 for m in CONFLICTING_MODULES:
8081 if m in g_found_conflicting_modules:
8082 continue
8083
8084 if not m in sys.modules:
8085 continue
8086
8087 if m == 'psyco':
8088 #
8089 # Old event kept for compatibility.
8090 #
8091 event = CEventPsycoWarning()
8092 self.m_event_dispatcher.fire_event(event)
8093
8094 g_found_conflicting_modules.append(m)
8095 modules_list.append(as_unicode(m))
8096
8097 if modules_list == []:
8098 return False
8099
8100 event = CEventConflictingModules(modules_list)
8101 self.m_event_dispatcher.fire_event(event)
8102
8103 return True
8104
8105
8106 def wait_for_event(self, timeout, event_index):
8107 """
8108 Wait for new events and return them as list of events.
8109 """
8110
8111 self.cancel_request_go_timer()
8112 self.trap_conflicting_modules()
8113
8114 (new_event_index, sel) = self.m_event_queue.wait_for_event(timeout, event_index)
8115
8116 if self.trap_conflicting_modules():
8117 (new_event_index, sel) = self.m_event_queue.wait_for_event(timeout, event_index)
8118
8119 return (new_event_index, sel)
8120
8121
8122 def set_breakpoint(self, filename, scope, lineno, fEnabled, expr, frame_index, fException, encoding):
8123 print_debug('Setting breakpoint to: %s, %s, %d' % (repr(filename), scope, lineno))
8124
8125 assert(is_unicode(filename))
8126 assert(is_unicode(scope))
8127 assert(is_unicode(expr))
8128
8129 fLock = False
8130
8131 try:
8132 if filename in [None, '']:
8133 self.m_state_manager.acquire()
8134 fLock = True
8135 self.verify_broken()
8136
8137 _filename = self.get_current_filename(frame_index, fException)
8138 elif not is_provider_filesystem(filename):
8139 _filename = as_string(filename, sys.getfilesystemencoding())
8140 else:
8141 _filename = FindFile(filename, fModules = True)
8142
8143 if expr != '':
8144 try:
8145 encoding = self.__calc_encoding(encoding, filename = _filename)
8146 _expr = as_bytes(ENCODING_SOURCE % encoding + expr, encoding)
8147 compile(_expr, '<string>', 'eval')
8148 except:
8149 raise SyntaxError
8150
8151 encoding = as_unicode(encoding)
8152
8153 bp = self.m_bp_manager.set_breakpoint(_filename, scope, lineno, fEnabled, expr, encoding)
8154 self.set_all_tracers()
8155
8156 event = CEventBreakpoint(bp)
8157 #print_debug(repr(vars(bp)))
8158 self.m_event_dispatcher.fire_event(event)
8159
8160 finally:
8161 if fLock:
8162 self.m_state_manager.release()
8163
8164
8165 def disable_breakpoint(self, id_list, fAll):
8166 self.m_bp_manager.disable_breakpoint(id_list, fAll)
8167 self.set_all_tracers()
8168
8169 event = CEventBreakpoint(None, CEventBreakpoint.DISABLE, id_list, fAll)
8170 self.m_event_dispatcher.fire_event(event)
8171
8172
8173 def enable_breakpoint(self, id_list, fAll):
8174 self.m_bp_manager.enable_breakpoint(id_list, fAll)
8175 self.set_all_tracers()
8176
8177 event = CEventBreakpoint(None, CEventBreakpoint.ENABLE, id_list, fAll)
8178 self.m_event_dispatcher.fire_event(event)
8179
8180
8181 def delete_breakpoint(self, id_list, fAll):
8182 self.m_bp_manager.delete_breakpoint(id_list, fAll)
8183 self.set_all_tracers()
8184
8185 event = CEventBreakpoint(None, CEventBreakpoint.REMOVE, id_list, fAll)
8186 self.m_event_dispatcher.fire_event(event)
8187
8188
8189 def get_breakpoints(self):
8190 """
8191 return id->breakpoint dictionary.
8192 """
8193
8194 bpl = self.m_bp_manager.get_breakpoints()
8195 _items = [(id, breakpoint_copy(bp)) for (id, bp) in bpl.items()]
8196 for (id, bp) in _items:
8197 bp.m_code = None
8198
8199 _bpl = dict(_items)
8200
8201 return _bpl
8202
8203
8204 def send_events(self, event):
8205 """
8206 Send series of events that define the debugger state.
8207 """
8208
8209 if isinstance(event, CEventSync):
8210 fException = event.m_fException
8211 fSendUnhandled = event.m_fSendUnhandled
8212 else:
8213 fException = False
8214 fSendUnhandled = False
8215
8216 try:
8217 if isinstance(event, CEventSync) and not fException:
8218 self.m_state_manager.set_state()
8219
8220 self.send_stack_depth()
8221 self.send_threads_event(fException)
8222 self.send_stack_event(fException)
8223 self.send_namespace_event()
8224
8225 if fSendUnhandled and self.m_fUnhandledException:
8226 self.send_unhandled_exception_event()
8227
8228 except NoThreads:
8229 self.send_no_threads_event()
8230
8231 except:
8232 print_debug_exception()
8233 raise
8234
8235
8236 def send_unhandled_exception_event(self):
8237 event = CEventUnhandledException()
8238 self.m_event_dispatcher.fire_event(event)
8239
8240
8241 def send_stack_depth(self):
8242 """
8243 Send event with stack depth and exception stack depth.
8244 """
8245
8246 f = None
8247 tb = None
8248 ctx = self.get_current_ctx()
8249
8250 try:
8251 try:
8252 f = ctx.frame_acquire()
8253 except ThreadDone:
8254 return
8255
8256 s = my_extract_stack(f)
8257 s = [1 for (a, b, c, d) in s if g_fDebug or c != 'rpdb2_import_wrapper']
8258
8259 stack_depth = len(s)
8260
8261 tb = get_traceback(f, ctx)
8262 if tb == None:
8263 stack_depth_exception = None
8264
8265 else:
8266 s = my_extract_stack(tb.tb_frame.f_back)
8267 s += my_extract_tb(tb)
8268 s = [1 for (a, b, c, d) in s if g_fDebug or c != 'rpdb2_import_wrapper']
8269
8270 stack_depth_exception = len(s)
8271
8272 event = CEventStackDepth(stack_depth, stack_depth_exception)
8273 self.m_event_dispatcher.fire_event(event)
8274
8275 finally:
8276 f = None
8277 tb = None
8278 ctx.frame_release()
8279
8280
8281 def send_threads_event(self, fException):
8282 """
8283 Send event with current thread list.
8284 In case of exception, send only the current thread.
8285 """
8286
8287 tl = self.get_thread_list()
8288
8289 if fException:
8290 ctid = tl[0]
8291 itl = tl[1]
8292 _itl = [a for a in itl if a[DICT_KEY_TID] == ctid]
8293 _tl = (ctid, _itl)
8294 else:
8295 _tl = tl
8296
8297 event = CEventThreads(*_tl)
8298 self.m_event_dispatcher.fire_event(event)
8299
8300
8301 def send_stack_event(self, fException):
8302 sl = self.get_stack([], False, fException)
8303
8304 if len(sl) == 0:
8305 return
8306
8307 event = CEventStack(sl[0])
8308 self.m_event_dispatcher.fire_event(event)
8309
8310
8311 def send_namespace_event(self):
8312 """
8313 Send event notifying namespace should be queried again.
8314 """
8315
8316 event = CEventNamespace()
8317 self.m_event_dispatcher.fire_event(event)
8318
8319
8320 def send_no_threads_event(self):
8321 _event = CEventNoThreads()
8322 self.m_event_dispatcher.fire_event(_event)
8323
8324
8325 def send_event_null(self):
8326 """
8327 Make the event waiter return.
8328 """
8329
8330 event = CEventNull()
8331 self.m_event_dispatcher.fire_event(event)
8332
8333
8334 def __get_stack(self, ctx, ctid, fException):
8335 tid = ctx.m_thread_id
8336
8337 f = None
8338 _f = None
8339 tb = None
8340 _tb = None
8341
8342 try:
8343 try:
8344 f = ctx.frame_acquire()
8345 except ThreadDone:
8346 return None
8347
8348 if fException:
8349 tb = get_traceback(f, ctx)
8350 if tb == None:
8351 raise NoExceptionFound
8352
8353 _tb = tb
8354 while _tb.tb_next is not None:
8355 _tb = _tb.tb_next
8356
8357 _f = _tb.tb_frame
8358 s = my_extract_stack(tb.tb_frame.f_back)
8359 s += my_extract_tb(tb)
8360
8361 else:
8362 _f = f
8363 s = my_extract_stack(f)
8364
8365 code_list = []
8366 while _f is not None:
8367 rc = repr(_f.f_code).split(',')[0].split()[-1]
8368 rc = as_unicode(rc)
8369 code_list.insert(0, rc)
8370 _f = _f.f_back
8371
8372 finally:
8373 f = None
8374 _f = None
8375 tb = None
8376 _tb = None
8377
8378 ctx.frame_release()
8379
8380 #print code_list
8381
8382 __s = [(a, b, c, d) for (a, b, c, d) in s if g_fDebug or c != 'rpdb2_import_wrapper']
8383
8384 if (ctx.m_uef_lineno is not None) and (len(__s) > 0):
8385 (a, b, c, d) = __s[0]
8386 __s = [(a, ctx.m_uef_lineno, c, d)] + __s[1:]
8387
8388 r = {}
8389 r[DICT_KEY_STACK] = __s
8390 r[DICT_KEY_CODE_LIST] = code_list
8391 r[DICT_KEY_TID] = tid
8392 r[DICT_KEY_BROKEN] = ctx.m_fBroken
8393 r[DICT_KEY_EVENT] = as_unicode([ctx.m_event, 'exception'][fException])
8394
8395 if tid == ctid:
8396 r[DICT_KEY_CURRENT_TID] = True
8397
8398 return r
8399
8400
8401 def get_stack(self, tid_list, fAll, fException):
8402 if fException and (fAll or (len(tid_list) != 0)):
8403 raise BadArgument
8404
8405 ctx = self.get_current_ctx()
8406 ctid = ctx.m_thread_id
8407
8408 if fAll:
8409 ctx_list = list(self.get_threads().values())
8410 elif fException or (len(tid_list) == 0):
8411 ctx_list = [ctx]
8412 else:
8413 ctx_list = [self.get_threads().get(t, None) for t in tid_list]
8414
8415 _sl = [self.__get_stack(ctx, ctid, fException) for ctx in ctx_list if ctx is not None]
8416 sl = [s for s in _sl if s is not None]
8417
8418 return sl
8419
8420
8421 def get_source_file(self, filename, lineno, nlines, frame_index, fException):
8422 assert(is_unicode(filename))
8423
8424 if lineno < 1:
8425 lineno = 1
8426 nlines = -1
8427
8428 _lineno = lineno
8429 r = {}
8430 frame_filename = None
8431
8432 try:
8433 ctx = self.get_current_ctx()
8434
8435 try:
8436 f = None
8437 base_frame = None
8438
8439 base_frame = ctx.frame_acquire()
8440 (f, frame_lineno) = ctx.get_frame(base_frame, frame_index, fException)
8441 frame_filename = calc_frame_path(f)
8442
8443 finally:
8444 f = None
8445 base_frame = None
8446 ctx.frame_release()
8447
8448 frame_event = [[ctx.m_event, 'call'][frame_index > 0], 'exception'][fException]
8449
8450 except NoThreads:
8451 if filename in [None, '']:
8452 raise
8453
8454 if filename in [None, '']:
8455 __filename = frame_filename
8456 r[DICT_KEY_TID] = ctx.m_thread_id
8457 elif not is_provider_filesystem(filename):
8458 __filename = as_string(filename, sys.getfilesystemencoding())
8459 else:
8460 __filename = FindFile(filename, fModules = True)
8461 if not IsPythonSourceFile(__filename):
8462 raise NotPythonSource
8463
8464 _filename = winlower(__filename)
8465
8466 lines = []
8467 breakpoints = {}
8468 fhide_pwd_mode = False
8469
8470 while nlines != 0:
8471 try:
8472 g_traceback_lock.acquire()
8473 line = get_source_line(_filename, _lineno)
8474
8475 finally:
8476 g_traceback_lock.release()
8477
8478 if line == '':
8479 break
8480
8481 #
8482 # Remove any trace of session password from data structures that
8483 # go over the network.
8484 #
8485
8486 if fhide_pwd_mode:
8487 if not ')' in line:
8488 line = as_unicode('...\n')
8489 else:
8490 line = '...""")' + line.split(')', 1)[1]
8491 fhide_pwd_mode = False
8492
8493 elif 'start_embedded_debugger(' in line:
8494 ls = line.split('start_embedded_debugger(', 1)
8495 line = ls[0] + 'start_embedded_debugger("""...Removed-password-from-output...'
8496
8497 if ')' in ls[1]:
8498 line += '""")' + ls[1].split(')', 1)[1]
8499 else:
8500 line += '\n'
8501 fhide_pwd_mode = True
8502
8503 lines.append(line)
8504
8505 try:
8506 bp = self.m_bp_manager.get_breakpoint(_filename, _lineno)
8507 breakpoints[_lineno] = as_unicode([STATE_DISABLED, STATE_ENABLED][bp.isEnabled()])
8508 except KeyError:
8509 pass
8510
8511 _lineno += 1
8512 nlines -= 1
8513
8514 if frame_filename == _filename:
8515 r[DICT_KEY_FRAME_LINENO] = frame_lineno
8516 r[DICT_KEY_EVENT] = as_unicode(frame_event)
8517 r[DICT_KEY_BROKEN] = ctx.m_fBroken
8518
8519 r[DICT_KEY_LINES] = lines
8520 r[DICT_KEY_FILENAME] = as_unicode(_filename, sys.getfilesystemencoding())
8521 r[DICT_KEY_BREAKPOINTS] = breakpoints
8522 r[DICT_KEY_FIRST_LINENO] = lineno
8523
8524 return r
8525
8526
8527 def __get_source(self, ctx, nlines, frame_index, fException):
8528 tid = ctx.m_thread_id
8529 _frame_index = [0, frame_index][tid == self.m_current_ctx.m_thread_id]
8530
8531 try:
8532 try:
8533 f = None
8534 base_frame = None
8535
8536 base_frame = ctx.frame_acquire()
8537 (f, frame_lineno) = ctx.get_frame(base_frame, _frame_index, fException)
8538 frame_filename = calc_frame_path(f)
8539
8540 except (ThreadDone, InvalidFrame):
8541 return None
8542
8543 finally:
8544 f = None
8545 base_frame = None
8546 ctx.frame_release()
8547
8548 frame_event = [[ctx.m_event, 'call'][frame_index > 0], 'exception'][fException]
8549
8550 first_line = max(1, frame_lineno - nlines // 2)
8551 _lineno = first_line
8552
8553 lines = []
8554 breakpoints = {}
8555 fhide_pwd_mode = False
8556
8557 while nlines != 0:
8558 try:
8559 g_traceback_lock.acquire()
8560 line = get_source_line(frame_filename, _lineno)
8561
8562 finally:
8563 g_traceback_lock.release()
8564
8565 if line == '':
8566 break
8567
8568 #
8569 # Remove any trace of session password from data structures that
8570 # go over the network.
8571 #
8572
8573 if fhide_pwd_mode:
8574 if not ')' in line:
8575 line = as_unicode('...\n')
8576 else:
8577 line = '...""")' + line.split(')', 1)[1]
8578 fhide_pwd_mode = False
8579
8580 elif 'start_embedded_debugger(' in line:
8581 ls = line.split('start_embedded_debugger(', 1)
8582 line = ls[0] + 'start_embedded_debugger("""...Removed-password-from-output...'
8583
8584 if ')' in ls[1]:
8585 line += '""")' + ls[1].split(')', 1)[1]
8586 else:
8587 line += '\n'
8588 fhide_pwd_mode = True
8589
8590 lines.append(line)
8591
8592 try:
8593 bp = self.m_bp_manager.get_breakpoint(frame_filename, _lineno)
8594 breakpoints[_lineno] = as_unicode([STATE_DISABLED, STATE_ENABLED][bp.isEnabled()])
8595 except KeyError:
8596 pass
8597
8598 _lineno += 1
8599 nlines -= 1
8600
8601 r = {}
8602
8603 r[DICT_KEY_FRAME_LINENO] = frame_lineno
8604 r[DICT_KEY_EVENT] = as_unicode(frame_event)
8605 r[DICT_KEY_BROKEN] = ctx.m_fBroken
8606 r[DICT_KEY_TID] = tid
8607 r[DICT_KEY_LINES] = lines
8608 r[DICT_KEY_FILENAME] = as_unicode(frame_filename, sys.getfilesystemencoding())
8609 r[DICT_KEY_BREAKPOINTS] = breakpoints
8610 r[DICT_KEY_FIRST_LINENO] = first_line
8611
8612 return r
8613
8614
8615 def get_source_lines(self, nlines, fAll, frame_index, fException):
8616 if fException and fAll:
8617 raise BadArgument
8618
8619 if fAll:
8620 ctx_list = list(self.get_threads().values())
8621 else:
8622 ctx = self.get_current_ctx()
8623 ctx_list = [ctx]
8624
8625 _sl = [self.__get_source(ctx, nlines, frame_index, fException) for ctx in ctx_list]
8626 sl = [s for s in _sl if s is not None]
8627
8628 return sl
8629
8630
8631 def __get_locals_globals(self, frame_index, fException, fReadOnly = False):
8632 ctx = self.get_current_ctx()
8633 (_globals, _locals, _original_locals_copy) = ctx.get_locals_copy(frame_index, fException, fReadOnly)
8634
8635 return (_globals, _locals, _original_locals_copy)
8636
8637
8638 def __calc_number_of_subnodes(self, r):
8639 for t in [bytearray, bytes, str, str8, unicode, int, long, float, bool, type(None)]:
8640 if t is type(r):
8641 return 0
8642
8643 try:
8644 try:
8645 if isinstance(r, frozenset) or isinstance(r, set):
8646 return len(r)
8647
8648 except NameError:
8649 pass
8650
8651 if isinstance(r, sets.BaseSet):
8652 return len(r)
8653
8654 if isinstance(r, dict):
8655 return len(r)
8656
8657 if isinstance(r, list):
8658 return len(r)
8659
8660 if isinstance(r, tuple):
8661 return len(r)
8662
8663 return len(dir(r))
8664
8665 except AttributeError:
8666 return 0
8667
8668 return 0
8669
8670
8671 def __calc_subnodes(self, expr, r, fForceNames, filter_level, repr_limit, encoding):
8672 snl = []
8673
8674 try:
8675 if isinstance(r, frozenset) or isinstance(r, set):
8676 if len(r) > MAX_SORTABLE_LENGTH:
8677 g = r
8678 else:
8679 g = [i for i in r]
8680 sort(g)
8681
8682 for i in g:
8683 if len(snl) >= MAX_NAMESPACE_ITEMS:
8684 snl.append(MAX_NAMESPACE_WARNING)
8685 break
8686
8687 is_valid = [True]
8688 rk = repr_ltd(i, REPR_ID_LENGTH, encoding = ENCODING_RAW_I)
8689
8690 e = {}
8691 e[DICT_KEY_EXPR] = as_unicode('_RPDB2_FindRepr((%s), %d)["%s"]' % (expr, REPR_ID_LENGTH, rk.replace('"', '&quot')))
8692 e[DICT_KEY_NAME] = repr_ltd(i, repr_limit, encoding)
8693 e[DICT_KEY_REPR] = repr_ltd(i, repr_limit, encoding, is_valid)
8694 e[DICT_KEY_IS_VALID] = is_valid[0]
8695 e[DICT_KEY_TYPE] = as_unicode(parse_type(type(i)))
8696 e[DICT_KEY_N_SUBNODES] = self.__calc_number_of_subnodes(i)
8697
8698 snl.append(e)
8699
8700 return snl
8701
8702 except NameError:
8703 pass
8704
8705 if isinstance(r, sets.BaseSet):
8706 if len(r) > MAX_SORTABLE_LENGTH:
8707 g = r
8708 else:
8709 g = [i for i in r]
8710 sort(g)
8711
8712 for i in g:
8713 if len(snl) >= MAX_NAMESPACE_ITEMS:
8714 snl.append(MAX_NAMESPACE_WARNING)
8715 break
8716
8717 is_valid = [True]
8718 rk = repr_ltd(i, REPR_ID_LENGTH, encoding = ENCODING_RAW_I)
8719
8720 e = {}
8721 e[DICT_KEY_EXPR] = as_unicode('_RPDB2_FindRepr((%s), %d)["%s"]' % (expr, REPR_ID_LENGTH, rk.replace('"', '&quot')))
8722 e[DICT_KEY_NAME] = repr_ltd(i, repr_limit, encoding)
8723 e[DICT_KEY_REPR] = repr_ltd(i, repr_limit, encoding, is_valid)
8724 e[DICT_KEY_IS_VALID] = is_valid[0]
8725 e[DICT_KEY_TYPE] = as_unicode(parse_type(type(i)))
8726 e[DICT_KEY_N_SUBNODES] = self.__calc_number_of_subnodes(i)
8727
8728 snl.append(e)
8729
8730 return snl
8731
8732 if isinstance(r, list) or isinstance(r, tuple):
8733 for i, v in enumerate(r[0: MAX_NAMESPACE_ITEMS]):
8734 is_valid = [True]
8735 e = {}
8736 e[DICT_KEY_EXPR] = as_unicode('(%s)[%d]' % (expr, i))
8737 e[DICT_KEY_NAME] = as_unicode(repr(i))
8738 e[DICT_KEY_REPR] = repr_ltd(v, repr_limit, encoding, is_valid)
8739 e[DICT_KEY_IS_VALID] = is_valid[0]
8740 e[DICT_KEY_TYPE] = as_unicode(parse_type(type(v)))
8741 e[DICT_KEY_N_SUBNODES] = self.__calc_number_of_subnodes(v)
8742
8743 snl.append(e)
8744
8745 if len(r) > MAX_NAMESPACE_ITEMS:
8746 snl.append(MAX_NAMESPACE_WARNING)
8747
8748 return snl
8749
8750 if isinstance(r, dict):
8751 if filter_level == 2 and expr in ['locals()', 'globals()']:
8752 r = copy.copy(r)
8753 for k, v in list(r.items()):
8754 if parse_type(type(v)) in ['function', 'classobj', 'type']:
8755 del r[k]
8756
8757 if len(r) > MAX_SORTABLE_LENGTH:
8758 kl = r
8759 else:
8760 kl = list(r.keys())
8761 sort(kl)
8762
8763 for k in kl:
8764 #
8765 # Remove any trace of session password from data structures that
8766 # go over the network.
8767 #
8768 if k in ['_RPDB2_FindRepr', '_RPDB2_builtins', '_rpdb2_args', '_rpdb2_pwd', 'm_rpdb2_pwd']:
8769 continue
8770
8771 v = r[k]
8772
8773 if len(snl) >= MAX_NAMESPACE_ITEMS:
8774 snl.append(MAX_NAMESPACE_WARNING)
8775 break
8776
8777 is_valid = [True]
8778 e = {}
8779
8780 if [True for t in [bool, int, float, bytes, str, unicode, type(None)] if t is type(k)]:
8781 rk = repr(k)
8782 if len(rk) < REPR_ID_LENGTH:
8783 e[DICT_KEY_EXPR] = as_unicode('(%s)[%s]' % (expr, rk))
8784
8785 if type(k) is str8:
8786 rk = repr(k)
8787 if len(rk) < REPR_ID_LENGTH:
8788 e[DICT_KEY_EXPR] = as_unicode('(%s)[str8(%s)]' % (expr, rk[1:]))
8789
8790 if not DICT_KEY_EXPR in e:
8791 rk = repr_ltd(k, REPR_ID_LENGTH, encoding = ENCODING_RAW_I)
8792 e[DICT_KEY_EXPR] = as_unicode('_RPDB2_FindRepr((%s), %d)["%s"]' % (expr, REPR_ID_LENGTH, rk.replace('"', '&quot')))
8793
8794 e[DICT_KEY_NAME] = as_unicode([repr_ltd(k, repr_limit, encoding), k][fForceNames])
8795 e[DICT_KEY_REPR] = repr_ltd(v, repr_limit, encoding, is_valid)
8796 e[DICT_KEY_IS_VALID] = is_valid[0]
8797 e[DICT_KEY_TYPE] = as_unicode(parse_type(type(v)))
8798 e[DICT_KEY_N_SUBNODES] = self.__calc_number_of_subnodes(v)
8799
8800 snl.append(e)
8801
8802 return snl
8803
8804 al = calc_attribute_list(r, filter_level)
8805 sort(al)
8806
8807 for a in al:
8808 if a == 'm_rpdb2_pwd':
8809 continue
8810
8811 try:
8812 v = getattr(r, a)
8813 except AttributeError:
8814 continue
8815
8816 if len(snl) >= MAX_NAMESPACE_ITEMS:
8817 snl.append(MAX_NAMESPACE_WARNING)
8818 break
8819
8820 is_valid = [True]
8821 e = {}
8822 e[DICT_KEY_EXPR] = as_unicode('(%s).%s' % (expr, a))
8823 e[DICT_KEY_NAME] = as_unicode(a)
8824 e[DICT_KEY_REPR] = repr_ltd(v, repr_limit, encoding, is_valid)
8825 e[DICT_KEY_IS_VALID] = is_valid[0]
8826 e[DICT_KEY_TYPE] = as_unicode(parse_type(type(v)))
8827 e[DICT_KEY_N_SUBNODES] = self.__calc_number_of_subnodes(v)
8828
8829 snl.append(e)
8830
8831 return snl
8832
8833
8834 def get_exception(self, frame_index, fException):
8835 ctx = self.get_current_ctx()
8836
8837 if is_py3k():
8838 exc_info = ctx.get_exc_info()
8839 if exc_info == None:
8840 return {'type': None, 'value': None, 'traceback': None}
8841
8842 type, value, traceback = exc_info
8843 e = {'type': type, 'value': value, 'traceback': traceback}
8844
8845 return e
8846
8847 try:
8848 f = None
8849 base_frame = None
8850
8851 base_frame = ctx.frame_acquire()
8852 (f, frame_lineno) = ctx.get_frame(base_frame, frame_index, fException)
8853
8854 e = {'type': f.f_exc_type, 'value': f.f_exc_value, 'traceback': f.f_exc_traceback}
8855
8856 return e
8857
8858 finally:
8859 f = None
8860 base_frame = None
8861 ctx.frame_release()
8862
8863
8864 def is_child_of_failure(self, failed_expr_list, expr):
8865 for failed_expr in failed_expr_list:
8866 if expr.startswith(failed_expr):
8867 return True
8868
8869 return False
8870
8871
8872 def calc_expr(self, expr, fExpand, filter_level, frame_index, fException, _globals, _locals, lock, event, rl, index, repr_limit, encoding):
8873 e = {}
8874
8875 try:
8876 __globals = _globals
8877 __locals = _locals
8878
8879 if RPDB_EXEC_INFO in expr:
8880 rpdb_exception_info = self.get_exception(frame_index, fException)
8881 __globals = globals()
8882 __locals = locals()
8883
8884 __locals['_RPDB2_FindRepr'] = _RPDB2_FindRepr
8885
8886 is_valid = [True]
8887 r = eval(expr, __globals, __locals)
8888
8889 e[DICT_KEY_EXPR] = as_unicode(expr)
8890 e[DICT_KEY_REPR] = repr_ltd(r, repr_limit, encoding, is_valid)
8891 e[DICT_KEY_IS_VALID] = is_valid[0]
8892 e[DICT_KEY_TYPE] = as_unicode(parse_type(type(r)))
8893 e[DICT_KEY_N_SUBNODES] = self.__calc_number_of_subnodes(r)
8894
8895 if fExpand and (e[DICT_KEY_N_SUBNODES] > 0):
8896 fForceNames = (expr in ['globals()', 'locals()']) or (RPDB_EXEC_INFO in expr)
8897 e[DICT_KEY_SUBNODES] = self.__calc_subnodes(expr, r, fForceNames, filter_level, repr_limit, encoding)
8898 e[DICT_KEY_N_SUBNODES] = len(e[DICT_KEY_SUBNODES])
8899
8900 except:
8901 print_debug_exception()
8902 e[DICT_KEY_ERROR] = as_unicode(safe_repr(sys.exc_info()))
8903
8904 lock.acquire()
8905 if len(rl) == index:
8906 rl.append(e)
8907 lock.release()
8908
8909 event.set()
8910
8911
8912 def __calc_encoding(self, encoding, fvalidate = False, filename = None):
8913 if encoding != ENCODING_AUTO and not fvalidate:
8914 return encoding
8915
8916 if encoding != ENCODING_AUTO:
8917 try:
8918 codecs.lookup(encoding)
8919 return encoding
8920
8921 except:
8922 pass
8923
8924 if filename == None:
8925 ctx = self.get_current_ctx()
8926 filename = ctx.m_code_context.m_filename
8927
8928 try:
8929 encoding = get_file_encoding(filename)
8930 return encoding
8931
8932 except:
8933 return 'utf-8'
8934
8935
8936
8937 def get_namespace(self, nl, filter_level, frame_index, fException, repr_limit, encoding, fraw):
8938 if fraw:
8939 encoding = ENCODING_RAW_I
8940 else:
8941 encoding = self.__calc_encoding(encoding, fvalidate = True)
8942
8943 try:
8944 (_globals, _locals, x) = self.__get_locals_globals(frame_index, fException, fReadOnly = True)
8945 except:
8946 print_debug_exception()
8947 raise
8948
8949 failed_expr_list = []
8950 rl = []
8951 index = 0
8952 lock = threading.Condition()
8953
8954 for (expr, fExpand) in nl:
8955 if self.is_child_of_failure(failed_expr_list, expr):
8956 continue
8957
8958 event = threading.Event()
8959 args = (expr, fExpand, filter_level, frame_index, fException, _globals, _locals, lock, event, rl, index, repr_limit, encoding)
8960
8961 if self.m_fsynchronicity:
8962 g_server.m_work_queue.post_work_item(target = self.calc_expr, args = args, name = 'calc_expr %s' % expr)
8963 else:
8964 try:
8965 ctx = self.get_current_ctx()
8966 tid = ctx.m_thread_id
8967 send_job(tid, 0, self.calc_expr, *args)
8968 except:
8969 pass
8970
8971 safe_wait(event, 2)
8972
8973 lock.acquire()
8974 if len(rl) == index:
8975 rl.append('error')
8976 failed_expr_list.append(expr)
8977 index += 1
8978 lock.release()
8979
8980 if len(failed_expr_list) > 3:
8981 break
8982
8983 _rl = [r for r in rl if r != 'error']
8984
8985 return _rl
8986
8987
8988 def evaluate(self, expr, frame_index, fException, encoding, fraw):
8989 """
8990 Evaluate expression in context of frame at depth 'frame-index'.
8991 """
8992
8993 result = [(as_unicode(''), as_unicode(STR_SYNCHRONICITY_BAD), as_unicode(''))]
8994
8995 if self.m_fsynchronicity:
8996 self._evaluate(result, expr, frame_index, fException, encoding, fraw)
8997 else:
8998 try:
8999 ctx = self.get_current_ctx()
9000 tid = ctx.m_thread_id
9001 send_job(tid, 1000, self._evaluate, result, expr, frame_index, fException, encoding, fraw)
9002 except:
9003 pass
9004
9005 return result[-1]
9006
9007
9008 def _evaluate(self, result, expr, frame_index, fException, encoding, fraw):
9009 """
9010 Evaluate expression in context of frame at depth 'frame-index'.
9011 """
9012
9013 encoding = self.__calc_encoding(encoding)
9014
9015 (_globals, _locals, x) = self.__get_locals_globals(frame_index, fException)
9016
9017 v = ''
9018 w = ''
9019 e = ''
9020
9021 try:
9022 if '_rpdb2_pwd' in expr or '_rpdb2_args' in expr:
9023 r = '...Removed-password-from-output...'
9024
9025 else:
9026 _expr = as_bytes(ENCODING_SOURCE % encoding + expr, encoding, fstrict = True)
9027
9028 if '_RPDB2_builtins' in expr:
9029 _locals['_RPDB2_builtins'] = vars(g_builtins_module)
9030
9031 try:
9032 redirect_exc_info = True
9033 r = eval(_expr, _globals, _locals)
9034
9035 finally:
9036 del redirect_exc_info
9037
9038 if '_RPDB2_builtins' in expr:
9039 del _locals['_RPDB2_builtins']
9040
9041
9042 if fraw:
9043 encoding = ENCODING_RAW_I
9044
9045 v = repr_ltd(r, MAX_EVALUATE_LENGTH, encoding)
9046
9047 if len(v) > MAX_EVALUATE_LENGTH:
9048 v += '... *** %s ***' % STR_MAX_EVALUATE_LENGTH_WARNING
9049 w = STR_MAX_EVALUATE_LENGTH_WARNING
9050
9051 except:
9052 exc_info = sys.exc_info()
9053 e = "%s, %s" % (safe_str(exc_info[0]), safe_str(exc_info[1]))
9054
9055 self.notify_namespace()
9056
9057 result.append((as_unicode(v), as_unicode(w), as_unicode(e)))
9058
9059
9060 def execute(self, suite, frame_index, fException, encoding):
9061 """
9062 Execute suite (Python statement) in context of frame at
9063 depth 'frame-index'.
9064 """
9065
9066 result = [(as_unicode(STR_SYNCHRONICITY_BAD), as_unicode(''))]
9067
9068 if self.m_fsynchronicity:
9069 self._execute(result, suite, frame_index, fException, encoding)
9070 else:
9071 try:
9072 ctx = self.get_current_ctx()
9073 tid = ctx.m_thread_id
9074 send_job(tid, 1000, self._execute, result, suite, frame_index, fException, encoding)
9075 except:
9076 pass
9077
9078 return result[-1]
9079
9080
9081 def _execute(self, result, suite, frame_index, fException, encoding):
9082 """
9083 Execute suite (Python statement) in context of frame at
9084 depth 'frame-index'.
9085 """
9086
9087 print_debug('exec called with: ' + repr(suite))
9088
9089 encoding = self.__calc_encoding(encoding)
9090
9091 (_globals, _locals, _original_locals_copy) = self.__get_locals_globals(frame_index, fException)
9092
9093 if frame_index > 0 and not _globals is _locals:
9094 _locals_copy = copy.copy(_locals)
9095
9096 w = ''
9097 e = ''
9098
9099 try:
9100 if '_RPDB2_FindRepr' in suite and not '_RPDB2_FindRepr' in _original_locals_copy:
9101 _locals['_RPDB2_FindRepr'] = _RPDB2_FindRepr
9102
9103 try:
9104 _suite = as_bytes(ENCODING_SOURCE % encoding + suite, encoding, fstrict = True)
9105 #print_debug('suite is %s' % repr(_suite))
9106
9107 _code = compile(_suite, '<string>', 'exec')
9108
9109 try:
9110 redirect_exc_info = True
9111 exec(_code, _globals, _locals)
9112
9113 finally:
9114 del redirect_exc_info
9115
9116 finally:
9117 if '_RPDB2_FindRepr' in suite and not '_RPDB2_FindRepr' in _original_locals_copy:
9118 del _locals['_RPDB2_FindRepr']
9119
9120 except:
9121 exc_info = sys.exc_info()
9122 e = "%s, %s" % (safe_str(exc_info[0]), safe_str(exc_info[1]))
9123
9124 if frame_index > 0 and (not _globals is _locals) and _locals != _locals_copy:
9125 l = [(k, safe_repr(v)) for k, v in _locals.items()]
9126 sl = set(l)
9127
9128 lc = [(k, safe_repr(v)) for k, v in _locals_copy.items()]
9129 slc = set(lc)
9130
9131 nsc = [k for (k, v) in sl - slc if k in _original_locals_copy]
9132 if len(nsc) != 0:
9133 w = STR_LOCAL_NAMESPACE_WARNING
9134
9135 self.notify_namespace()
9136
9137 result.append((as_unicode(w), as_unicode(e)))
9138
9139
9140 def __decode_thread_name(self, name):
9141 name = as_unicode(name)
9142 return name
9143
9144
9145 def get_thread_list(self):
9146 """
9147 Return thread list with tid, state, and last event of each thread.
9148 """
9149
9150 ctx = self.get_current_ctx()
9151
9152 if ctx is None:
9153 current_thread_id = -1
9154 else:
9155 current_thread_id = ctx.m_thread_id
9156
9157 ctx_list = list(self.get_threads().values())
9158
9159 tl = []
9160 for c in ctx_list:
9161 d = {}
9162 d[DICT_KEY_TID] = c.m_thread_id
9163 d[DICT_KEY_NAME] = self.__decode_thread_name(c.m_thread_name)
9164 d[DICT_KEY_BROKEN] = c.m_fBroken
9165 d[DICT_KEY_EVENT] = as_unicode(c.m_event)
9166 tl.append(d)
9167
9168 return (current_thread_id, tl)
9169
9170
9171 def stop_debuggee(self):
9172 """
9173 Notify the client and terminate this proccess.
9174 """
9175
9176 g_server.m_work_queue.post_work_item(target = _atexit, args = (True, ), name = '_atexit')
9177
9178
9179 def set_synchronicity(self, fsynchronicity):
9180 self.m_fsynchronicity = fsynchronicity
9181
9182 event = CEventSynchronicity(fsynchronicity)
9183 self.m_event_dispatcher.fire_event(event)
9184
9185 if self.m_state_manager.get_state() == STATE_BROKEN:
9186 self.notify_namespace()
9187
9188
9189 def set_trap_unhandled_exceptions(self, ftrap):
9190 self.m_ftrap = ftrap
9191
9192 event = CEventTrap(ftrap)
9193 self.m_event_dispatcher.fire_event(event)
9194
9195
9196 def is_unhandled_exception(self):
9197 return self.m_fUnhandledException
9198
9199
9200 def set_fork_mode(self, ffork_into_child, ffork_auto):
9201 self.m_ffork_into_child = ffork_into_child
9202 self.m_ffork_auto = ffork_auto
9203
9204 event = CEventForkMode(ffork_into_child, ffork_auto)
9205 self.m_event_dispatcher.fire_event(event)
9206
9207
9208 def set_environ(self, envmap):
9209 global g_fignorefork
9210
9211 print_debug('Entered set_environ() with envmap = %s' % repr(envmap))
9212
9213 if len(envmap) == 0:
9214 return
9215
9216 old_pythonpath = os.environ.get('PYTHONPATH', '')
9217
9218 encoding = detect_locale()
9219
9220 for k, v in envmap:
9221 try:
9222 k = as_string(k, encoding, fstrict = True)
9223 v = as_string(v, encoding, fstrict = True)
9224 except:
9225 continue
9226
9227 command = 'echo %s' % v
9228
9229 try:
9230 g_fignorefork = True
9231 f = platform.popen(command)
9232
9233 finally:
9234 g_fignorefork = False
9235
9236 value = f.read()
9237 f.close()
9238
9239 if value[-1:] == '\n':
9240 value = value[:-1]
9241
9242 os.environ[k] = value
9243
9244 if 'PYTHONPATH' in [k for (k, v) in envmap]:
9245 recalc_sys_path(old_pythonpath)
9246
9247
9248
9249 #
9250 # ------------------------------------- RPC Server --------------------------------------------
9251 #
9252
9253
9254
9255 class CWorkQueue:
9256 """
9257 Worker threads pool mechanism for RPC server.
9258 """
9259
9260 def __init__(self, size = N_WORK_QUEUE_THREADS):
9261 self.m_lock = threading.Condition()
9262 self.m_work_items = []
9263 self.m_f_shutdown = False
9264
9265 self.m_size = size
9266 self.m_n_threads = 0
9267 self.m_n_available = 0
9268
9269 self.__create_thread()
9270
9271
9272 def __create_thread(self):
9273 t = CThread(name = '__worker_target', target = self.__worker_target, shutdown = self.shutdown)
9274 #thread_set_daemon(t, True)
9275 t.start()
9276
9277
9278 def shutdown(self):
9279 """
9280 Signal worker threads to exit, and wait until they do.
9281 """
9282
9283 if self.m_f_shutdown:
9284 return
9285
9286 print_debug('Shutting down worker queue...')
9287
9288 self.m_lock.acquire()
9289 self.m_f_shutdown = True
9290 lock_notify_all(self.m_lock)
9291
9292 t0 = time.time()
9293
9294 while self.m_n_threads > 0:
9295 if time.time() - t0 > SHUTDOWN_TIMEOUT:
9296 self.m_lock.release()
9297 print_debug('Shut down of worker queue has TIMED OUT!')
9298 return
9299
9300 safe_wait(self.m_lock, 0.1)
9301
9302 self.m_lock.release()
9303 print_debug('Shutting down worker queue, done.')
9304
9305
9306 def __worker_target(self):
9307 try:
9308 self.m_lock.acquire()
9309
9310 self.m_n_threads += 1
9311 self.m_n_available += 1
9312 fcreate_thread = not self.m_f_shutdown and self.m_n_threads < self.m_size
9313
9314 self.m_lock.release()
9315
9316 if fcreate_thread:
9317 self.__create_thread()
9318
9319 self.m_lock.acquire()
9320
9321 while not self.m_f_shutdown:
9322 safe_wait(self.m_lock)
9323
9324 if self.m_f_shutdown:
9325 break
9326
9327 if len(self.m_work_items) == 0:
9328 continue
9329
9330 fcreate_thread = self.m_n_available == 1
9331
9332 (target, args, name) = self.m_work_items.pop()
9333
9334 self.m_n_available -= 1
9335 self.m_lock.release()
9336
9337 if fcreate_thread:
9338 print_debug('Creating an extra worker thread.')
9339 self.__create_thread()
9340
9341 thread_set_name(current_thread(), '__worker_target - ' + name)
9342
9343 try:
9344 target(*args)
9345 except:
9346 print_debug_exception()
9347
9348 thread_set_name(current_thread(), '__worker_target')
9349
9350 self.m_lock.acquire()
9351 self.m_n_available += 1
9352
9353 if self.m_n_available > self.m_size:
9354 break
9355
9356 self.m_n_threads -= 1
9357 self.m_n_available -= 1
9358 lock_notify_all(self.m_lock)
9359
9360 finally:
9361 self.m_lock.release()
9362
9363
9364 def post_work_item(self, target, args, name = ''):
9365 if self.m_f_shutdown:
9366 return
9367
9368 try:
9369 self.m_lock.acquire()
9370
9371 if self.m_f_shutdown:
9372 return
9373
9374 self.m_work_items.append((target, args, name))
9375
9376 self.m_lock.notify()
9377
9378 finally:
9379 self.m_lock.release()
9380
9381
9382
9383 #
9384 # MOD
9385 #
9386 class CUnTracedThreadingMixIn(SocketServer.ThreadingMixIn):
9387 """
9388 Modification of SocketServer.ThreadingMixIn that uses a worker thread
9389 queue instead of spawning threads to process requests.
9390 This mod was needed to resolve deadlocks that were generated in some
9391 circumstances.
9392 """
9393
9394 def process_request(self, request, client_address):
9395 g_server.m_work_queue.post_work_item(target = SocketServer.ThreadingMixIn.process_request_thread, args = (self, request, client_address), name = 'process_request')
9396
9397
9398
9399 #
9400 # MOD
9401 #
9402 def my_xmlrpclib_loads(data):
9403 """
9404 Modification of Python 2.3 xmlrpclib.loads() that does not do an
9405 import. Needed to prevent deadlocks.
9406 """
9407
9408 p, u = xmlrpclib.getparser()
9409 p.feed(data)
9410 p.close()
9411 return u.close(), u.getmethodname()
9412
9413
9414
9415 #
9416 # MOD
9417 #
9418 class CXMLRPCServer(CUnTracedThreadingMixIn, SimpleXMLRPCServer.SimpleXMLRPCServer):
9419 if os.name == POSIX:
9420 allow_reuse_address = True
9421 else:
9422 allow_reuse_address = False
9423
9424 """
9425 Modification of Python 2.3 SimpleXMLRPCServer.SimpleXMLRPCDispatcher
9426 that uses my_xmlrpclib_loads(). Needed to prevent deadlocks.
9427 """
9428
9429 def __marshaled_dispatch(self, data, dispatch_method = None):
9430 params, method = my_xmlrpclib_loads(data)
9431
9432 # generate response
9433 try:
9434 if dispatch_method is not None:
9435 response = dispatch_method(method, params)
9436 else:
9437 response = self._dispatch(method, params)
9438 # wrap response in a singleton tuple
9439 response = (response,)
9440 response = xmlrpclib.dumps(response, methodresponse=1)
9441 except xmlrpclib.Fault:
9442 fault = sys.exc_info()[1]
9443 response = xmlrpclib.dumps(fault)
9444 except:
9445 # report exception back to server
9446 response = xmlrpclib.dumps(
9447 xmlrpclib.Fault(1, "%s:%s" % (sys.exc_type, sys.exc_value))
9448 )
9449 print_debug_exception()
9450
9451 return response
9452
9453 if sys.version_info[:2] <= (2, 3):
9454 _marshaled_dispatch = __marshaled_dispatch
9455
9456
9457 #def server_activate(self):
9458 # self.socket.listen(1)
9459
9460
9461 def handle_error(self, request, client_address):
9462 print_debug("handle_error() in pid %d" % _getpid())
9463
9464 if g_ignore_broken_pipe + 5 > time.time():
9465 return
9466
9467 return SimpleXMLRPCServer.SimpleXMLRPCServer.handle_error(self, request, client_address)
9468
9469
9470
9471 class CPwdServerProxy:
9472 """
9473 Encrypted proxy to the debuggee.
9474 Works by wrapping a xmlrpclib.ServerProxy object.
9475 """
9476
9477 def __init__(self, crypto, uri, transport = None, target_rid = 0):
9478 self.m_crypto = crypto
9479 self.m_proxy = xmlrpclib.ServerProxy(uri, transport)
9480
9481 self.m_fEncryption = is_encryption_supported()
9482 self.m_target_rid = target_rid
9483
9484 self.m_method = getattr(self.m_proxy, DISPACHER_METHOD)
9485
9486
9487 def __set_encryption(self, fEncryption):
9488 self.m_fEncryption = fEncryption
9489
9490
9491 def get_encryption(self):
9492 return self.m_fEncryption
9493
9494
9495 def __request(self, name, params):
9496 """
9497 Call debuggee method 'name' with parameters 'params'.
9498 """
9499
9500 while True:
9501 try:
9502 #
9503 # Encrypt method and params.
9504 #
9505 fencrypt = self.get_encryption()
9506 args = (as_unicode(name), params, self.m_target_rid)
9507 (fcompress, digest, msg) = self.m_crypto.do_crypto(args, fencrypt)
9508
9509 rpdb_version = as_unicode(get_interface_compatibility_version())
9510
9511 r = self.m_method(rpdb_version, fencrypt, fcompress, digest, msg)
9512 (fencrypt, fcompress, digest, msg) = r
9513
9514 #
9515 # Decrypt response.
9516 #
9517 ((max_index, _r, _e), id) = self.m_crypto.undo_crypto(fencrypt, fcompress, digest, msg, fVerifyIndex = False)
9518
9519 if _e is not None:
9520 raise _e
9521
9522 except AuthenticationBadIndex:
9523 e = sys.exc_info()[1]
9524 self.m_crypto.set_index(e.m_max_index, e.m_anchor)
9525 continue
9526
9527 except xmlrpclib.Fault:
9528 fault = sys.exc_info()[1]
9529 if class_name(BadVersion) in fault.faultString:
9530 s = fault.faultString.split("'")
9531 version = ['', s[1]][len(s) > 0]
9532 raise BadVersion(version)
9533
9534 if class_name(EncryptionExpected) in fault.faultString:
9535 raise EncryptionExpected
9536
9537 elif class_name(EncryptionNotSupported) in fault.faultString:
9538 if self.m_crypto.m_fAllowUnencrypted:
9539 self.__set_encryption(False)
9540 continue
9541
9542 raise EncryptionNotSupported
9543
9544 elif class_name(DecryptionFailure) in fault.faultString:
9545 raise DecryptionFailure
9546
9547 elif class_name(AuthenticationBadData) in fault.faultString:
9548 raise AuthenticationBadData
9549
9550 elif class_name(AuthenticationFailure) in fault.faultString:
9551 raise AuthenticationFailure
9552
9553 else:
9554 print_debug_exception()
9555 assert False
9556
9557 except xmlrpclib.ProtocolError:
9558 print_debug("Caught ProtocolError for %s" % name)
9559 #print_debug_exception()
9560 raise CConnectionException
9561
9562 return _r
9563
9564
9565 def __getattr__(self, name):
9566 return xmlrpclib._Method(self.__request, name)
9567
9568
9569
9570 class CIOServer:
9571 """
9572 Base class for debuggee server.
9573 """
9574
9575 def __init__(self, _rpdb2_pwd, fAllowUnencrypted, fAllowRemote, rid):
9576 assert(is_unicode(_rpdb2_pwd))
9577 assert(is_unicode(rid))
9578
9579 self.m_thread = None
9580
9581 self.m_crypto = CCrypto(_rpdb2_pwd, fAllowUnencrypted, rid)
9582
9583 self.m_fAllowRemote = fAllowRemote
9584 self.m_rid = rid
9585
9586 self.m_port = None
9587 self.m_stop = False
9588 self.m_server = None
9589
9590 self.m_work_queue = None
9591
9592
9593 def shutdown(self):
9594 self.stop()
9595
9596
9597 def start(self):
9598 self.m_thread = CThread(name = 'ioserver', target = self.run, shutdown = self.shutdown)
9599 thread_set_daemon(self.m_thread, True)
9600 self.m_thread.start()
9601
9602
9603 def jumpstart(self):
9604 self.m_stop = False
9605 self.start()
9606
9607
9608 def stop(self):
9609 if self.m_stop:
9610 return
9611
9612 print_debug('Stopping IO server... (pid = %d)' % _getpid())
9613
9614 self.m_stop = True
9615
9616 while thread_is_alive(self.m_thread):
9617 try:
9618 proxy = CPwdServerProxy(self.m_crypto, calcURL(LOOPBACK, self.m_port), CLocalTimeoutTransport())
9619 proxy.null()
9620 except (socket.error, CException):
9621 pass
9622
9623 self.m_thread.join(0.5)
9624
9625 self.m_thread = None
9626
9627 self.m_work_queue.shutdown()
9628
9629 #try:
9630 # self.m_server.socket.close()
9631 #except:
9632 # pass
9633
9634 print_debug('Stopping IO server, done.')
9635
9636
9637 def export_null(self):
9638 return 0
9639
9640
9641 def run(self):
9642 if self.m_server == None:
9643 (self.m_port, self.m_server) = self.__StartXMLRPCServer()
9644
9645 self.m_work_queue = CWorkQueue()
9646 self.m_server.register_function(self.dispatcher_method)
9647
9648 while not self.m_stop:
9649 self.m_server.handle_request()
9650
9651
9652 def dispatcher_method(self, rpdb_version, fencrypt, fcompress, digest, msg):
9653 """
9654 Process RPC call.
9655 """
9656
9657 #print_debug('dispatcher_method() called with: %s, %s, %s, %s' % (rpdb_version, fencrypt, digest, msg[:100]))
9658
9659 if rpdb_version != as_unicode(get_interface_compatibility_version()):
9660 raise BadVersion(as_unicode(get_version()))
9661
9662 try:
9663 try:
9664 #
9665 # Decrypt parameters.
9666 #
9667 ((name, __params, target_rid), client_id) = self.m_crypto.undo_crypto(fencrypt, fcompress, digest, msg)
9668
9669 except AuthenticationBadIndex:
9670 e = sys.exc_info()[1]
9671 #print_debug_exception()
9672
9673 #
9674 # Notify the caller on the expected index.
9675 #
9676 max_index = self.m_crypto.get_max_index()
9677 args = (max_index, None, e)
9678 (fcompress, digest, msg) = self.m_crypto.do_crypto(args, fencrypt)
9679 return (fencrypt, fcompress, digest, msg)
9680
9681 r = None
9682 e = None
9683
9684 try:
9685 #
9686 # We are forcing the 'export_' prefix on methods that are
9687 # callable through XML-RPC to prevent potential security
9688 # problems
9689 #
9690 func = getattr(self, 'export_' + name)
9691 except AttributeError:
9692 raise Exception('method "%s" is not supported' % ('export_' + name))
9693
9694 try:
9695 if (target_rid != 0) and (target_rid != self.m_rid):
9696 raise NotAttached
9697
9698 #
9699 # Record that client id is still attached.
9700 #
9701 self.record_client_heartbeat(client_id, name, __params)
9702
9703 r = func(*__params)
9704
9705 except Exception:
9706 _e = sys.exc_info()[1]
9707 print_debug_exception()
9708 e = _e
9709
9710 #
9711 # Send the encrypted result.
9712 #
9713 max_index = self.m_crypto.get_max_index()
9714 args = (max_index, r, e)
9715 (fcompress, digest, msg) = self.m_crypto.do_crypto(args, fencrypt)
9716 return (fencrypt, fcompress, digest, msg)
9717
9718 except:
9719 print_debug_exception()
9720 raise
9721
9722
9723 def __StartXMLRPCServer(self):
9724 """
9725 As the name says, start the XML RPC server.
9726 Looks for an available tcp port to listen on.
9727 """
9728
9729 host = [LOOPBACK, ""][self.m_fAllowRemote]
9730 port = SERVER_PORT_RANGE_START
9731
9732 while True:
9733 try:
9734 server = CXMLRPCServer((host, port), logRequests = 0)
9735 return (port, server)
9736
9737 except socket.error:
9738 e = sys.exc_info()[1]
9739 if GetSocketError(e) != errno.EADDRINUSE:
9740 raise
9741
9742 if port >= SERVER_PORT_RANGE_START + SERVER_PORT_RANGE_LENGTH - 1:
9743 raise
9744
9745 port += 1
9746 continue
9747
9748
9749 def record_client_heartbeat(self, id, name, params):
9750 pass
9751
9752
9753
9754 class CServerInfo(object):
9755 def __init__(self, age, port, pid, filename, rid, state, fembedded):
9756 assert(is_unicode(rid))
9757
9758 self.m_age = age
9759 self.m_port = port
9760 self.m_pid = pid
9761 self.m_filename = as_unicode(filename, sys.getfilesystemencoding())
9762 self.m_module_name = as_unicode(CalcModuleName(filename), sys.getfilesystemencoding())
9763 self.m_rid = rid
9764 self.m_state = as_unicode(state)
9765 self.m_fembedded = fembedded
9766
9767
9768 def __reduce__(self):
9769 rv = (copy_reg.__newobj__, (type(self), ), vars(self), None, None)
9770 return rv
9771
9772
9773 def __str__(self):
9774 return 'age: %d, port: %d, pid: %d, filename: %s, rid: %s' % (self.m_age, self.m_port, self.m_pid, self.m_filename, self.m_rid)
9775
9776
9777
9778 class CDebuggeeServer(CIOServer):
9779 """
9780 The debuggee XML RPC server class.
9781 """
9782
9783 def __init__(self, filename, debugger, _rpdb2_pwd, fAllowUnencrypted, fAllowRemote, rid = None):
9784 if rid is None:
9785 rid = generate_rid()
9786
9787 assert(is_unicode(_rpdb2_pwd))
9788 assert(is_unicode(rid))
9789
9790 CIOServer.__init__(self, _rpdb2_pwd, fAllowUnencrypted, fAllowRemote, rid)
9791
9792 self.m_filename = filename
9793 self.m_pid = _getpid()
9794 self.m_time = time.time()
9795 self.m_debugger = debugger
9796 self.m_rid = rid
9797
9798
9799 def shutdown(self):
9800 CIOServer.shutdown(self)
9801
9802
9803 def record_client_heartbeat(self, id, name, params):
9804 finit = (name == 'request_break')
9805 fdetach = (name == 'request_go' and True in params)
9806
9807 self.m_debugger.record_client_heartbeat(id, finit, fdetach)
9808
9809
9810 def export_null(self):
9811 return self.m_debugger.send_event_null()
9812
9813
9814 def export_server_info(self):
9815 age = time.time() - self.m_time
9816 state = self.m_debugger.get_state()
9817 fembedded = self.m_debugger.is_embedded()
9818
9819 si = CServerInfo(age, self.m_port, self.m_pid, self.m_filename, self.m_rid, state, fembedded)
9820 return si
9821
9822
9823 def export_sync_with_events(self, fException, fSendUnhandled):
9824 ei = self.m_debugger.sync_with_events(fException, fSendUnhandled)
9825 return ei
9826
9827
9828 def export_wait_for_event(self, timeout, event_index):
9829 (new_event_index, s) = self.m_debugger.wait_for_event(timeout, event_index)
9830 return (new_event_index, s)
9831
9832
9833 def export_set_breakpoint(self, filename, scope, lineno, fEnabled, expr, frame_index, fException, encoding):
9834 self.m_debugger.set_breakpoint(filename, scope, lineno, fEnabled, expr, frame_index, fException, encoding)
9835 return 0
9836
9837
9838 def export_disable_breakpoint(self, id_list, fAll):
9839 self.m_debugger.disable_breakpoint(id_list, fAll)
9840 return 0
9841
9842
9843 def export_enable_breakpoint(self, id_list, fAll):
9844 self.m_debugger.enable_breakpoint(id_list, fAll)
9845 return 0
9846
9847
9848 def export_delete_breakpoint(self, id_list, fAll):
9849 self.m_debugger.delete_breakpoint(id_list, fAll)
9850 return 0
9851
9852
9853 def export_get_breakpoints(self):
9854 bpl = self.m_debugger.get_breakpoints()
9855 return bpl
9856
9857
9858 def export_request_break(self):
9859 self.m_debugger.request_break()
9860 return 0
9861
9862
9863 def export_request_go(self, fdetach = False):
9864 self.m_debugger.request_go()
9865 return 0
9866
9867
9868 def export_request_go_breakpoint(self, filename, scope, lineno, frame_index, fException):
9869 self.m_debugger.request_go_breakpoint(filename, scope, lineno, frame_index, fException)
9870 return 0
9871
9872
9873 def export_request_step(self):
9874 self.m_debugger.request_step()
9875 return 0
9876
9877
9878 def export_request_next(self):
9879 self.m_debugger.request_next()
9880 return 0
9881
9882
9883 def export_request_return(self):
9884 self.m_debugger.request_return()
9885 return 0
9886
9887
9888 def export_request_jump(self, lineno):
9889 self.m_debugger.request_jump(lineno)
9890 return 0
9891
9892
9893 def export_get_stack(self, tid_list, fAll, fException):
9894 r = self.m_debugger.get_stack(tid_list, fAll, fException)
9895 return r
9896
9897
9898 def export_get_source_file(self, filename, lineno, nlines, frame_index, fException):
9899 r = self.m_debugger.get_source_file(filename, lineno, nlines, frame_index, fException)
9900 return r
9901
9902
9903 def export_get_source_lines(self, nlines, fAll, frame_index, fException):
9904 r = self.m_debugger.get_source_lines(nlines, fAll, frame_index, fException)
9905 return r
9906
9907
9908 def export_get_thread_list(self):
9909 r = self.m_debugger.get_thread_list()
9910 return r
9911
9912
9913 def export_set_thread(self, tid):
9914 self.m_debugger.set_thread(tid)
9915 return 0
9916
9917
9918 def export_get_namespace(self, nl, filter_level, frame_index, fException, repr_limit, encoding, fraw):
9919 r = self.m_debugger.get_namespace(nl, filter_level, frame_index, fException, repr_limit, encoding, fraw)
9920 return r
9921
9922
9923 def export_evaluate(self, expr, frame_index, fException, encoding, fraw):
9924 (v, w, e) = self.m_debugger.evaluate(expr, frame_index, fException, encoding, fraw)
9925 return (v, w, e)
9926
9927
9928 def export_execute(self, suite, frame_index, fException, encoding):
9929 (w, e) = self.m_debugger.execute(suite, frame_index, fException, encoding)
9930 return (w, e)
9931
9932
9933 def export_stop_debuggee(self):
9934 self.m_debugger.stop_debuggee()
9935 return 0
9936
9937
9938 def export_set_synchronicity(self, fsynchronicity):
9939 self.m_debugger.set_synchronicity(fsynchronicity)
9940 return 0
9941
9942
9943 def export_set_trap_unhandled_exceptions(self, ftrap):
9944 self.m_debugger.set_trap_unhandled_exceptions(ftrap)
9945 return 0
9946
9947
9948 def export_is_unhandled_exception(self):
9949 return self.m_debugger.is_unhandled_exception()
9950
9951
9952 def export_set_fork_mode(self, ffork_into_child, ffork_auto):
9953 self.m_debugger.set_fork_mode(ffork_into_child, ffork_auto)
9954 return 0
9955
9956
9957 def export_set_environ(self, envmap):
9958 self.m_debugger.set_environ(envmap)
9959 return 0
9960
9961
9962 def export_embedded_sync(self):
9963 self.m_debugger.embedded_sync()
9964 return 0
9965
9966
9967
9968 #
9969 # ------------------------------------- RPC Client --------------------------------------------
9970 #
9971
9972
9973
9974 #
9975 # MOD
9976 #
9977 class CTimeoutHTTPConnection(httplib.HTTPConnection):
9978 """
9979 Modification of httplib.HTTPConnection with timeout for sockets.
9980 """
9981
9982 _rpdb2_timeout = PING_TIMEOUT
9983
9984 def connect(self):
9985 """Connect to the host and port specified in __init__."""
9986
9987 # New Python version of connect().
9988 if hasattr(self, 'timeout'):
9989 self.timeout = self._rpdb2_timeout
9990 return httplib.HTTPConnection.connect(self)
9991
9992 # Old Python version of connect().
9993 msg = "getaddrinfo returns an empty list"
9994 for res in socket.getaddrinfo(self.host, self.port, 0,
9995 socket.SOCK_STREAM):
9996 af, socktype, proto, canonname, sa = res
9997 try:
9998 self.sock = socket.socket(af, socktype, proto)
9999 self.sock.settimeout(self._rpdb2_timeout)
10000 if self.debuglevel > 0:
10001 print_debug("connect: (%s, %s)" % (self.host, self.port))
10002 self.sock.connect(sa)
10003 except socket.error:
10004 msg = sys.exc_info()[1]
10005 if self.debuglevel > 0:
10006 print_debug('connect fail: ' + repr((self.host, self.port)))
10007 if self.sock:
10008 self.sock.close()
10009 self.sock = None
10010 continue
10011 break
10012 if not self.sock:
10013 raise socket.error(msg)
10014
10015
10016
10017 #
10018 # MOD
10019 #
10020 class CLocalTimeoutHTTPConnection(CTimeoutHTTPConnection):
10021 """
10022 Modification of httplib.HTTPConnection with timeout for sockets.
10023 """
10024
10025 _rpdb2_timeout = LOCAL_TIMEOUT
10026
10027
10028
10029 if is_py3k():
10030 class httplib_HTTP(object):
10031 pass
10032 else:
10033 httplib_HTTP = httplib.HTTP
10034
10035
10036
10037 #
10038 # MOD
10039 #
10040 class CTimeoutHTTP(httplib_HTTP):
10041 """
10042 Modification of httplib.HTTP with timeout for sockets.
10043 """
10044
10045 _connection_class = CTimeoutHTTPConnection
10046
10047
10048
10049 #
10050 # MOD
10051 #
10052 class CLocalTimeoutHTTP(httplib_HTTP):
10053 """
10054 Modification of httplib.HTTP with timeout for sockets.
10055 """
10056
10057 _connection_class = CLocalTimeoutHTTPConnection
10058
10059
10060
10061 #
10062 # MOD
10063 #
10064 class CLocalTransport(xmlrpclib.Transport):
10065 """
10066 Modification of xmlrpclib.Transport to work around Zonealarm sockets
10067 bug.
10068 """
10069
10070 _connection_class = httplib.HTTPConnection
10071 _connection_class_old = httplib_HTTP
10072
10073
10074 def make_connection(self, host):
10075 # New Python version of connect().
10076 # However, make_connection is hacked to always create a new connection
10077 # Otherwise all threads use single connection and crash.
10078 if hasattr(self, '_connection'):
10079 chost, self._extra_headers, x509 = self.get_host_info(host)
10080 return self._connection_class(chost)
10081
10082 # Old Python version of connect().
10083 # create a HTTP connection object from a host descriptor
10084 host, extra_headers, x509 = self.get_host_info(host)
10085 return self._connection_class_old(host)
10086
10087
10088 def __parse_response(self, file, sock):
10089 # read response from input file/socket, and parse it
10090
10091 p, u = self.getparser()
10092
10093 while 1:
10094 if sock:
10095 response = sock.recv(1024)
10096 else:
10097 time.sleep(0.002)
10098 response = file.read(1024)
10099 if not response:
10100 break
10101 if self.verbose:
10102 _print("body: " + repr(response))
10103 p.feed(response)
10104
10105 file.close()
10106 p.close()
10107
10108 return u.close()
10109
10110 if os.name == 'nt':
10111 _parse_response = __parse_response
10112
10113
10114
10115 #
10116 # MOD
10117 #
10118 class CTimeoutTransport(CLocalTransport):
10119 """
10120 Modification of xmlrpclib.Transport with timeout for sockets.
10121 """
10122
10123 _connection_class = CTimeoutHTTPConnection
10124 _connection_class_old = CTimeoutHTTP
10125
10126
10127
10128 #
10129 # MOD
10130 #
10131 class CLocalTimeoutTransport(CLocalTransport):
10132 """
10133 Modification of xmlrpclib.Transport with timeout for sockets.
10134 """
10135
10136 _connection_class = CLocalTimeoutHTTPConnection
10137 _connection_class_old = CLocalTimeoutHTTP
10138
10139
10140
10141 class CSession:
10142 """
10143 Basic class that communicates with the debuggee server.
10144 """
10145
10146 def __init__(self, host, port, _rpdb2_pwd, fAllowUnencrypted, rid):
10147 self.m_crypto = CCrypto(_rpdb2_pwd, fAllowUnencrypted, rid)
10148
10149 self.m_host = host
10150 self.m_port = port
10151 self.m_proxy = None
10152 self.m_server_info = None
10153 self.m_exc_info = None
10154
10155 self.m_fShutDown = False
10156 self.m_fRestart = False
10157
10158
10159 def get_encryption(self):
10160 return self.m_proxy.get_encryption()
10161
10162
10163 def getServerInfo(self):
10164 return self.m_server_info
10165
10166
10167 def pause(self):
10168 self.m_fRestart = True
10169
10170
10171 def restart(self, sleep = 0, timeout = 10):
10172 self.m_fRestart = True
10173
10174 time.sleep(sleep)
10175
10176 t0 = time.time()
10177
10178 try:
10179 try:
10180 while time.time() < t0 + timeout:
10181 try:
10182 self.Connect()
10183 return
10184
10185 except socket.error:
10186 continue
10187
10188 raise CConnectionException
10189
10190 except:
10191 self.m_fShutDown = True
10192 raise
10193
10194 finally:
10195 self.m_fRestart = False
10196
10197
10198 def shut_down(self):
10199 self.m_fShutDown = True
10200
10201
10202 def getProxy(self):
10203 """
10204 Return the proxy object.
10205 With this object you can invoke methods on the server.
10206 """
10207
10208 while self.m_fRestart:
10209 time.sleep(0.1)
10210
10211 if self.m_fShutDown:
10212 raise NotAttached
10213
10214 return self.m_proxy
10215
10216
10217 def ConnectAsync(self):
10218 t = threading.Thread(target = self.ConnectNoThrow)
10219 #thread_set_daemon(t, True)
10220 t.start()
10221 return t
10222
10223
10224 def ConnectNoThrow(self):
10225 try:
10226 self.Connect()
10227 except:
10228 self.m_exc_info = sys.exc_info()
10229
10230
10231 def Connect(self):
10232 host = self.m_host
10233 if host.lower() == LOCALHOST:
10234 host = LOOPBACK
10235
10236 server = CPwdServerProxy(self.m_crypto, calcURL(host, self.m_port), CTimeoutTransport())
10237 server_info = server.server_info()
10238
10239 self.m_proxy = CPwdServerProxy(self.m_crypto, calcURL(host, self.m_port), CLocalTransport(), target_rid = server_info.m_rid)
10240 self.m_server_info = server_info
10241
10242
10243 def isConnected(self):
10244 return self.m_proxy is not None
10245
10246
10247
10248 class CServerList:
10249 def __init__(self, host):
10250 self.m_host = host
10251 self.m_list = []
10252 self.m_errors = {}
10253
10254
10255 def calcList(self, _rpdb2_pwd, rid, key = None):
10256 sil = []
10257 sessions = []
10258 self.m_errors = {}
10259
10260 port = SERVER_PORT_RANGE_START
10261 while port < SERVER_PORT_RANGE_START + SERVER_PORT_RANGE_LENGTH:
10262 s = CSession(self.m_host, port, _rpdb2_pwd, fAllowUnencrypted = True, rid = rid)
10263 t = s.ConnectAsync()
10264 sessions.append((s, t))
10265 port += 1
10266
10267 for (s, t) in sessions:
10268 t.join()
10269
10270 if (s.m_exc_info is not None):
10271 if not issubclass(s.m_exc_info[0], socket.error):
10272 self.m_errors.setdefault(s.m_exc_info[0], []).append(s.m_exc_info)
10273
10274 continue
10275
10276 si = s.getServerInfo()
10277 if si is not None:
10278 sil.append((-si.m_age, si))
10279
10280 sil.sort()
10281 self.m_list = [s[1] for s in sil]
10282
10283 if key != None:
10284 try:
10285 return self.findServers(key)[0]
10286 except:
10287 pass
10288
10289 if key != None:
10290 raise UnknownServer
10291
10292 sil.sort()
10293 self.m_list = [s[1] for s in sil]
10294
10295 return self.m_list
10296
10297
10298 def get_errors(self):
10299 return self.m_errors
10300
10301
10302 def findServers(self, key):
10303 try:
10304 n = int(key)
10305 _s = [s for s in self.m_list if (s.m_pid == n) or (s.m_rid == key)]
10306
10307 except ValueError:
10308 key = as_string(key, sys.getfilesystemencoding())
10309 _s = [s for s in self.m_list if key in s.m_filename]
10310
10311 if _s == []:
10312 raise UnknownServer
10313
10314 return _s
10315
10316
10317
10318 class CSessionManagerInternal:
10319 def __init__(self, _rpdb2_pwd, fAllowUnencrypted, fAllowRemote, host):
10320 self.m_rpdb2_pwd = [_rpdb2_pwd, None][_rpdb2_pwd in [None, '']]
10321 self.m_fAllowUnencrypted = fAllowUnencrypted
10322 self.m_fAllowRemote = fAllowRemote
10323 self.m_rid = generate_rid()
10324
10325 self.m_host = host
10326 self.m_server_list_object = CServerList(host)
10327
10328 self.m_session = None
10329 self.m_server_info = None
10330
10331 self.m_worker_thread = None
10332 self.m_worker_thread_ident = None
10333 self.m_fStop = False
10334
10335 self.m_stack_depth = None
10336 self.m_stack_depth_exception = None
10337 self.m_frame_index = 0
10338 self.m_frame_index_exception = 0
10339
10340 self.m_completions = {}
10341
10342 self.m_remote_event_index = 0
10343 self.m_event_dispatcher_proxy = CEventDispatcher()
10344 self.m_event_dispatcher = CEventDispatcher(self.m_event_dispatcher_proxy)
10345 self.m_state_manager = CStateManager(STATE_DETACHED, self.m_event_dispatcher, self.m_event_dispatcher_proxy)
10346
10347 self.m_breakpoints_proxy = CBreakPointsManagerProxy(self)
10348
10349 event_type_dict = {CEventState: {EVENT_EXCLUDE: [STATE_BROKEN, STATE_ANALYZE]}}
10350 self.register_callback(self.reset_frame_indexes, event_type_dict, fSingleUse = False)
10351
10352 event_type_dict = {CEventStackDepth: {}}
10353 self.register_callback(self.set_stack_depth, event_type_dict, fSingleUse = False)
10354
10355 event_type_dict = {CEventNoThreads: {}}
10356 self.register_callback(self._reset_frame_indexes, event_type_dict, fSingleUse = False)
10357
10358 event_type_dict = {CEventExit: {}}
10359 self.register_callback(self.on_event_exit, event_type_dict, fSingleUse = False)
10360
10361 event_type_dict = {CEventConflictingModules: {}}
10362 self.register_callback(self.on_event_conflicting_modules, event_type_dict, fSingleUse = False)
10363
10364 event_type_dict = {CEventSignalIntercepted: {}}
10365 self.register_callback(self.on_event_signal_intercept, event_type_dict, fSingleUse = False)
10366
10367 event_type_dict = {CEventSignalException: {}}
10368 self.register_callback(self.on_event_signal_exception, event_type_dict, fSingleUse = False)
10369
10370 event_type_dict = {CEventEmbeddedSync: {}}
10371 self.register_callback(self.on_event_embedded_sync, event_type_dict, fSingleUse = False)
10372
10373 event_type_dict = {CEventSynchronicity: {}}
10374 self.m_event_dispatcher_proxy.register_callback(self.on_event_synchronicity, event_type_dict, fSingleUse = False)
10375 self.m_event_dispatcher.register_chain_override(event_type_dict)
10376
10377 event_type_dict = {CEventTrap: {}}
10378 self.m_event_dispatcher_proxy.register_callback(self.on_event_trap, event_type_dict, fSingleUse = False)
10379 self.m_event_dispatcher.register_chain_override(event_type_dict)
10380
10381 event_type_dict = {CEventForkMode: {}}
10382 self.m_event_dispatcher_proxy.register_callback(self.on_event_fork_mode, event_type_dict, fSingleUse = False)
10383 self.m_event_dispatcher.register_chain_override(event_type_dict)
10384
10385 self.m_printer = self.__nul_printer
10386
10387 self.m_last_command_line = None
10388 self.m_last_fchdir = None
10389
10390 self.m_fsynchronicity = True
10391 self.m_ftrap = True
10392
10393 self.m_ffork_into_child = False
10394 self.m_ffork_auto = False
10395
10396 self.m_environment = []
10397
10398 self.m_encoding = ENCODING_AUTO
10399 self.m_fraw = False
10400
10401
10402 def shutdown(self):
10403 self.m_event_dispatcher_proxy.shutdown()
10404 self.m_event_dispatcher.shutdown()
10405 self.m_state_manager.shutdown()
10406
10407
10408 def __nul_printer(self, _str):
10409 pass
10410
10411
10412 def set_printer(self, printer):
10413 self.m_printer = printer
10414
10415
10416 def register_callback(self, callback, event_type_dict, fSingleUse):
10417 return self.m_event_dispatcher.register_callback(callback, event_type_dict, fSingleUse)
10418
10419
10420 def remove_callback(self, callback):
10421 return self.m_event_dispatcher.remove_callback(callback)
10422
10423
10424 def __wait_for_debuggee(self, rid):
10425 try:
10426 time.sleep(STARTUP_TIMEOUT / 2)
10427
10428 for i in range(STARTUP_RETRIES):
10429 try:
10430 print_debug('Scanning for debuggee...')
10431
10432 t0 = time.time()
10433 return self.m_server_list_object.calcList(self.m_rpdb2_pwd, self.m_rid, rid)
10434
10435 except UnknownServer:
10436 dt = time.time() - t0
10437 if dt < STARTUP_TIMEOUT:
10438 time.sleep(STARTUP_TIMEOUT - dt)
10439
10440 continue
10441
10442 return self.m_server_list_object.calcList(self.m_rpdb2_pwd, self.m_rid, rid)
10443
10444 finally:
10445 errors = self.m_server_list_object.get_errors()
10446 self.__report_server_errors(errors, fsupress_pwd_warning = True)
10447
10448
10449 def get_encryption(self):
10450 return self.getSession().get_encryption()
10451
10452
10453 def launch(self, fchdir, command_line, fload_breakpoints = True):
10454 assert(is_unicode(command_line))
10455
10456 self.__verify_unattached()
10457
10458 if not os.name in [POSIX, 'nt']:
10459 self.m_printer(STR_SPAWN_UNSUPPORTED)
10460 raise SpawnUnsupported
10461
10462 if g_fFirewallTest:
10463 firewall_test = CFirewallTest(self.get_remote())
10464 if not firewall_test.run():
10465 raise FirewallBlock
10466 else:
10467 print_debug('Skipping firewall test.')
10468
10469 if self.m_rpdb2_pwd is None:
10470 self.set_random_password()
10471
10472 if command_line == '':
10473 raise BadArgument
10474
10475 (path, filename, args) = split_command_line_path_filename_args(command_line)
10476
10477 #if not IsPythonSourceFile(filename):
10478 # raise NotPythonSource
10479
10480 _filename = my_os_path_join(path, filename)
10481
10482 ExpandedFilename = FindFile(_filename)
10483 self.set_host(LOCALHOST)
10484
10485 self.m_printer(STR_STARTUP_SPAWN_NOTICE)
10486
10487 rid = generate_rid()
10488
10489 create_pwd_file(rid, self.m_rpdb2_pwd)
10490
10491 self.m_state_manager.set_state(STATE_SPAWNING)
10492
10493 try:
10494 try:
10495 self._spawn_server(fchdir, ExpandedFilename, args, rid)
10496 server = self.__wait_for_debuggee(rid)
10497 self.attach(server.m_rid, server.m_filename, fsupress_pwd_warning = True, fsetenv = True, ffirewall_test = False, server = server, fload_breakpoints = fload_breakpoints)
10498
10499 self.m_last_command_line = command_line
10500 self.m_last_fchdir = fchdir
10501
10502 except:
10503 if self.m_state_manager.get_state() != STATE_DETACHED:
10504 self.m_state_manager.set_state(STATE_DETACHED)
10505
10506 raise
10507
10508 finally:
10509 delete_pwd_file(rid)
10510
10511
10512 def restart(self):
10513 """
10514 Restart debug session with same command_line and fchdir arguments
10515 which were used in last launch.
10516 """
10517
10518 if None in (self.m_last_fchdir, self.m_last_command_line):
10519 return
10520
10521 if self.m_state_manager.get_state() != STATE_DETACHED:
10522 self.stop_debuggee()
10523
10524 self.launch(self.m_last_fchdir, self.m_last_command_line)
10525
10526
10527 def get_launch_args(self):
10528 """
10529 Return command_line and fchdir arguments which were used in last
10530 launch as (last_fchdir, last_command_line).
10531 Returns None if there is no info.
10532 """
10533
10534 if None in (self.m_last_fchdir, self.m_last_command_line):
10535 return (None, None)
10536
10537 return (self.m_last_fchdir, self.m_last_command_line)
10538
10539
10540 def _spawn_server(self, fchdir, ExpandedFilename, args, rid):
10541 """
10542 Start an OS console to act as server.
10543 What it does is to start rpdb again in a new console in server only mode.
10544 """
10545
10546 if g_fScreen:
10547 name = SCREEN
10548 elif sys.platform == DARWIN:
10549 name = DARWIN
10550 else:
10551 try:
10552 import terminalcommand
10553 name = MAC
10554 except:
10555 name = os.name
10556
10557 if name == 'nt' and g_fDebug:
10558 name = NT_DEBUG
10559
10560 e = ['', ' --encrypt'][not self.m_fAllowUnencrypted]
10561 r = ['', ' --remote'][self.m_fAllowRemote]
10562 c = ['', ' --chdir'][fchdir]
10563 p = ['', ' --pwd="%s"' % self.m_rpdb2_pwd][os.name == 'nt']
10564
10565 b = ''
10566
10567 encoding = detect_locale()
10568 fse = sys.getfilesystemencoding()
10569
10570 ExpandedFilename = g_found_unicode_files.get(ExpandedFilename, ExpandedFilename)
10571 ExpandedFilename = as_unicode(ExpandedFilename, fse)
10572
10573 if as_bytes('?') in as_bytes(ExpandedFilename, encoding, fstrict = False):
10574 _u = as_bytes(ExpandedFilename)
10575 _b = base64.encodestring(_u)
10576 _b = _b.strip(as_bytes('\n')).translate(g_safe_base64_to)
10577 _b = as_string(_b, fstrict = True)
10578 b = ' --base64=%s' % _b
10579
10580 debugger = os.path.abspath(__file__)
10581 if debugger[-1:] == 'c':
10582 debugger = debugger[:-1]
10583
10584 debugger = as_unicode(debugger, fse)
10585
10586 debug_prints = ['', ' --debug'][g_fDebug]
10587
10588 options = '"%s"%s --debugee%s%s%s%s%s --rid=%s "%s" %s' % (debugger, debug_prints, p, e, r, c, b, rid, ExpandedFilename, args)
10589
10590 python_exec = sys.executable
10591 if python_exec.endswith('w.exe'):
10592 python_exec = python_exec[:-5] + '.exe'
10593
10594 python_exec = as_unicode(python_exec, fse)
10595
10596 if as_bytes('?') in as_bytes(python_exec + debugger, encoding, fstrict = False):
10597 raise BadMBCSPath
10598
10599 if name == POSIX:
10600 shell = CalcUserShell()
10601 terminal_command = CalcTerminalCommand()
10602
10603 if terminal_command in osSpawn:
10604 command = osSpawn[terminal_command] % {'shell': shell, 'exec': python_exec, 'options': options}
10605 else:
10606 command = osSpawn[name] % {'term': terminal_command, 'shell': shell, 'exec': python_exec, 'options': options}
10607 else:
10608 command = osSpawn[name] % {'exec': python_exec, 'options': options}
10609
10610 if name == DARWIN:
10611 s = 'cd "%s" ; %s' % (getcwdu(), command)
10612 command = CalcMacTerminalCommand(s)
10613
10614 print_debug('Terminal open string: %s' % repr(command))
10615
10616 command = as_string(command, encoding)
10617
10618 if name == MAC:
10619 terminalcommand.run(command)
10620 else:
10621 subprocess.Popen(command, shell=True)
10622
10623
10624 def attach(self, key, name = None, fsupress_pwd_warning = False, fsetenv = False, ffirewall_test = True, server = None, fload_breakpoints = True):
10625 assert(is_unicode(key))
10626
10627 self.__verify_unattached()
10628
10629 if key == '':
10630 raise BadArgument
10631
10632 if self.m_rpdb2_pwd is None:
10633 #self.m_printer(STR_PASSWORD_MUST_BE_SET)
10634 raise UnsetPassword
10635
10636 if g_fFirewallTest and ffirewall_test:
10637 firewall_test = CFirewallTest(self.get_remote())
10638 if not firewall_test.run():
10639 raise FirewallBlock
10640 elif not g_fFirewallTest and ffirewall_test:
10641 print_debug('Skipping firewall test.')
10642
10643 if name is None:
10644 name = key
10645
10646 _name = name
10647
10648 self.m_printer(STR_STARTUP_NOTICE)
10649 self.m_state_manager.set_state(STATE_ATTACHING)
10650
10651 try:
10652 servers = [server]
10653 if server == None:
10654 self.m_server_list_object.calcList(self.m_rpdb2_pwd, self.m_rid)
10655 servers = self.m_server_list_object.findServers(key)
10656 server = servers[0]
10657
10658 _name = server.m_filename
10659
10660 errors = self.m_server_list_object.get_errors()
10661 if not key in [server.m_rid, str(server.m_pid)]:
10662 self.__report_server_errors(errors, fsupress_pwd_warning)
10663
10664 self.__attach(server, fsetenv)
10665 if len(servers) > 1:
10666 self.m_printer(STR_MULTIPLE_DEBUGGEES % key)
10667 self.m_printer(STR_ATTACH_CRYPTO_MODE % ([' ' + STR_ATTACH_CRYPTO_MODE_NOT, ''][self.get_encryption()]))
10668 self.m_printer(STR_ATTACH_SUCCEEDED % server.m_filename)
10669
10670 try:
10671 if fload_breakpoints:
10672 self.load_breakpoints()
10673 except:
10674 pass
10675
10676 except (socket.error, CConnectionException):
10677 self.m_printer(STR_ATTACH_FAILED_NAME % _name)
10678 self.m_state_manager.set_state(STATE_DETACHED)
10679 raise
10680
10681 except:
10682 print_debug_exception()
10683 assert False
10684
10685
10686 def report_exception(self, _type, value, tb):
10687 msg = g_error_mapping.get(_type, STR_ERROR_OTHER)
10688
10689 if _type == SpawnUnsupported and os.name == POSIX and not g_fScreen and g_fDefaultStd:
10690 msg += ' ' + STR_SPAWN_UNSUPPORTED_SCREEN_SUFFIX
10691
10692 if _type == UnknownServer and os.name == POSIX and not g_fScreen and g_fDefaultStd:
10693 msg += ' ' + STR_DISPLAY_ERROR
10694
10695 _str = msg % {'type': _type, 'value': value, 'traceback': tb}
10696 self.m_printer(_str)
10697
10698 if not _type in g_error_mapping:
10699 print_exception(_type, value, tb, True)
10700
10701
10702 def __report_server_errors(self, errors, fsupress_pwd_warning = False):
10703 for k, el in errors.items():
10704 if fsupress_pwd_warning and k in [BadVersion, AuthenticationBadData, AuthenticationFailure]:
10705 continue
10706
10707 if k in [BadVersion]:
10708 for (t, v, tb) in el:
10709 self.report_exception(t, v, None)
10710 continue
10711
10712 (t, v, tb) = el[0]
10713 self.report_exception(t, v, tb)
10714
10715
10716 def __attach(self, server, fsetenv):
10717 self.__verify_unattached()
10718
10719 session = CSession(self.m_host, server.m_port, self.m_rpdb2_pwd, self.m_fAllowUnencrypted, self.m_rid)
10720 session.Connect()
10721
10722 if (session.getServerInfo().m_pid != server.m_pid) or (session.getServerInfo().m_filename != server.m_filename):
10723 raise UnexpectedData
10724
10725 self.m_session = session
10726
10727 self.m_server_info = self.get_server_info()
10728
10729 self.getSession().getProxy().set_synchronicity(self.m_fsynchronicity)
10730 self.getSession().getProxy().set_trap_unhandled_exceptions(self.m_ftrap)
10731 self.getSession().getProxy().set_fork_mode(self.m_ffork_into_child, self.m_ffork_auto)
10732
10733 if fsetenv and len(self.m_environment) != 0:
10734 self.getSession().getProxy().set_environ(self.m_environment)
10735
10736 self.request_break()
10737 self.refresh(True)
10738
10739 self.__start_event_monitor()
10740
10741 print_debug('Attached to debuggee on port %d.' % session.m_port)
10742
10743 #self.enable_breakpoint([], fAll = True)
10744
10745
10746 def __verify_unattached(self):
10747 if self.__is_attached():
10748 raise AlreadyAttached
10749
10750
10751 def __verify_attached(self):
10752 if not self.__is_attached():
10753 raise NotAttached
10754
10755
10756 def __is_attached(self):
10757 return (self.m_state_manager.get_state() != STATE_DETACHED) and (self.m_session is not None)
10758
10759
10760 def __verify_broken(self):
10761 if self.m_state_manager.get_state() not in [STATE_BROKEN, STATE_ANALYZE]:
10762 raise DebuggerNotBroken
10763
10764
10765 def refresh(self, fSendUnhandled = False):
10766 fAnalyzeMode = (self.m_state_manager.get_state() == STATE_ANALYZE)
10767
10768 self.m_remote_event_index = self.getSession().getProxy().sync_with_events(fAnalyzeMode, fSendUnhandled)
10769 self.m_breakpoints_proxy.sync()
10770
10771
10772 def __start_event_monitor(self):
10773 self.m_fStop = False
10774 self.m_worker_thread = threading.Thread(target = self.__event_monitor_proc)
10775 #thread_set_daemon(self.m_worker_thread, True)
10776 self.m_worker_thread.start()
10777
10778
10779 def __event_monitor_proc(self):
10780 self.m_worker_thread_ident = thread.get_ident()
10781 t = 0
10782 nfailures = 0
10783
10784 while not self.m_fStop:
10785 try:
10786 t = ControlRate(t, IDLE_MAX_RATE)
10787 if self.m_fStop:
10788 return
10789
10790 (n, sel) = self.getSession().getProxy().wait_for_event(PING_TIMEOUT, self.m_remote_event_index)
10791
10792 if True in [isinstance(e, CEventForkSwitch) for e in sel]:
10793 print_debug('Received fork switch event.')
10794
10795 self.getSession().pause()
10796 threading.Thread(target = self.restart_session_job).start()
10797
10798 if True in [isinstance(e, CEventExecSwitch) for e in sel]:
10799 print_debug('Received exec switch event.')
10800
10801 self.getSession().pause()
10802 threading.Thread(target = self.restart_session_job, args = (True, )).start()
10803
10804 if True in [isinstance(e, CEventExit) for e in sel]:
10805 self.getSession().shut_down()
10806 self.m_fStop = True
10807
10808 if n > self.m_remote_event_index:
10809 #print >> sys.__stderr__, (n, sel)
10810 self.m_remote_event_index = n
10811 self.m_event_dispatcher_proxy.fire_events(sel)
10812
10813 nfailures = 0
10814
10815 except CConnectionException:
10816 if not self.m_fStop:
10817 self.report_exception(*sys.exc_info())
10818 threading.Thread(target = self.detach_job).start()
10819
10820 return
10821
10822 except socket.error:
10823 if nfailures < COMMUNICATION_RETRIES:
10824 nfailures += 1
10825 continue
10826
10827 if not self.m_fStop:
10828 self.report_exception(*sys.exc_info())
10829 threading.Thread(target = self.detach_job).start()
10830
10831 return
10832
10833
10834 def on_event_conflicting_modules(self, event):
10835 s = ', '.join(event.m_modules_list)
10836 self.m_printer(STR_CONFLICTING_MODULES % s)
10837
10838
10839 def on_event_signal_intercept(self, event):
10840 if self.m_state_manager.get_state() in [STATE_ANALYZE, STATE_BROKEN]:
10841 self.m_printer(STR_SIGNAL_INTERCEPT % (event.m_signame, event.m_signum))
10842
10843
10844 def on_event_signal_exception(self, event):
10845 self.m_printer(STR_SIGNAL_EXCEPTION % (event.m_description, event.m_signame, event.m_signum))
10846
10847
10848 def on_event_embedded_sync(self, event):
10849 #
10850 # time.sleep() allows pending break requests to go through...
10851 #
10852 time.sleep(0.001)
10853 self.getSession().getProxy().embedded_sync()
10854
10855
10856 def on_event_exit(self, event):
10857 self.m_printer(STR_DEBUGGEE_TERMINATED)
10858 threading.Thread(target = self.detach_job).start()
10859
10860
10861 def restart_session_job(self, fSendExitOnFailure = False):
10862 try:
10863 self.getSession().restart(sleep = 3)
10864 return
10865
10866 except:
10867 pass
10868
10869 self.m_fStop = True
10870
10871 if fSendExitOnFailure:
10872 e = CEventExit()
10873 self.m_event_dispatcher_proxy.fire_event(e)
10874 return
10875
10876 self.m_printer(STR_LOST_CONNECTION)
10877 self.detach_job()
10878
10879
10880 def detach_job(self):
10881 try:
10882 self.detach()
10883 except:
10884 pass
10885
10886
10887 def detach(self):
10888 self.__verify_attached()
10889
10890 try:
10891 self.save_breakpoints()
10892 except:
10893 print_debug_exception()
10894 pass
10895
10896 self.m_printer(STR_ATTEMPTING_TO_DETACH)
10897
10898 self.m_state_manager.set_state(STATE_DETACHING)
10899
10900 self.__stop_event_monitor()
10901
10902 try:
10903 #self.disable_breakpoint([], fAll = True)
10904
10905 try:
10906 self.getSession().getProxy().set_trap_unhandled_exceptions(False)
10907 self.request_go(fdetach = True)
10908
10909 except DebuggerNotBroken:
10910 pass
10911
10912 finally:
10913 self.m_state_manager.set_state(STATE_DETACHED)
10914 self.m_session = None
10915 self.m_printer(STR_DETACH_SUCCEEDED)
10916
10917
10918 def __stop_event_monitor(self):
10919 self.m_fStop = True
10920 if self.m_worker_thread is not None:
10921 if thread.get_ident() != self.m_worker_thread_ident:
10922 try:
10923 self.getSession().getProxy().null()
10924 except:
10925 pass
10926
10927 self.m_worker_thread.join()
10928
10929 self.m_worker_thread = None
10930 self.m_worker_thread_ident = None
10931
10932
10933 def request_break(self):
10934 self.getSession().getProxy().request_break()
10935
10936
10937 def request_go(self, fdetach = False):
10938 self.getSession().getProxy().request_go(fdetach)
10939
10940
10941 def request_go_breakpoint(self, filename, scope, lineno):
10942 frame_index = self.get_frame_index()
10943 fAnalyzeMode = (self.m_state_manager.get_state() == STATE_ANALYZE)
10944
10945 self.getSession().getProxy().request_go_breakpoint(filename, scope, lineno, frame_index, fAnalyzeMode)
10946
10947
10948 def request_step(self):
10949 self.getSession().getProxy().request_step()
10950
10951
10952 def request_next(self):
10953 self.getSession().getProxy().request_next()
10954
10955
10956 def request_return(self):
10957 self.getSession().getProxy().request_return()
10958
10959
10960 def request_jump(self, lineno):
10961 self.getSession().getProxy().request_jump(lineno)
10962
10963
10964 def set_breakpoint(self, filename, scope, lineno, fEnabled, expr, encoding = None):
10965 frame_index = self.get_frame_index()
10966 fAnalyzeMode = (self.m_state_manager.get_state() == STATE_ANALYZE)
10967
10968 if encoding == None:
10969 encoding = self.m_encoding
10970
10971 self.getSession().getProxy().set_breakpoint(filename, scope, lineno, fEnabled, expr, frame_index, fAnalyzeMode, encoding)
10972
10973
10974 def disable_breakpoint(self, id_list, fAll):
10975 self.getSession().getProxy().disable_breakpoint(id_list, fAll)
10976
10977
10978 def enable_breakpoint(self, id_list, fAll):
10979 self.getSession().getProxy().enable_breakpoint(id_list, fAll)
10980
10981
10982 def delete_breakpoint(self, id_list, fAll):
10983 self.getSession().getProxy().delete_breakpoint(id_list, fAll)
10984
10985
10986 def get_breakpoints(self):
10987 self.__verify_attached()
10988
10989 bpl = self.m_breakpoints_proxy.get_breakpoints()
10990 return bpl
10991
10992
10993 def save_breakpoints(self, filename = ''):
10994 self.__verify_attached()
10995
10996 module_name = self.getSession().getServerInfo().m_module_name
10997 if module_name[:1] == '<':
10998 return
10999
11000 if sys.platform == 'OpenVMS':
11001 #
11002 # OpenVMS filesystem does not support byte stream.
11003 #
11004 mode = 'w'
11005 else:
11006 mode = 'wb'
11007
11008 path = calc_bpl_filename(module_name + filename)
11009 file = open(path, mode)
11010
11011 try:
11012 try:
11013 bpl = self.get_breakpoints()
11014 sbpl = pickle.dumps(bpl)
11015 file.write(sbpl)
11016
11017 except:
11018 print_debug_exception()
11019 raise CException
11020
11021 finally:
11022 file.close()
11023
11024
11025 def load_breakpoints(self, filename = ''):
11026 self.__verify_attached()
11027
11028 module_name = self.getSession().getServerInfo().m_module_name
11029 if module_name[:1] == '<':
11030 return
11031
11032 if sys.platform == 'OpenVMS':
11033 #
11034 # OpenVMS filesystem does not support byte stream.
11035 #
11036 mode = 'r'
11037 else:
11038 mode = 'rb'
11039
11040 path = calc_bpl_filename(module_name + filename)
11041 file = open(path, mode)
11042
11043 ferror = False
11044
11045 try:
11046 try:
11047 bpl = pickle.load(file)
11048 self.delete_breakpoint([], True)
11049
11050 except:
11051 print_debug_exception()
11052 raise CException
11053
11054 #
11055 # No Breakpoints were found in file.
11056 #
11057 if filename == '' and len(bpl.values()) == 0:
11058 raise IOError
11059
11060 for bp in bpl.values():
11061 try:
11062 if bp.m_scope_fqn != None:
11063 bp.m_scope_fqn = as_unicode(bp.m_scope_fqn)
11064
11065 if bp.m_filename != None:
11066 bp.m_filename = as_unicode(bp.m_filename)
11067
11068 if bp.m_expr != None:
11069 bp.m_expr = as_unicode(bp.m_expr)
11070
11071 if bp.m_expr in [None, '']:
11072 bp.m_encoding = as_unicode('utf-8')
11073
11074 self.set_breakpoint(bp.m_filename, bp.m_scope_fqn, bp.m_scope_offset, bp.m_fEnabled, bp.m_expr, bp.m_encoding)
11075 except:
11076 print_debug_exception()
11077 ferror = True
11078
11079 if ferror:
11080 raise CException
11081
11082 finally:
11083 file.close()
11084
11085
11086 def on_event_synchronicity(self, event):
11087 ffire = self.m_fsynchronicity != event.m_fsynchronicity
11088 self.m_fsynchronicity = event.m_fsynchronicity
11089
11090 if ffire:
11091 event = CEventSynchronicity(event.m_fsynchronicity)
11092 self.m_event_dispatcher.fire_event(event)
11093
11094
11095 def set_synchronicity(self, fsynchronicity):
11096 self.m_fsynchronicity = fsynchronicity
11097
11098 if self.__is_attached():
11099 try:
11100 self.getSession().getProxy().set_synchronicity(fsynchronicity)
11101 except NotAttached:
11102 pass
11103
11104 event = CEventSynchronicity(fsynchronicity)
11105 self.m_event_dispatcher.fire_event(event)
11106
11107
11108 def get_synchronicity(self):
11109 return self.m_fsynchronicity
11110
11111
11112 def on_event_trap(self, event):
11113 ffire = self.m_ftrap != event.m_ftrap
11114 self.m_ftrap = event.m_ftrap
11115
11116 if ffire:
11117 event = CEventTrap(event.m_ftrap)
11118 self.m_event_dispatcher.fire_event(event)
11119
11120
11121 def set_trap_unhandled_exceptions(self, ftrap):
11122 self.m_ftrap = ftrap
11123
11124 if self.__is_attached():
11125 try:
11126 self.getSession().getProxy().set_trap_unhandled_exceptions(self.m_ftrap)
11127 except NotAttached:
11128 pass
11129
11130 event = CEventTrap(ftrap)
11131 self.m_event_dispatcher.fire_event(event)
11132
11133
11134 def get_trap_unhandled_exceptions(self):
11135 return self.m_ftrap
11136
11137
11138 def is_unhandled_exception(self):
11139 self.__verify_attached()
11140
11141 return self.getSession().getProxy().is_unhandled_exception()
11142
11143
11144 def on_event_fork_mode(self, event):
11145 ffire = ((self.m_ffork_into_child , self.m_ffork_auto) !=
11146 (event.m_ffork_into_child, event.m_ffork_auto))
11147
11148 self.m_ffork_into_child = event.m_ffork_into_child
11149 self.m_ffork_auto = event.m_ffork_auto
11150
11151 if ffire:
11152 event = CEventForkMode(self.m_ffork_into_child, self.m_ffork_auto)
11153 self.m_event_dispatcher.fire_event(event)
11154
11155
11156 def set_fork_mode(self, ffork_into_child, ffork_auto):
11157 self.m_ffork_into_child = ffork_into_child
11158 self.m_ffork_auto = ffork_auto
11159
11160 if self.__is_attached():
11161 try:
11162 self.getSession().getProxy().set_fork_mode(
11163 self.m_ffork_into_child,
11164 self.m_ffork_auto
11165 )
11166
11167 except NotAttached:
11168 pass
11169
11170 event = CEventForkMode(ffork_into_child, ffork_auto)
11171 self.m_event_dispatcher.fire_event(event)
11172
11173
11174 def get_fork_mode(self):
11175 return (self.m_ffork_into_child, self.m_ffork_auto)
11176
11177
11178 def get_stack(self, tid_list, fAll):
11179 fAnalyzeMode = (self.m_state_manager.get_state() == STATE_ANALYZE)
11180 r = self.getSession().getProxy().get_stack(tid_list, fAll, fAnalyzeMode)
11181 return r
11182
11183
11184 def get_source_file(self, filename, lineno, nlines):
11185 assert(is_unicode(filename))
11186
11187 frame_index = self.get_frame_index()
11188 fAnalyzeMode = (self.m_state_manager.get_state() == STATE_ANALYZE)
11189
11190 r = self.getSession().getProxy().get_source_file(filename, lineno, nlines, frame_index, fAnalyzeMode)
11191 return r
11192
11193
11194 def get_source_lines(self, nlines, fAll):
11195 frame_index = self.get_frame_index()
11196 fAnalyzeMode = (self.m_state_manager.get_state() == STATE_ANALYZE)
11197
11198 r = self.getSession().getProxy().get_source_lines(nlines, fAll, frame_index, fAnalyzeMode)
11199 return r
11200
11201
11202 def get_thread_list(self):
11203 (current_thread_id, thread_list) = self.getSession().getProxy().get_thread_list()
11204 return (current_thread_id, thread_list)
11205
11206
11207 def set_thread(self, tid):
11208 self.reset_frame_indexes(None)
11209 self.getSession().getProxy().set_thread(tid)
11210
11211
11212 def get_namespace(self, nl, filter_level, repr_limit):
11213 frame_index = self.get_frame_index()
11214 fAnalyzeMode = (self.m_state_manager.get_state() == STATE_ANALYZE)
11215
11216 r = self.getSession().getProxy().get_namespace(nl, filter_level, frame_index, fAnalyzeMode, repr_limit, self.m_encoding, self.m_fraw)
11217 return r
11218
11219
11220 def evaluate(self, expr, fclear_completions = True):
11221 assert(is_unicode(expr))
11222
11223 self.__verify_attached()
11224 self.__verify_broken()
11225
11226 frame_index = self.get_frame_index()
11227 fAnalyzeMode = (self.m_state_manager.get_state() == STATE_ANALYZE)
11228
11229 (value, warning, error) = self.getSession().getProxy().evaluate(expr, frame_index, fAnalyzeMode, self.m_encoding, self.m_fraw)
11230
11231 if fclear_completions:
11232 self.m_completions.clear()
11233
11234 return (value, warning, error)
11235
11236
11237 def execute(self, suite):
11238 assert(is_unicode(suite))
11239
11240 self.__verify_attached()
11241 self.__verify_broken()
11242
11243 frame_index = self.get_frame_index()
11244 fAnalyzeMode = (self.m_state_manager.get_state() == STATE_ANALYZE)
11245
11246 (warning, error) = self.getSession().getProxy().execute(suite, frame_index, fAnalyzeMode, self.m_encoding)
11247
11248 self.m_completions.clear()
11249
11250 return (warning, error)
11251
11252
11253 def set_encoding(self, encoding, fraw):
11254 if (self.m_encoding, self.m_fraw) == (encoding, fraw):
11255 return
11256
11257 self.m_encoding = encoding
11258 self.m_fraw = fraw
11259
11260 event = CEventEncoding(encoding, fraw)
11261 self.m_event_dispatcher.fire_event(event)
11262
11263 if self.__is_attached():
11264 self.refresh()
11265
11266
11267 def get_encoding(self):
11268 return (self.m_encoding, self.m_fraw)
11269
11270
11271 def set_host(self, host):
11272 self.__verify_unattached()
11273
11274 try:
11275 if not is_unicode(host):
11276 host = host.decode('ascii')
11277
11278 host.encode('ascii')
11279
11280 except:
11281 raise BadArgument
11282
11283 host = as_string(host, 'ascii')
11284
11285 try:
11286 socket.getaddrinfo(host, 0, 0, socket.SOCK_STREAM)
11287
11288 except socket.gaierror:
11289 if host.lower() != LOCALHOST:
11290 raise
11291
11292 #
11293 # Work-around for gaierror: (-8, 'Servname not supported for ai_socktype')
11294 #
11295 return self.set_host(LOOPBACK)
11296
11297 self.m_host = host
11298 self.m_server_list_object = CServerList(host)
11299
11300
11301 def get_host(self):
11302 return as_unicode(self.m_host)
11303
11304
11305 def calc_server_list(self):
11306 if self.m_rpdb2_pwd is None:
11307 raise UnsetPassword
11308
11309 if g_fFirewallTest:
11310 firewall_test = CFirewallTest(self.get_remote())
11311 if not firewall_test.run():
11312 raise FirewallBlock
11313 else:
11314 print_debug('Skipping firewall test.')
11315
11316 server_list = self.m_server_list_object.calcList(self.m_rpdb2_pwd, self.m_rid)
11317 errors = self.m_server_list_object.get_errors()
11318 self.__report_server_errors(errors)
11319
11320 return (server_list, errors)
11321
11322
11323 def get_server_info(self):
11324 return self.getSession().getServerInfo()
11325
11326
11327 def complete_expression(self, expr):
11328 match = re.search(
11329 r'(?P<unsupported> \.)? (?P<match> ((?P<scope> (\w+\.)* \w+) \.)? (?P<complete>\w*) $)',
11330 expr,
11331 re.U | re.X
11332 )
11333
11334 if match == None:
11335 raise BadArgument
11336
11337 d = match.groupdict()
11338
11339 unsupported, scope, complete = (d['unsupported'], d['scope'], d['complete'])
11340
11341 if unsupported != None:
11342 raise BadArgument
11343
11344 if scope == None:
11345 _scope = as_unicode('list(globals().keys()) + list(locals().keys()) + list(_RPDB2_builtins.keys())')
11346 else:
11347 _scope = as_unicode('dir(%s)' % scope)
11348
11349 if not _scope in self.m_completions:
11350 (v, w, e) = self.evaluate(_scope, fclear_completions = False)
11351 if w != '' or e != '':
11352 print_debug('evaluate() returned the following warning/error: %s' % w + e)
11353 return (expr, [])
11354
11355 cl = list(set(eval(v)))
11356 if '_RPDB2_builtins' in cl:
11357 cl.remove('_RPDB2_builtins')
11358 self.m_completions[_scope] = cl
11359
11360 completions = [attr for attr in self.m_completions[_scope] if attr.startswith(complete)]
11361 completions.sort()
11362
11363 if complete == '':
11364 prefix = expr
11365 else:
11366 prefix = expr[:-len(complete)]
11367
11368 return (prefix, completions)
11369
11370
11371
11372 def _reset_frame_indexes(self, event):
11373 self.reset_frame_indexes(None)
11374
11375
11376 def reset_frame_indexes(self, event):
11377 try:
11378 self.m_state_manager.acquire()
11379 if event is None:
11380 self.__verify_broken()
11381 elif self.m_state_manager.get_state() in [STATE_BROKEN, STATE_ANALYZE]:
11382 return
11383
11384 self.m_stack_depth = None
11385 self.m_stack_depth_exception = None
11386 self.m_frame_index = 0
11387 self.m_frame_index_exception = 0
11388
11389 self.m_completions.clear()
11390
11391 finally:
11392 self.m_state_manager.release()
11393
11394
11395 def set_stack_depth(self, event):
11396 try:
11397 self.m_state_manager.acquire()
11398 self.__verify_broken()
11399
11400 self.m_stack_depth = event.m_stack_depth
11401 self.m_stack_depth_exception = event.m_stack_depth_exception
11402 self.m_frame_index = min(self.m_frame_index, self.m_stack_depth - 1)
11403 self.m_frame_index_exception = min(self.m_frame_index_exception, self.m_stack_depth_exception - 1)
11404
11405 finally:
11406 self.m_state_manager.release()
11407
11408
11409 def set_frame_index(self, frame_index):
11410 try:
11411 self.m_state_manager.acquire()
11412 self.__verify_broken()
11413
11414 if (frame_index < 0) or (self.m_stack_depth is None):
11415 return self.get_frame_index(fLock = False)
11416
11417 if self.m_state_manager.get_state() == STATE_ANALYZE:
11418 self.m_frame_index_exception = min(frame_index, self.m_stack_depth_exception - 1)
11419 si = self.m_frame_index_exception
11420
11421 else:
11422 self.m_frame_index = min(frame_index, self.m_stack_depth - 1)
11423 si = self.m_frame_index
11424
11425 finally:
11426 self.m_state_manager.release()
11427
11428 event = CEventStackFrameChange(si)
11429 self.m_event_dispatcher.fire_event(event)
11430
11431 event = CEventNamespace()
11432 self.m_event_dispatcher.fire_event(event)
11433
11434 return si
11435
11436
11437 def get_frame_index(self, fLock = True):
11438 try:
11439 if fLock:
11440 self.m_state_manager.acquire()
11441
11442 self.__verify_attached()
11443
11444 if self.m_state_manager.get_state() == STATE_ANALYZE:
11445 return self.m_frame_index_exception
11446 else:
11447 return self.m_frame_index
11448
11449 finally:
11450 if fLock:
11451 self.m_state_manager.release()
11452
11453
11454 def set_analyze(self, fAnalyze):
11455 try:
11456 self.m_state_manager.acquire()
11457
11458 if fAnalyze and (self.m_state_manager.get_state() != STATE_BROKEN):
11459 raise DebuggerNotBroken
11460
11461 if (not fAnalyze) and (self.m_state_manager.get_state() != STATE_ANALYZE):
11462 return
11463
11464 state = [STATE_BROKEN, STATE_ANALYZE][fAnalyze]
11465 self.m_state_manager.set_state(state, fLock = False)
11466
11467 finally:
11468 self.m_state_manager.release()
11469
11470 self.refresh()
11471
11472
11473 def getSession(self):
11474 self.__verify_attached()
11475
11476 return self.m_session
11477
11478
11479 def get_state(self):
11480 return as_unicode(self.m_state_manager.get_state())
11481
11482
11483 def set_password(self, _rpdb2_pwd):
11484 assert(is_unicode(_rpdb2_pwd))
11485
11486 if not is_valid_pwd(_rpdb2_pwd):
11487 raise BadArgument
11488
11489 try:
11490 self.m_state_manager.acquire()
11491
11492 self.__verify_unattached()
11493
11494 self.m_rpdb2_pwd = _rpdb2_pwd
11495 finally:
11496 self.m_state_manager.release()
11497
11498
11499 def set_random_password(self):
11500 try:
11501 self.m_state_manager.acquire()
11502
11503 self.__verify_unattached()
11504
11505 self.m_rpdb2_pwd = generate_random_password()
11506 self.m_printer(STR_RANDOM_PASSWORD)
11507
11508 finally:
11509 self.m_state_manager.release()
11510
11511
11512 def get_password(self):
11513 return self.m_rpdb2_pwd
11514
11515
11516 def set_remote(self, fAllowRemote):
11517 try:
11518 self.m_state_manager.acquire()
11519
11520 self.__verify_unattached()
11521
11522 self.m_fAllowRemote = fAllowRemote
11523 finally:
11524 self.m_state_manager.release()
11525
11526
11527 def get_remote(self):
11528 return self.m_fAllowRemote
11529
11530
11531 def set_environ(self, envmap):
11532 self.m_environment = []
11533
11534 try:
11535 for k, v in envmap:
11536 k = as_unicode(k, fstrict = True)
11537 v = as_unicode(v, fstrict = True)
11538
11539 self.m_environment.append((k, v))
11540
11541 except:
11542 raise BadArgument
11543
11544
11545 def get_environ(self):
11546 return self.m_environment
11547
11548
11549 def stop_debuggee(self):
11550 self.__verify_attached()
11551
11552 try:
11553 self.save_breakpoints()
11554 except:
11555 print_debug_exception()
11556 pass
11557
11558 self.m_printer(STR_ATTEMPTING_TO_STOP)
11559 self.m_printer(STR_ATTEMPTING_TO_DETACH)
11560
11561 self.m_state_manager.set_state(STATE_DETACHING)
11562
11563 self.__stop_event_monitor()
11564
11565 try:
11566 self.getSession().getProxy().stop_debuggee()
11567
11568 finally:
11569 self.m_state_manager.set_state(STATE_DETACHED)
11570 self.m_session = None
11571 self.m_printer(STR_DETACH_SUCCEEDED)
11572
11573
11574
11575 class CConsoleInternal(cmd.Cmd, threading.Thread):
11576 def __init__(self, session_manager, stdin = None, stdout = None, fSplit = False):
11577 global g_fDefaultStd
11578
11579 cmd.Cmd.__init__(self, stdin = stdin, stdout = stdout)
11580 threading.Thread.__init__(self)
11581
11582 self.fAnalyzeMode = False
11583 self.fPrintBroken = True
11584
11585 self.m_filename = as_unicode('')
11586
11587 self.m_completion_thread = None
11588
11589 self.use_rawinput = [1, 0][fSplit]
11590 self.m_fSplit = fSplit
11591 self.prompt = [[CONSOLE_PROMPT, CONSOLE_PROMPT_ANALYZE][self.fAnalyzeMode], ""][fSplit]
11592 self.intro = CONSOLE_INTRO
11593 if fSplit:
11594 self.intro += '\n'
11595
11596 #thread_set_daemon(self, True)
11597
11598 self.m_session_manager = session_manager
11599 self.m_session_manager.set_printer(self.printer)
11600
11601 event_type_dict = {CEventState: {}}
11602 self.m_session_manager.register_callback(self.event_handler, event_type_dict, fSingleUse = False)
11603
11604 event_type_dict = {CEventSynchronicity: {}}
11605 self.m_session_manager.register_callback(self.synchronicity_handler, event_type_dict, fSingleUse = False)
11606
11607 event_type_dict = {CEventTrap: {}}
11608 self.m_session_manager.register_callback(self.trap_handler, event_type_dict, fSingleUse = False)
11609
11610 event_type_dict = {CEventForkMode: {}}
11611 self.m_session_manager.register_callback(self.fork_mode_handler, event_type_dict, fSingleUse = False)
11612
11613 self.m_last_source_line = None
11614 self.m_last_nlines = DEFAULT_NUMBER_OF_LINES
11615
11616 self.m_fAddPromptBeforeMsg = False
11617 self.m_eInLoop = threading.Event()
11618 self.cmdqueue.insert(0, '')
11619
11620 self.m_stdout = self.stdout
11621 self.m_encoding = detect_encoding(self.stdin)
11622
11623 g_fDefaultStd = (stdin == None)
11624
11625 if self.use_rawinput:
11626 try:
11627 import readline
11628 cd = readline.get_completer_delims()
11629 if not '.' in cd:
11630 readline.set_completer_delims(cd + '.')
11631 except:
11632 pass
11633
11634
11635 def set_filename(self, filename):
11636 assert(is_unicode(filename))
11637
11638 self.m_filename = filename
11639
11640
11641 def precmd(self, line):
11642 line = as_unicode(line, self.m_encoding)
11643
11644 self.m_fAddPromptBeforeMsg = True
11645 if not event_is_set(self.m_eInLoop):
11646 self.m_eInLoop.set()
11647 time.sleep(0.01)
11648
11649 if not line.strip():
11650 return line
11651
11652 command = line.split(' ', 1)[0].split(SOURCE_MORE, 1)[0].split(SOURCE_LESS, 1)[0]
11653 if command not in ['list', 'l']:
11654 self.m_last_source_line = None
11655 self.m_last_nlines = DEFAULT_NUMBER_OF_LINES
11656
11657 return line
11658
11659
11660 def postcmd(self, stop, line):
11661 self.m_fAddPromptBeforeMsg = False
11662
11663 return stop
11664
11665
11666 def onecmd(self, line):
11667 """
11668 Default Error handling and reporting of session manager errors.
11669 """
11670
11671 try:
11672 return cmd.Cmd.onecmd(self, line)
11673
11674 except (socket.error, CConnectionException):
11675 self.m_session_manager.report_exception(*sys.exc_info())
11676 except CException:
11677 self.m_session_manager.report_exception(*sys.exc_info())
11678 except:
11679 self.m_session_manager.report_exception(*sys.exc_info())
11680 print_debug_exception(True)
11681
11682 return False
11683
11684
11685 def default(self, line):
11686 """
11687 Called on an input line when the command prefix is not recognized.
11688 Over-rides base method at cmd.py.
11689 """
11690
11691 self.printer(STR_BAD_SYNTAX % line)
11692
11693
11694 def emptyline(self):
11695 pass
11696
11697
11698 def complete(self, text, state):
11699 """
11700 Return the next possible completion for 'text'.
11701 If a command has not been entered, then complete against command list.
11702 Otherwise try to call complete_<command> to get list of completions.
11703 """
11704
11705 if self.use_rawinput:
11706 #
11707 # Import cmd to workaround a strange bug in Python.
11708 #
11709 import cmd
11710 return cmd.Cmd.complete(self, text, state)
11711
11712 #
11713 # Without rawinput assuming text includes entire buffer up to cursor.
11714 #
11715
11716 try:
11717 if state != 0:
11718 return self.completion_matches[state]
11719
11720 if not ' ' in text:
11721 self.completion_matches = self.completenames(text)
11722 return self.completion_matches[state]
11723
11724 cmd, args, foo = self.parseline(text)
11725 if cmd == '' or not hasattr(self, 'complete_' + cmd):
11726 self.completion_matches = self.completedefault(text)
11727 return self.completion_matches[state]
11728
11729 compfunc = getattr(self, 'complete_' + cmd)
11730
11731 self.completion_matches = compfunc(text)
11732 return self.completion_matches[state]
11733
11734 except IndexError:
11735 return None
11736
11737
11738 def complete_launch(self, text, line = None, begidx = None, endidx = None):
11739 if line != None and endidx != None:
11740 text = line[:endidx]
11741
11742 if text.endswith(' '):
11743 dn, bn = '', ''
11744 else:
11745 path = text.split()[-1]
11746 dn, bn = os.path.split(path)
11747
11748 prefix = text
11749 if bn != '':
11750 prefix = prefix[:-len(bn)]
11751
11752 if dn == '' and bn.startswith('~'):
11753 if bn == os.path.expanduser(bn):
11754 c = text
11755 else:
11756 c = os.path.join(text, '')
11757
11758 if begidx != None:
11759 c = c[begidx:]
11760
11761 return [c]
11762
11763 pl = [dn]
11764 if dn == '':
11765 pl += os.environ['PATH'].split(os.pathsep)
11766
11767 fl = []
11768 for p in pl:
11769 if p == '':
11770 p = '.'
11771
11772 try:
11773 ep = os.path.expanduser(p)
11774 l = os.listdir(ep)
11775 for f in l:
11776 if not f.startswith(bn):
11777 continue
11778
11779 root, ext = os.path.splitext(f)
11780 if not ext in ['.py', '.pyw', '']:
11781 continue
11782
11783 if os.path.isdir(os.path.join(ep, f)):
11784 c = prefix + os.path.join(f, '')
11785 else:
11786 c = prefix + f
11787
11788 if begidx != None:
11789 c = c[begidx:]
11790
11791 fl.append(c)
11792 except:
11793 pass
11794
11795 fs = set(fl)
11796 cl = list(fs)
11797 cl.sort()
11798
11799 return cl
11800
11801
11802 def complete_eval(self, text, line = None, begidx = None, endidx = None):
11803 t = self.m_completion_thread
11804 if t != None and thread_is_alive(t):
11805 return []
11806
11807 self.m_completion_thread = None
11808 result = [('', [])]
11809
11810 if line != None and endidx != None:
11811 text = line[:endidx]
11812
11813 t = threading.Thread(target = self.complete_expression_job, args = (text, result))
11814 t.start()
11815 t.join(PING_TIMEOUT)
11816
11817 if thread_is_alive(t):
11818 self.m_completion_thread = t
11819 return []
11820
11821 (prefix, completions) = result[-1]
11822
11823 if begidx != None:
11824 prefix = prefix[begidx:]
11825
11826 ce = [prefix + c for c in completions]
11827
11828 return ce
11829
11830 complete_v = complete_eval
11831 complete_exec = complete_eval
11832 complete_x = complete_exec
11833
11834
11835 def complete_expression_job(self, text, result):
11836 try:
11837 (prefix, completions) = self.m_session_manager.complete_expression(text)
11838 result.append((prefix, completions))
11839
11840 except:
11841 print_debug_exception()
11842
11843
11844 def run(self):
11845 self.cmdloop()
11846
11847
11848 def __get_str_wrap(self, _str, max_len):
11849 if len(_str) <= max_len and not '\n' in _str:
11850 return (_str, '')
11851
11852 s = _str[: max_len]
11853
11854 i = s.find('\n')
11855
11856 if i == -1:
11857 i = s.rfind(' ')
11858
11859 if i == -1:
11860 return (s, _str[max_len:])
11861
11862 return (_str[: i], _str[i + 1:])
11863
11864
11865 def printer(self, _str):
11866 if not event_is_set(self.m_eInLoop):
11867 self.m_eInLoop.wait()
11868
11869 fAPBM = self.m_fAddPromptBeforeMsg
11870 prefix = ['', self.prompt.strip('\n')][fAPBM] + CONSOLE_PRINTER
11871 suffix = '\n' + [self.prompt.strip('\n'), ''][fAPBM]
11872
11873 s = _str
11874 while s != '':
11875 s, _s = self.__get_str_wrap(s, CONSOLE_WRAP_INDEX - len(prefix + suffix))
11876 _print(prefix + s + suffix, self.m_stdout, feol = False)
11877 s = _s
11878
11879 self.m_stdout.flush()
11880
11881
11882 def print_notice(self, notice):
11883 nl = notice.split('\n')
11884
11885 i = 0
11886 for l in nl:
11887 _print(l, self.m_stdout)
11888 i += 1
11889 if i % PRINT_NOTICE_LINES_PER_SECTION == 0:
11890 _print("\n" + PRINT_NOTICE_PROMPT, self.m_stdout, feol = False)
11891 response = self.stdin.readline()
11892 if response != '\n':
11893 break
11894
11895 _print('', self.m_stdout)
11896
11897
11898 def event_handler(self, event):
11899 state = event.m_state
11900 if (state == STATE_BROKEN) and self.fPrintBroken:
11901 self.fPrintBroken = False
11902 self.printer(STR_DEBUGGER_HAS_BROKEN)
11903 return
11904
11905 if (state != STATE_ANALYZE) and self.fAnalyzeMode:
11906 self.fAnalyzeMode = False
11907 self.prompt = [CONSOLE_PROMPT, ""][self.m_fSplit]
11908 self.printer(STR_ANALYZE_MODE_TOGGLE % MODE_OFF)
11909 return
11910
11911 if (state == STATE_ANALYZE) and not self.fAnalyzeMode:
11912 self.fAnalyzeMode = True
11913 self.prompt = [CONSOLE_PROMPT_ANALYZE, ""][self.m_fSplit]
11914 self.printer(STR_ANALYZE_MODE_TOGGLE % MODE_ON)
11915 return
11916
11917
11918 def synchronicity_handler(self, event):
11919 self.printer(STR_SYNCHRONICITY_MODE % str(event.m_fsynchronicity))
11920
11921
11922 def trap_handler(self, event):
11923 self.printer(STR_TRAP_MODE_SET % str(event.m_ftrap))
11924
11925
11926 def fork_mode_handler(self, event):
11927 x = [FORK_PARENT, FORK_CHILD][event.m_ffork_into_child]
11928 y = [FORK_MANUAL, FORK_AUTO][event.m_ffork_auto]
11929
11930 self.printer(STR_FORK_MODE_SET % (x, y))
11931
11932
11933 def do_launch(self, arg):
11934 if arg == '':
11935 self.printer(STR_BAD_ARGUMENT)
11936 return
11937
11938 if arg[:2] == '-k':
11939 fchdir = False
11940 _arg = arg[2:].strip()
11941 else:
11942 fchdir = True
11943 _arg = arg
11944
11945 self.fPrintBroken = True
11946
11947 try:
11948 self.m_session_manager.launch(fchdir, _arg)
11949 return
11950
11951 except BadArgument:
11952 self.printer(STR_BAD_ARGUMENT)
11953 except IOError:
11954 self.printer(STR_FILE_NOT_FOUND % arg)
11955 except:
11956 self.fPrintBroken = False
11957 raise
11958
11959 self.fPrintBroken = False
11960
11961
11962 def do_restart(self, arg):
11963 if arg != '':
11964 self.printer(STR_BAD_ARGUMENT)
11965 return
11966
11967 try:
11968 self.m_session_manager.restart()
11969 return
11970
11971 except BadArgument:
11972 self.printer(STR_BAD_ARGUMENT)
11973 except IOError:
11974 self.printer(STR_FILE_NOT_FOUND % arg)
11975 except:
11976 self.fPrintBroken = False
11977 raise
11978
11979 self.fPrintBroken = False
11980
11981
11982 def do_attach(self, arg):
11983 if arg == '':
11984 return self.__scripts(arg)
11985
11986 self.fPrintBroken = True
11987
11988 try:
11989 self.m_session_manager.attach(arg)
11990 return
11991
11992 except BadArgument:
11993 self.printer(STR_BAD_ARGUMENT)
11994 except:
11995 self.fPrintBroken = False
11996 raise
11997
11998 self.fPrintBroken = False
11999
12000
12001 def __scripts(self, arg):
12002 if self.m_session_manager.get_password() is None:
12003 _print(STR_PASSWORD_MUST_BE_SET, self.m_stdout)
12004 return
12005
12006 host = self.m_session_manager.get_host()
12007 _print(STR_SCRIPTS_CONNECTING % host, self.m_stdout)
12008
12009 (server_list, errors) = self.m_session_manager.calc_server_list()
12010
12011 if server_list == []:
12012 _print(STR_SCRIPTS_NO_SCRIPTS % host, self.m_stdout)
12013 return
12014
12015 try:
12016 spid = self.m_session_manager.get_server_info().m_pid
12017 except NotAttached:
12018 spid = None
12019
12020 _print(STR_SCRIPTS_TO_DEBUG % host, self.m_stdout)
12021 for s in server_list:
12022 m = ['', SYMBOL_MARKER][spid == s.m_pid]
12023 _print(' %1s %-5d %s' % (m, s.m_pid, s.m_filename), self.m_stdout)
12024
12025
12026 def do_detach(self, arg):
12027 if not arg == '':
12028 self.printer(STR_BAD_ARGUMENT)
12029 return
12030
12031 self.m_session_manager.detach()
12032
12033
12034 def do_host(self, arg):
12035 if arg == '':
12036 host = self.m_session_manager.get_host()
12037 _print(host, self.m_stdout)
12038 return
12039
12040 try:
12041 self.m_session_manager.set_host(arg)
12042
12043 except socket.gaierror:
12044 e = sys.exc_info()[1]
12045 self.printer(MSG_ERROR_HOST_TEXT % (arg, e))
12046
12047
12048 def do_break(self, arg):
12049 if arg != '':
12050 self.printer(STR_BAD_ARGUMENT)
12051 return
12052
12053 self.m_session_manager.request_break()
12054
12055 do_b = do_break
12056
12057
12058 def __parse_bp_arg(self, arg, fAllowExpr = True):
12059 _args = arg.split(BP_EVAL_SEP)
12060
12061 if (len(_args) > 1) and (not fAllowExpr):
12062 raise BadArgument
12063
12064 if len(_args) > 1:
12065 expr = _args[1].strip()
12066 else:
12067 expr = ''
12068
12069 rf = _args[0].rfind(BP_FILENAME_SEP)
12070 if rf == -1:
12071 args = [_args[0]]
12072 else:
12073 args = [_args[0][:rf], _args[0][rf + 1:]]
12074
12075 filename = ['', args[0]][len(args) > 1]
12076
12077 if filename in [None, '']:
12078 filename = self.m_filename
12079
12080 try:
12081 lineno = int(args[-1])
12082 scope = ''
12083 except ValueError:
12084 lineno = 0
12085 scope = args[-1].strip()
12086
12087 return (filename, scope, lineno, expr)
12088
12089
12090 def do_go(self, arg):
12091 if self.fAnalyzeMode:
12092 self.printer(STR_ILEGAL_ANALYZE_MODE_CMD)
12093 return
12094
12095 try:
12096 if arg != '':
12097 (filename, scope, lineno, expr) = self.__parse_bp_arg(arg, fAllowExpr = False)
12098 self.fPrintBroken = True
12099 self.m_session_manager.request_go_breakpoint(filename, scope, lineno)
12100 return
12101
12102 self.fPrintBroken = True
12103 self.m_session_manager.request_go()
12104 return
12105
12106 except BadArgument:
12107 self.printer(STR_BAD_ARGUMENT)
12108 except IOError:
12109 self.printer(STR_FILE_NOT_FOUND % filename)
12110 except InvalidScopeName:
12111 self.printer(STR_SCOPE_NOT_FOUND % scope)
12112 except DebuggerNotBroken:
12113 self.m_session_manager.report_exception(*sys.exc_info())
12114 except:
12115 self.fPrintBroken = False
12116 raise
12117
12118 self.fPrintBroken = False
12119
12120 do_g = do_go
12121
12122
12123 def do_step(self, arg):
12124 if arg != '':
12125 self.printer(STR_BAD_ARGUMENT)
12126 return
12127
12128 if self.fAnalyzeMode:
12129 self.printer(STR_ILEGAL_ANALYZE_MODE_CMD)
12130 return
12131
12132 try:
12133 self.m_session_manager.request_step()
12134
12135 except DebuggerNotBroken:
12136 self.m_session_manager.report_exception(*sys.exc_info())
12137
12138 do_s = do_step
12139
12140
12141 def do_next(self, arg):
12142 if arg != '':
12143 self.printer(STR_BAD_ARGUMENT)
12144 return
12145
12146 if self.fAnalyzeMode:
12147 self.printer(STR_ILEGAL_ANALYZE_MODE_CMD)
12148 return
12149
12150 try:
12151 self.m_session_manager.request_next()
12152
12153 except DebuggerNotBroken:
12154 self.m_session_manager.report_exception(*sys.exc_info())
12155
12156 do_n = do_next
12157
12158
12159 def do_return(self, arg):
12160 if arg != '':
12161 self.printer(STR_BAD_ARGUMENT)
12162 return
12163
12164 if self.fAnalyzeMode:
12165 self.printer(STR_ILEGAL_ANALYZE_MODE_CMD)
12166 return
12167
12168 try:
12169 self.m_session_manager.request_return()
12170
12171 except DebuggerNotBroken:
12172 self.m_session_manager.report_exception(*sys.exc_info())
12173
12174 do_r = do_return
12175
12176
12177 def do_jump(self, arg):
12178 try:
12179 lineno = int(arg)
12180 except ValueError:
12181 self.printer(STR_BAD_ARGUMENT)
12182 return
12183
12184 try:
12185 self.m_session_manager.request_jump(lineno)
12186
12187 except DebuggerNotBroken:
12188 self.m_session_manager.report_exception(*sys.exc_info())
12189
12190 do_j = do_jump
12191
12192
12193 def do_bp(self, arg):
12194 if arg == '':
12195 self.printer(STR_BAD_ARGUMENT)
12196 return
12197
12198 try:
12199 (filename, scope, lineno, expr) = self.__parse_bp_arg(arg, fAllowExpr = True)
12200 self.m_session_manager.set_breakpoint(filename, scope, lineno, True, expr)
12201
12202 except BadArgument:
12203 self.printer(STR_BAD_ARGUMENT)
12204 except IOError:
12205 self.printer(STR_FILE_NOT_FOUND % filename)
12206 except InvalidScopeName:
12207 self.printer(STR_SCOPE_NOT_FOUND % scope)
12208 except SyntaxError:
12209 self.printer(STR_BAD_EXPRESSION % expr)
12210 except DebuggerNotBroken:
12211 self.m_session_manager.report_exception(*sys.exc_info())
12212
12213
12214 def do_be(self, arg):
12215 if arg == '':
12216 self.printer(STR_BAD_ARGUMENT)
12217 return
12218
12219 try:
12220 id_list = []
12221 fAll = (arg == SYMBOL_ALL)
12222
12223 if not fAll:
12224 sid_list = arg.split()
12225 id_list = [int(sid) for sid in sid_list]
12226
12227 self.m_session_manager.enable_breakpoint(id_list, fAll)
12228
12229 except ValueError:
12230 self.printer(STR_BAD_ARGUMENT)
12231
12232
12233 def do_bd(self, arg):
12234 if arg == '':
12235 self.printer(STR_BAD_ARGUMENT)
12236 return
12237
12238 try:
12239 id_list = []
12240 fAll = (arg == SYMBOL_ALL)
12241
12242 if not fAll:
12243 sid_list = arg.split()
12244 id_list = [int(sid) for sid in sid_list]
12245
12246 self.m_session_manager.disable_breakpoint(id_list, fAll)
12247
12248 except ValueError:
12249 self.printer(STR_BAD_ARGUMENT)
12250
12251
12252 def do_bc(self, arg):
12253 if arg == '':
12254 self.printer(STR_BAD_ARGUMENT)
12255 return
12256
12257 try:
12258 id_list = []
12259 fAll = (arg == SYMBOL_ALL)
12260
12261 if not fAll:
12262 sid_list = arg.split()
12263 id_list = [int(sid) for sid in sid_list]
12264
12265 self.m_session_manager.delete_breakpoint(id_list, fAll)
12266
12267 except ValueError:
12268 self.printer(STR_BAD_ARGUMENT)
12269
12270
12271 def do_bl(self, arg):
12272 bpl = self.m_session_manager.get_breakpoints()
12273
12274 bplk = list(bpl.keys())
12275 bplk.sort()
12276
12277 _print(STR_BREAKPOINTS_LIST, self.m_stdout)
12278 for id in bplk:
12279 bp = bpl[id]
12280
12281 if bp.m_expr:
12282 expr = bp.m_expr
12283 else:
12284 expr = ''
12285
12286 try:
12287 expr.encode('ascii', 'strict')
12288 encoding = ''
12289 except:
12290 encoding = bp.m_encoding
12291
12292 scope = bp.m_scope_fqn
12293
12294 if scope.startswith(MODULE_SCOPE + '.'):
12295 scope = scope[len(MODULE_SCOPE) + 1:]
12296
12297 elif scope.startswith(MODULE_SCOPE2 + '.'):
12298 scope = scope[len(MODULE_SCOPE2) + 1:]
12299
12300 state = [STATE_DISABLED, STATE_ENABLED][bp.isEnabled()]
12301 s = STR_BREAKPOINTS_TEMPLATE % (id, state, bp.m_lineno, clip_filename(bp.m_filename, 45), calc_suffix(scope, 45), calc_prefix(expr, 50), encoding)
12302 _print(s.rstrip() + '\n', self.m_stdout)
12303
12304
12305 def do_save(self, arg):
12306 self.m_session_manager.save_breakpoints(arg)
12307 _print(STR_BREAKPOINTS_SAVED, self.m_stdout)
12308 return
12309
12310
12311 def do_load(self, arg):
12312 try:
12313 self.m_session_manager.load_breakpoints(arg)
12314 _print(STR_BREAKPOINTS_LOADED, self.m_stdout)
12315 return
12316
12317 except IOError:
12318 error = [STR_BREAKPOINTS_FILE_NOT_FOUND, STR_BREAKPOINTS_NOT_FOUND][arg == '']
12319 self.printer(error)
12320
12321
12322 def do_stack(self, arg):
12323 if self.fAnalyzeMode and (arg != ''):
12324 self.printer(STR_ILEGAL_ANALYZE_MODE_ARG)
12325 return
12326
12327 try:
12328 tid_list = []
12329 fAll = (arg == SYMBOL_ALL)
12330
12331 if not fAll:
12332 sid_list = arg.split()
12333 tid_list = [int(sid) for sid in sid_list]
12334
12335 sl = self.m_session_manager.get_stack(tid_list, fAll)
12336
12337 if len(sl) == 0:
12338 self.printer(STR_NO_THREADS_FOUND)
12339 return
12340
12341 frame_index = self.m_session_manager.get_frame_index()
12342
12343 m = None
12344 for st in sl:
12345 s = st.get(DICT_KEY_STACK, [])
12346 tid = st.get(DICT_KEY_TID, 0)
12347 fBroken = st.get(DICT_KEY_BROKEN, False)
12348 fCurrent = st.get(DICT_KEY_CURRENT_TID, False)
12349
12350 if m is not None:
12351 _print('', self.m_stdout)
12352
12353 _print(STR_STACK_TRACE % tid, self.m_stdout)
12354 i = 0
12355 while i < len(s):
12356 e = s[-(1 + i)]
12357
12358 marker = [SOURCE_STATE_UNBROKEN, SYMBOL_MARKER][fBroken]
12359
12360 if fCurrent:
12361 m = ['', marker][i == frame_index]
12362 else:
12363 m = ['', marker][i == 0]
12364
12365 _print(' %1s %5d %-28s %4d %s' % (m, i, calc_suffix(e[0], 28), e[1], calc_prefix(e[2], 20)), self.m_stdout)
12366 i += 1
12367
12368 except ValueError:
12369 self.printer(STR_BAD_ARGUMENT)
12370 except (NoExceptionFound, NoThreads):
12371 self.m_session_manager.report_exception(*sys.exc_info())
12372
12373 do_k = do_stack
12374
12375
12376 def do_list(self, arg):
12377 rf = arg.rfind(BP_FILENAME_SEP)
12378 if rf == -1:
12379 _filename = ''
12380 __args2 = arg
12381 else:
12382 _filename = arg[:rf]
12383 __args2 = arg[rf + 1:]
12384
12385 _args = __args2.split(BP_EVAL_SEP)
12386
12387 fAll = (_args[0] == SYMBOL_ALL)
12388 fMore = (_args[0] == SOURCE_MORE)
12389 fLess = (_args[0] == SOURCE_LESS)
12390 fEntire = (_args[0] == SOURCE_ENTIRE_FILE)
12391 fCurrent = (_args[0] == '')
12392 fLine = False
12393 l = 1
12394
12395 try:
12396 if len(_args) > 1:
12397 nlines = int(_args[1])
12398 else:
12399 nlines = self.m_last_nlines
12400
12401 if not (fAll or fMore or fLess or fEntire or fCurrent):
12402 l = int(_args[0])
12403 fLine = True
12404
12405 except ValueError:
12406 self.printer(STR_BAD_ARGUMENT)
12407 return
12408
12409 if self.fAnalyzeMode and fAll:
12410 self.printer(STR_ILEGAL_ANALYZE_MODE_ARG)
12411 return
12412
12413 if fMore and self.m_last_source_line:
12414 l = max(1, self.m_last_source_line + self.m_last_nlines // 2 + 1)
12415 fLine = True
12416 elif fLess and self.m_last_source_line:
12417 l = max(1, self.m_last_source_line - (self.m_last_nlines - 1) // 2 - nlines)
12418 fLine = True
12419
12420 try:
12421 if fEntire:
12422 r = [self.m_session_manager.get_source_file(_filename, -1, -1)]
12423 elif fLine:
12424 r = [self.m_session_manager.get_source_file(_filename, l, nlines)]
12425 elif _filename != '':
12426 r = [self.m_session_manager.get_source_file(_filename, l, nlines)]
12427 else:
12428 r = self.m_session_manager.get_source_lines(nlines, fAll)
12429
12430 if len(r) == 0:
12431 self.printer(STR_NO_THREADS_FOUND)
12432 return
12433
12434 m = None
12435 for d in r:
12436 tid = d.get(DICT_KEY_TID, 0)
12437 filename = d.get(DICT_KEY_FILENAME, '')
12438 breakpoints = d.get(DICT_KEY_BREAKPOINTS, {})
12439 source_lines = d.get(DICT_KEY_LINES, [])
12440 first_lineno = d.get(DICT_KEY_FIRST_LINENO, 0)
12441
12442 if len(r) == 1 and first_lineno != 0:
12443 l = first_lineno
12444
12445 fBroken = d.get(DICT_KEY_BROKEN, False)
12446 frame_event = d.get(DICT_KEY_EVENT, '')
12447 frame_lineno = d.get(DICT_KEY_FRAME_LINENO, 0)
12448
12449 if m is not None:
12450 _print('', self.m_stdout)
12451
12452 _print(STR_SOURCE_LINES % (tid, filename), self.m_stdout)
12453 for i, line in enumerate(source_lines):
12454 lineno = first_lineno + i
12455 if lineno != frame_lineno:
12456 m = ''
12457 elif not fBroken:
12458 m = SOURCE_STATE_UNBROKEN + SYMBOL_MARKER
12459 elif frame_event == 'call':
12460 m = SOURCE_EVENT_CALL + SYMBOL_MARKER
12461 elif frame_event == 'line':
12462 m = SOURCE_EVENT_LINE + SYMBOL_MARKER
12463 elif frame_event == 'return':
12464 m = SOURCE_EVENT_RETURN + SYMBOL_MARKER
12465 elif frame_event == 'exception':
12466 m = SOURCE_EVENT_EXCEPTION + SYMBOL_MARKER
12467
12468 if breakpoints.get(lineno, None) == STATE_ENABLED:
12469 b = SOURCE_BP_ENABLED
12470 elif breakpoints.get(lineno, None) == STATE_DISABLED:
12471 b = SOURCE_BP_DISABLED
12472 else:
12473 b = ''
12474
12475 line = line.replace('\t', ' ' * PYTHON_TAB_WIDTH)
12476
12477 _print(' %2s %1s %5d %s' % (m, b, lineno, calc_prefix(line[:-1], 60)), self.m_stdout)
12478
12479 if fAll or fEntire:
12480 self.m_last_source_line = None
12481 elif len(source_lines) != 0:
12482 self.m_last_source_line = [l + (nlines - 1) // 2, frame_lineno][l == -1]
12483
12484 self.m_last_nlines = nlines
12485
12486 except (InvalidFrame, IOError):
12487 self.printer(STR_SOURCE_NOT_FOUND)
12488 except (NoExceptionFound, NoThreads):
12489 self.m_session_manager.report_exception(*sys.exc_info())
12490
12491 do_l = do_list
12492
12493
12494 def do_up(self, arg):
12495 if arg != '':
12496 self.printer(STR_BAD_ARGUMENT)
12497 return
12498
12499 try:
12500 fi = self.m_session_manager.get_frame_index()
12501 self.m_session_manager.set_frame_index(fi - 1)
12502
12503 except DebuggerNotBroken:
12504 self.m_session_manager.report_exception(*sys.exc_info())
12505
12506
12507 def do_down(self, arg):
12508 if arg != '':
12509 self.printer(STR_BAD_ARGUMENT)
12510 return
12511
12512 try:
12513 fi = self.m_session_manager.get_frame_index()
12514 self.m_session_manager.set_frame_index(fi + 1)
12515
12516 except DebuggerNotBroken:
12517 self.m_session_manager.report_exception(*sys.exc_info())
12518
12519
12520 def evaluate_job(self, sync_event, expr):
12521 try:
12522 (value, warning, error) = self.m_session_manager.evaluate(expr)
12523
12524 if warning:
12525 self.printer(STR_WARNING % warning)
12526
12527 if error:
12528 _print(error + '\n', self.m_stdout)
12529
12530 _print(value, self.m_stdout)
12531
12532 if event_is_set(sync_event):
12533 _print(self.prompt, self.m_stdout, feol = False)
12534
12535 return
12536
12537 except (NoExceptionFound, DebuggerNotBroken):
12538 self.m_session_manager.report_exception(*sys.exc_info())
12539
12540 except (socket.error, CConnectionException):
12541 self.m_session_manager.report_exception(*sys.exc_info())
12542 except CException:
12543 self.m_session_manager.report_exception(*sys.exc_info())
12544 except:
12545 self.m_session_manager.report_exception(*sys.exc_info())
12546 print_debug_exception(True)
12547
12548
12549 def do_eval(self, arg):
12550 if arg == '':
12551 self.printer(STR_BAD_ARGUMENT)
12552 return
12553
12554 sync_event = threading.Event()
12555 t = threading.Thread(target = self.evaluate_job, args = (sync_event, arg))
12556 t.start()
12557 t.join(WAIT_FOR_BREAK_TIMEOUT)
12558
12559 if thread_is_alive(t):
12560 _print(STR_OUTPUT_WARNING_ASYNC, self.m_stdout)
12561 sync_event.set()
12562
12563 do_v = do_eval
12564
12565
12566 def execute_job(self, sync_event, suite):
12567 try:
12568 (warning, error) = self.m_session_manager.execute(suite)
12569
12570 if warning:
12571 self.printer(STR_WARNING % warning)
12572
12573 if error:
12574 _print(error + '\n', self.m_stdout)
12575
12576 if event_is_set(sync_event):
12577 _print(self.prompt, self.m_stdout, feol = False)
12578
12579 return
12580
12581 except (NoExceptionFound, DebuggerNotBroken):
12582 self.m_session_manager.report_exception(*sys.exc_info())
12583
12584 except (socket.error, CConnectionException):
12585 self.m_session_manager.report_exception(*sys.exc_info())
12586 except CException:
12587 self.m_session_manager.report_exception(*sys.exc_info())
12588 except:
12589 self.m_session_manager.report_exception(*sys.exc_info())
12590 print_debug_exception(True)
12591
12592
12593 def do_exec(self, arg):
12594 if arg == '':
12595 self.printer(STR_BAD_ARGUMENT)
12596 return
12597
12598 _print(STR_OUTPUT_WARNING, self.m_stdout)
12599
12600 sync_event = threading.Event()
12601 t = threading.Thread(target = self.execute_job, args = (sync_event, arg))
12602 t.start()
12603 t.join(WAIT_FOR_BREAK_TIMEOUT)
12604
12605 if thread_is_alive(t):
12606 _print(STR_OUTPUT_WARNING_ASYNC, self.m_stdout)
12607 sync_event.set()
12608
12609 do_x = do_exec
12610
12611
12612 def do_encoding(self, arg):
12613 if arg == '':
12614 encoding, fraw = self.m_session_manager.get_encoding()
12615 if encoding != ENCODING_AUTO:
12616 try:
12617 codecs.lookup(encoding)
12618 except:
12619 encoding += ' (?)'
12620
12621 if fraw:
12622 encoding += ', ' + ENCODING_RAW
12623
12624 _print(STR_ENCODING_MODE % encoding, self.m_stdout)
12625 return
12626
12627 if ',' in arg:
12628 encoding, raw = arg.split(',')
12629 else:
12630 encoding, raw = arg, ''
12631
12632 encoding = encoding.strip()
12633 if encoding == '':
12634 encoding, fraw = self.m_session_manager.get_encoding()
12635
12636 fraw = 'raw' in raw
12637
12638 self.m_session_manager.set_encoding(encoding, fraw)
12639
12640 if encoding != ENCODING_AUTO:
12641 try:
12642 codecs.lookup(encoding)
12643 except:
12644 encoding += ' (?)'
12645 _print(STR_ENCODING_BAD, self.m_stdout)
12646
12647 if fraw:
12648 encoding += ', ' + ENCODING_RAW
12649
12650 _print(STR_ENCODING_MODE_SET % encoding, self.m_stdout)
12651
12652
12653 def do_thread(self, arg):
12654 if self.fAnalyzeMode and (arg != ''):
12655 self.printer(STR_ILEGAL_ANALYZE_MODE_ARG)
12656 return
12657
12658 try:
12659 if arg != '':
12660 tid = int(arg)
12661 self.m_session_manager.set_thread(tid)
12662
12663 _print(STR_THREAD_FOCUS_SET, self.m_stdout)
12664 return
12665
12666 (current_thread_id, tl) = self.m_session_manager.get_thread_list()
12667
12668 _print(STR_ACTIVE_THREADS, self.m_stdout)
12669 for i, t in enumerate(tl):
12670 m = ['', SYMBOL_MARKER][t[DICT_KEY_TID] == current_thread_id]
12671 state = [STATE_RUNNING, STR_STATE_BROKEN][t[DICT_KEY_BROKEN]]
12672 _print(' %1s %3d %5d %-15s %s' % (m, i, t[DICT_KEY_TID], t[DICT_KEY_NAME], state[:25]), self.m_stdout)
12673
12674 except ValueError:
12675 self.printer(STR_BAD_ARGUMENT)
12676 except ThreadNotFound:
12677 self.printer(STR_THREAD_NOT_FOUND)
12678 except DebuggerNotBroken:
12679 self.m_session_manager.report_exception(*sys.exc_info())
12680
12681 do_t = do_thread
12682
12683
12684 def do_analyze(self, arg):
12685 if arg != '':
12686 self.printer(STR_BAD_ARGUMENT)
12687 return
12688
12689 try:
12690 self.m_session_manager.set_analyze(not self.fAnalyzeMode)
12691
12692 except DebuggerNotBroken:
12693 self.m_session_manager.report_exception(*sys.exc_info())
12694
12695 do_a = do_analyze
12696
12697
12698 def do_synchro(self, arg):
12699 if arg == '':
12700 fsynchronicity = self.m_session_manager.get_synchronicity()
12701 _print(STR_SYNCHRONICITY_MODE % str(fsynchronicity), self.m_stdout)
12702 return
12703
12704 if arg == str(True):
12705 fsynchronicity = True
12706 elif arg == str(False):
12707 fsynchronicity = False
12708 else:
12709 _print(STR_BAD_ARGUMENT, self.m_stdout)
12710 return
12711
12712 self.m_session_manager.set_synchronicity(fsynchronicity)
12713
12714
12715 def do_trap(self, arg):
12716 if arg == '':
12717 ftrap = self.m_session_manager.get_trap_unhandled_exceptions()
12718 _print(STR_TRAP_MODE % str(ftrap), self.m_stdout)
12719 return
12720
12721 if arg == str(True):
12722 ftrap = True
12723 elif arg == str(False):
12724 ftrap = False
12725 else:
12726 _print(STR_BAD_ARGUMENT, self.m_stdout)
12727 return
12728
12729 self.m_session_manager.set_trap_unhandled_exceptions(ftrap)
12730
12731
12732 def do_fork(self, arg):
12733 (ffork_into_child, ffork_auto) = self.m_session_manager.get_fork_mode()
12734
12735 if arg == '':
12736 x = [FORK_PARENT, FORK_CHILD][ffork_into_child]
12737 y = [FORK_MANUAL, FORK_AUTO][ffork_auto]
12738
12739 _print(STR_FORK_MODE % (x, y), self.m_stdout)
12740 return
12741
12742 arg = arg.lower()
12743
12744 if FORK_PARENT in arg:
12745 ffork_into_child = False
12746 elif FORK_CHILD in arg:
12747 ffork_into_child = True
12748
12749 if FORK_AUTO in arg:
12750 ffork_auto = True
12751 elif FORK_MANUAL in arg:
12752 ffork_auto = False
12753
12754 self.m_session_manager.set_fork_mode(ffork_into_child, ffork_auto)
12755
12756
12757 def do_password(self, arg):
12758 if arg == '':
12759 _rpdb2_pwd = self.m_session_manager.get_password()
12760 if _rpdb2_pwd is None:
12761 _print(STR_PASSWORD_NOT_SET, self.m_stdout)
12762 else:
12763 _print(STR_PASSWORD_SET % _rpdb2_pwd, self.m_stdout)
12764 return
12765
12766 _rpdb2_pwd = arg.strip('"\'')
12767
12768 try:
12769 self.m_session_manager.set_password(_rpdb2_pwd)
12770 _print(STR_PASSWORD_SET % _rpdb2_pwd, self.m_stdout)
12771
12772 except BadArgument:
12773 _print(STR_PASSWORD_BAD, self.m_stdout)
12774
12775
12776 def do_remote(self, arg):
12777 if arg == '':
12778 fAllowRemote = self.m_session_manager.get_remote()
12779 _print(STR_REMOTE_MODE % str(fAllowRemote), self.m_stdout)
12780 return
12781
12782 if arg == str(True):
12783 fAllowRemote = True
12784 elif arg == str(False):
12785 fAllowRemote = False
12786 else:
12787 _print(STR_BAD_ARGUMENT, self.m_stdout)
12788 return
12789
12790 self.m_session_manager.set_remote(fAllowRemote)
12791 _print(STR_REMOTE_MODE % str(fAllowRemote), self.m_stdout)
12792
12793
12794 def do_env(self, arg):
12795 env = self.m_session_manager.get_environ()
12796
12797 if arg == '':
12798 if len(env) == 0:
12799 _print(STR_ENVIRONMENT_EMPTY, self.m_stdout)
12800 return
12801
12802 _print(STR_ENVIRONMENT, self.m_stdout)
12803 for k, v in env:
12804 _print('%s=%s' % (k, v), self.m_stdout)
12805 return
12806
12807 if arg[:2] == '-d':
12808 k = arg[2:].strip()
12809 _env = [(_k, _v) for (_k, _v) in env if _k != k]
12810 self.m_session_manager.set_environ(_env)
12811 return
12812
12813 try:
12814 k, v = arg.split('=')
12815 k = k.strip()
12816 v = v.strip()
12817
12818 except ValueError:
12819 self.printer(STR_BAD_ARGUMENT)
12820 return
12821
12822 _env = [(_k, _v) for (_k, _v) in env if _k != k]
12823 _env.append((k, v))
12824
12825 self.m_session_manager.set_environ(_env)
12826
12827
12828 def do_stop(self, arg):
12829 self.m_session_manager.stop_debuggee()
12830
12831
12832 def do_exit(self, arg):
12833 if arg != '':
12834 self.printer(STR_BAD_ARGUMENT)
12835 return
12836
12837 if self.m_session_manager.get_state() != STATE_DETACHED:
12838 try:
12839 self.do_stop('')
12840
12841 except (socket.error, CConnectionException):
12842 self.m_session_manager.report_exception(*sys.exc_info())
12843 except CException:
12844 self.m_session_manager.report_exception(*sys.exc_info())
12845 except:
12846 self.m_session_manager.report_exception(*sys.exc_info())
12847 print_debug_exception(True)
12848
12849 _print('', self.m_stdout)
12850
12851 return True
12852
12853 do_EOF = do_exit
12854
12855
12856 def do_copyright(self, arg):
12857 self.print_notice(COPYRIGHT_NOTICE)
12858
12859
12860 def do_license(self, arg):
12861 self.print_notice(LICENSE_NOTICE + COPY_OF_THE_GPL_LICENSE)
12862
12863
12864 def do_credits(self, arg):
12865 self.print_notice(CREDITS_NOTICE)
12866
12867
12868 def do_help(self, arg):
12869 cmd.Cmd.do_help(self, arg)
12870
12871 if arg == '':
12872 help_notice = """Security:
12873 ----------------
12874
12875 password - Get or set the channel password.
12876 remote - Get or set "allow connections from remote machines" mode.
12877
12878 Session Control:
12879 -----------------
12880
12881 env - Display or set the environment setting for new sessions.
12882 host - Display or change host.
12883 attach - Display scripts or attach to a script on host.
12884 detach - Detach from script.
12885 launch - Start a script and attach to it.
12886 restart - Restart a script.
12887 stop - Shutdown the debugged script.
12888 exit - Exit from debugger.
12889
12890 Debuggee Control:
12891 -----------------
12892
12893 break - Request an immediate break.
12894 step - Continue to the next execution line.
12895 next - Continue to the next execution line in the current frame.
12896 return - Continue until the debugger is about to return from the frame.
12897 jump - Jump to a line in the current scope.
12898 go - Continue execution.
12899
12900 Breakpoints Control:
12901 --------------------
12902
12903 bp - Set a break point.
12904 bd - Disable a breakpoint.
12905 be - Enable a breakpoint.
12906 bc - Clear (delete) a breakpoint.
12907 bl - List all breakpoints.
12908 load - Load session breakpoints.
12909 save - save session breakpoints.
12910
12911 Misc:
12912 -----
12913
12914 thread - Display threads or switch to a particular thread.
12915 list - List source code.
12916 stack - Display stack trace.
12917 up - Go up one frame in stack.
12918 down - Go down one frame in stack.
12919 encoding - Set the source encoding used by exec and eval commands.
12920 eval - Evaluate expression in the context of the current frame.
12921 exec - Execute suite in the context of the current frame.
12922 analyze - Toggle analyze last exception mode.
12923 trap - Get or set "trap unhandled exceptions" mode.
12924 fork - Get or set fork handling mode.
12925 synchro - Get or set synchronicity mode.
12926
12927 License:
12928 ----------------
12929
12930 copyright - Print copyright notice.
12931 license - Print license.
12932 credits - Print credits information.
12933
12934
12935 type help <topic> for futher information."""
12936
12937 self.print_notice(help_notice)
12938
12939
12940 def help_copyright(self):
12941 _print("""copyright
12942
12943 Print copyright notice.""", self.m_stdout)
12944
12945
12946 def help_license(self):
12947 _print("""license
12948
12949 Print license.""", self.m_stdout)
12950
12951
12952 def help_credits(self):
12953 _print("""credits
12954
12955 Print credits information.""", self.m_stdout)
12956
12957
12958 def help_help(self):
12959 _print("""help <cmd>
12960
12961 Print help for command <cmd>.
12962 On the other hand I guess that you already know that, don't you?""", self.m_stdout)
12963
12964
12965 def help_analyze(self):
12966 _print("""analyze
12967
12968 (shorthand - a)
12969
12970 Toggle analyze last exception mode.
12971
12972 The following changes to the debugger behavior apply in analyze mode:
12973 The debugger prompt changes to 'Analyze>'.
12974 'go', 'step', 'next', and 'return' are not allowed.
12975 'thread' does not allow to change the thread focus.
12976 'stack' allows no arguments.
12977 'list' does not accept the '*' (all threads) argument
12978 'stack', 'list', 'eval', 'exec', 'up', and 'down' operate on the thrown
12979 exception.""", self.m_stdout)
12980
12981 help_a = help_analyze
12982
12983
12984 def help_password(self):
12985 _print("""password <password>
12986
12987 Get or set the channel password.
12988
12989 Communication between the console and the debuggee is always authenticated and
12990 optionally encrypted. The password (A secret known to the console and the
12991 debuggee alone) governs both security methods. The password is never
12992 communicated between the two components on the communication channel.
12993
12994 A password is always required since unsecured communication between the
12995 console and the debuggee might expose your machine to attacks.""", self.m_stdout)
12996
12997
12998 def help_remote(self):
12999 _print("""remote [True | False]
13000
13001 Get or set "allow connections from remote machines" mode.
13002
13003 When set to False:
13004 Newly launched debuggees will listen on localhost only. In this mode, debugger
13005 consoles on remote machines will NOT BE able to see or attach to the debuggee.
13006
13007 When set to True:
13008 Newly launched debuggees will listen on INADDR_ANY. In this mode, debugger
13009 consoles on remote machines will BE able to see and attach to the debuggee.""", self.m_stdout)
13010
13011
13012 def help_trap(self):
13013 _print("""trap [True | False]
13014
13015 Get or set "trap unhandled exceptions" mode.
13016
13017 When set to False:
13018 Debuggee will ignore unhandled exceptions.
13019
13020 When set to True:
13021 Debuggee will pause on unhandled exceptions for inspection.""", self.m_stdout)
13022
13023
13024 def help_synchro(self):
13025 _print("""synchro [True | False]
13026
13027 Get or set the synchronicity mode.
13028
13029 Traditional Python debuggers that use the inspected thread
13030 (usually the main thread) to query or modify the script
13031 name-space have to wait until the script hits a break-point.
13032 Synchronicity allows the debugger to query and modify the
13033 script name-space even if its threads are still running or
13034 blocked in C library code by using special worker threads.
13035 In some rare cases querying or modifying data in
13036 synchronicity can crash the script. For example in some
13037 Linux builds of wxPython querying the state of wx objects
13038 from a thread other than the GUI thread can crash the
13039 script. If this happens or if you want to restrict these
13040 operations to the inspected thread, turn synchronicity off.
13041
13042 Default is True.""", self.m_stdout)
13043
13044
13045 def help_fork(self):
13046 _print("""fork [parent | child] [manual | auto]
13047
13048 Get or set fork handling mode.
13049
13050 Without arguments returns the current mode.
13051
13052 When 'parent' is specified the debugger will continue to debug the original
13053 parent process after a fork.
13054
13055 When 'child' is specified the debugger will switch to debug the forked
13056 child process after a fork.
13057
13058 When 'manual' is specified the debugger will pause before doing a fork.
13059
13060 When 'auto' is specified the debugger will go through the fork without
13061 pausing and will make the forking decision based on the parent/child
13062 setting.
13063
13064 WARNING:
13065 On some Posix OS such as FreeBSD, Stepping into the child fork
13066 can result in termination of the child process since the debugger
13067 uses threading for its operation and on these systems threading and
13068 forking can conflict.
13069 """, self.m_stdout)
13070
13071
13072 def help_stop(self):
13073 _print("""stop
13074
13075 Shutdown the debugged script.""", self.m_stdout)
13076
13077
13078 def help_launch(self):
13079 _print("""launch [-k] <script_name> [<script_args>]
13080
13081 Start script <script_name> and attach to it.
13082
13083 -k Don't change the current working directory. By default the working
13084 directory of the launched script is set to its folder.""", self.m_stdout)
13085
13086
13087 def help_restart(self):
13088 _print("""restart
13089
13090 Restart a script with same arguments from last launch.""", self.m_stdout)
13091
13092
13093
13094 def help_attach(self):
13095 _print("""attach [<arg>]
13096
13097 Without an argument, 'attach' prints the scripts available for debugging
13098 on the selected host. To select a host use the 'host' command. A script is
13099 considered available for debugging only if it is using the rpdb2 module or
13100 has been executed by the debugger.
13101 If the debugger is already attached to a script, a special character will
13102 mark that script in the list.
13103
13104 When <arg> is an integer the debugger will try to attach to a script with
13105 that pid.
13106 When <arg> is a string the debugger will try to attach to a script
13107 with that name in the list.""", self.m_stdout)
13108
13109
13110 def help_detach(self):
13111 _print("""detach
13112
13113 Detach from the script the debugger is currently attached to. The detached
13114 script will continue execution.""", self.m_stdout)
13115
13116
13117 def help_break(self):
13118 _print("""break
13119
13120 (shorthand - b)
13121
13122 Request script to break (pause execution as if it hit a breakpoint).
13123 The 'break' command returns immdeiately but the break is only established
13124 when an active thread submits to the debugger control. If a thread is
13125 doing a system call or executing C code, this will happen only when
13126 it returns to do python code.""", self.m_stdout)
13127
13128 help_b = help_break
13129
13130
13131 def help_bp(self):
13132 _print("""bp [<filename>':'] (<line> | <scope>) [',' <expr>]
13133
13134 Set a breakpoint.
13135
13136 <filename> - either the filename or the module name.
13137 <line> - is the line number to assign the breakpoint to.
13138 <scope> - is a "fully qualified" function name. That is, not only the
13139 function name but also the class name (in case of a member
13140 function), such as MyClass.MyMemberFunction.
13141 <expr> - condition to evaluate in the context of the frame. If it
13142 evaluates to 'True' the break point will break into the debugger.
13143
13144 In case the <filemame> is omitted, the current file is assumed. In this case
13145 the debuggee has to be waiting at break point.
13146
13147 Examples:
13148
13149 bp test_file.py:20
13150 bp test_file.py:MyClass.Foo
13151 bp 304
13152
13153 Type 'help break' for more information on breakpoints and threads.""", self.m_stdout)
13154
13155
13156 def help_be(self):
13157 _print("""be (<id_list> | '*')
13158
13159 Enable breakpoints.
13160
13161 <id_list> - is a space delimited list of at least one breakpoint id
13162 '*' - Enable all breakpoints.""", self.m_stdout)
13163
13164
13165 def help_bd(self):
13166 _print("""bd (<id_list> | '*')
13167
13168 Disable breakpoints.
13169
13170 <id_list> - is a space delimited list of at least one breakpoint id
13171 '*' - disable all breakpoints.""", self.m_stdout)
13172
13173
13174 def help_bc(self):
13175 _print("""bc (<id_list> | '*')
13176
13177 Clear (delete) breakpoints.
13178
13179 <id_list> - is a space delimited list of at least one breakpoint id
13180 '*' - clear all breakpoints.""", self.m_stdout)
13181
13182
13183 def help_bl(self):
13184 _print("""bl
13185
13186 List all breakpoints, sorted by their id.""", self.m_stdout)
13187
13188
13189 def help_load(self):
13190 _print("""load [<filename>]
13191
13192 Load breakpoints.
13193
13194 <filename> - optional breakpoints filename. The filename should not include
13195 a file extension.""", self.m_stdout)
13196
13197
13198 def help_save(self):
13199 _print("""save [<filename>]
13200
13201 save breakpoints.
13202
13203 <filename> - optional breakpoints filename. The filename should not include
13204 a file extension.""", self.m_stdout)
13205
13206
13207 def help_go(self):
13208 _print("""go [[<filename>':'] (<line> | <scope>)]
13209
13210 (shorthand - g)
13211
13212 Resume execution of a script that is waiting at break point.
13213 If an argument is present, continue execution until that argument is reached.
13214
13215 <filename> - is the file name which basically is the script's name without
13216 the '.py' extension.
13217 <line> - is the line number to assign the breakpoint to.
13218 <scope> - is a "fully qualified" function name. That is, not only the
13219 function name but also the class name (in case of a member
13220 function), such as MyClass.MyMemberFunction.""", self.m_stdout)
13221
13222 help_g = help_go
13223
13224
13225 def help_exit(self):
13226 _print("""exit
13227
13228 Exit the debugger. If the debugger is attached to a script, the debugger
13229 will attempt to detach from the script first.""", self.m_stdout)
13230
13231 help_EOF = help_exit
13232
13233
13234 def help_host(self):
13235 _print("""host [<arg>]
13236
13237 Without an argument, 'host' prints the current selected host.
13238 With an argument <arg>, 'host' attempts to resolve <arg> to a known ip
13239 address or a domain name. If it is successful, that host will become the
13240 selected host.
13241 The default selected host is the local host.
13242 Subsequent 'attach' commands will be done on the selected host.
13243
13244 Type 'help attach' for more information.""", self.m_stdout)
13245
13246 def help_stack(self):
13247 _print("""stack [<tid> | '*']
13248
13249 (shorthand - k)
13250
13251 Without an argument, 'stack' prints the stack trace of the focused thread.
13252 If the thread is waiting at break point a special character will mark the
13253 focused frame.
13254
13255 <tid> - print the stack of thread <tid>
13256 '*' - print the stacks of all active threads.
13257
13258 Type 'help break' for more information on breakpoints and threads.
13259 Type 'help up' or 'help down' for more information on focused frames.""", self.m_stdout)
13260
13261 help_k = help_stack
13262
13263
13264 def help_list(self):
13265 _print("""list [<file_name>:][<line_no> | '+' | '-' | '^' | '*'] [',' <nlines>]
13266
13267 (shorthand - l)
13268
13269 Without an argument, 'list' prints the source lines around the current line
13270 of the focused thread in the focused frame. A special character sequence will
13271 mark the current line according to the event:
13272
13273 'C>' - call - A function is called.
13274 'L>' - line - The interpreter is about to execute a new line of code.
13275 'R>' - return - A function is about to return.
13276 'E>' - exception - An exception has been thrown.
13277 '*>' - running - The thread is running.
13278
13279 If a breakpoint is assigned to a line, that line will be marked with:
13280
13281 'B' - if the breakpoint is enabled
13282 'D' - if the breakpoint is disabled
13283
13284 <file_name> - List source from filename
13285 <line_no> - Print the source lines around that line number in the same file
13286 of the current line.
13287 '+' - Print the next lines in the file.
13288 '-' - Print the previous lines in the file.
13289 '^' - Print the entire file.
13290 '*' - Print the source lines for each of the active threads.
13291 <nlines> - Print <nlines> of source
13292
13293 Type 'help break' for more information on breakpoints and threads.
13294 Type 'help up' or 'help down' for more information on focused frames.""", self.m_stdout)
13295
13296 help_l = help_list
13297
13298
13299 def help_thread(self):
13300 _print("""thread [<no> | <tid>]
13301
13302 (shorthand - t)
13303
13304 Without an argument, 'thread' prints the list of known active threads, with
13305 their corresponding state, which can be either 'running' or
13306 'waiting at break point'. A special character will mark the focused thread.
13307
13308 With an argument <tid>, 'thread' will attempt to set the debugger focus to
13309 the thread of that tid.
13310 With an argument <no>, 'thread' will attempt to set the debugger focus to
13311 the thread of that order in the thread list.
13312
13313 Type 'help break' for more information on breakpoints and threads.""", self.m_stdout)
13314
13315 help_t = help_thread
13316
13317
13318 def help_jump(self):
13319 _print("""jump <lineno>
13320
13321 (shorthand - j)
13322
13323 Jump to line <lineno> in the current scope.""", self.m_stdout)
13324
13325 help_j = help_jump
13326
13327
13328 def help_next(self):
13329 _print("""next
13330
13331 (shorthand - n)
13332
13333 Continue execution until the next line in the current function
13334 is reached or it returns.""", self.m_stdout)
13335
13336 help_n = help_next
13337
13338
13339 def help_step(self):
13340 _print("""step
13341
13342 (shorthand - s)
13343
13344 Execute the current line, stop at the first possible occasion
13345 (either in a function that is called or in the current function).""", self.m_stdout)
13346
13347 help_s = help_step
13348
13349
13350 def help_return(self):
13351 _print("""next
13352
13353 (shorthand - r)
13354
13355 Continue execution until the current function returns.""", self.m_stdout)
13356
13357 help_r = help_return
13358
13359
13360 def help_up(self):
13361 _print("""up
13362
13363 move the debugger focus one frame up the stack of the debugged thread
13364 (closer to the current, most recently executed frame). Evaluation of
13365 expressions or execution of statements will be done at the local and global
13366 name spaces of the focused frame.
13367
13368 Type 'help eval' for more information on evaluation of expressions.
13369 Type 'help exec' for more information on execution of statements.""", self.m_stdout)
13370
13371
13372 def help_down(self):
13373 _print("""down
13374
13375 move the debugger focus one frame down the stack of the debugged thread
13376 (closer to the current, most recently executed frame). Evaluation of
13377 expressions or execution of statements will be done at the local and global
13378 name spaces of the focused frame.
13379
13380 Type 'help eval' for more information on evaluation of expressions.
13381 Type 'help exec' for more information on execution of statements.""", self.m_stdout)
13382
13383
13384 def help_eval(self):
13385 _print("""eval <expr>
13386
13387 (shorthand - v)
13388
13389 Evaluate the python expression <expr> under the global and local name spaces
13390 of the currently focused frame.
13391
13392 Example:
13393 'eval locals()' - will display the dictionary of the local variables.
13394
13395 IMPORTANT: Any changes to the global name space will be discarded unless the
13396 focused stack frame is the top most frame.
13397
13398 Type 'help up' or 'help down' for more information on focused frames.""", self.m_stdout)
13399
13400 help_v = help_eval
13401
13402
13403 def help_exec(self):
13404 _print("""exec <stmt>
13405
13406 (shorthand - x)
13407
13408 Execute the python suite <stmt> under the global and local name spaces
13409 of the currently focused frame.
13410
13411 Example:
13412 'exec i += 1'
13413
13414 IMPORTANT: Any changes to the global name space will be discarded unless the
13415 focused stack frame is the top most frame.
13416
13417 Type 'help up' or 'help down' for more information on focused frames.""", self.m_stdout)
13418
13419 help_x = help_exec
13420
13421
13422 def help_encoding(self):
13423 _print("""encoding [<encoding> [, raw]]
13424
13425 Set the source encoding for the exec and eval commands.
13426
13427 Without an argument returns the current encoding.
13428
13429 The specified encoding can be either 'auto' or any encoding accepted
13430 by the codecs module. If 'auto' is specified, the source encoding of
13431 the active scope will be used, which is utf-8 by default.
13432
13433 The default encoding value is 'auto'.
13434
13435 If 'raw' is specified, strings returned by the eval command
13436 will represent non ASCII characters as an escape sequence.""", self.m_stdout)
13437
13438
13439 def help_env(self):
13440 _print("""env [-d key | key = value]
13441
13442 Set the environment variables mapping. This mapping is used
13443 when a new script is launched to modify its environment.
13444
13445 Example for a mapping on Windows:
13446 env Path = %Path%;c:\\mydir
13447
13448 Example for a mapping on Linux:
13449 env PATH = $PATH:~/mydir
13450
13451 To delete the mapping for PATH
13452 env -d PATH
13453
13454 Without an argument returns the current list of mappings.
13455
13456 Note that the mapping will be evaluated and used to modify
13457 the environment after the debugger engine at the debuggee
13458 has imported the modules it requires. The order in which the
13459 mappings will be evaluated and applied is:
13460 last set, last evaluated.""", self.m_stdout)
13461
13462
13463
13464 #
13465 # ---------------------------------------- Replacement Functions ------------------------------------
13466 #
13467
13468
13469
13470 def rpdb2_import_wrapper(*args, **kwargs):
13471 if len(args) > 0:
13472 name = args[0]
13473 elif 'name' in kwargs:
13474 name = kwargs['name']
13475 else:
13476 return g_import(*args, **kwargs)
13477
13478 if name in sys.modules:
13479 return g_import(*args, **kwargs)
13480
13481 #
13482 # rpdb2 avoids stepping through this
13483 # function (rpdb2_import_wrapper) to
13484 # prevent confusion when stepping into
13485 # an import statement.
13486 #
13487 m = g_import(*args, **kwargs)
13488
13489 if name != 'gtk':
13490 return m
13491
13492 try:
13493 m.gdk.threads_init()
13494 return m
13495 except:
13496 pass
13497
13498 try:
13499 m.threads_init()
13500 return m
13501 except:
13502 pass
13503
13504 return m
13505
13506
13507
13508 g_import = None
13509
13510 if __name__ == 'rpdb2' and g_builtins_module.__import__ != rpdb2_import_wrapper:
13511 g_import = g_builtins_module.__import__
13512 g_builtins_module.__import__ = rpdb2_import_wrapper
13513
13514
13515
13516 def __find_eval_exec_frame_in_stack():
13517 f = sys._getframe(0)
13518
13519 while f != None:
13520 filename = f.f_code.co_filename
13521 name = f.f_code.co_name
13522
13523 if DEBUGGER_FILENAME in filename and name in ['_evaluate', '_execute'] and 'redirect_exc_info' in f.f_locals:
13524 return f
13525
13526 f = f.f_back
13527
13528 return None
13529
13530
13531
13532 def __exc_info():
13533 f = __find_eval_exec_frame_in_stack()
13534 if f == None:
13535 return g_sys_exc_info()
13536
13537 try:
13538 frame_index = f.f_locals['frame_index']
13539 fException = f.f_locals['fException']
13540
13541 e = g_debugger.get_exception(frame_index, fException)
13542 exc_info = (e['type'], e['value'], e['traceback'])
13543
13544 return exc_info
13545
13546 except:
13547 return g_sys_exc_info()
13548
13549
13550
13551 g_sys_exc_info = None
13552
13553 if __name__ == 'rpdb2' and 'exc_info' in dir(sys) and sys.exc_info != __exc_info:
13554 g_sys_exc_info = sys.exc_info
13555 sys.exc_info = __exc_info
13556
13557
13558
13559 def __setrecursionlimit(rl):
13560 global g_recursionlimit
13561
13562 print_debug('rl = %d' % rl)
13563
13564 g_recursionlimit = max(rl, 64)
13565
13566 rl = g_recursionlimit
13567 if sys.version_info[:2] == (2, 6):
13568 rl *= 3
13569
13570 return g_sys_setrecursionlimit(rl + 64)
13571
13572
13573
13574 g_sys_setrecursionlimit = None
13575
13576 if __name__ == 'rpdb2' and 'setrecursionlimit' in dir(sys) and sys.setrecursionlimit != __setrecursionlimit:
13577 g_sys_setrecursionlimit = sys.setrecursionlimit
13578 sys.setrecursionlimit = __setrecursionlimit
13579 __setrecursionlimit(sys.getrecursionlimit())
13580
13581
13582
13583 def __find_debugger_frame():
13584 frame = None
13585
13586 f = sys._getframe(0)
13587
13588 while f != None:
13589 filename = f.f_code.co_filename
13590 name = f.f_code.co_name
13591
13592 if DEBUGGER_FILENAME in filename and (name.startswith('trace_dispatch') or name == 'profile'):
13593 frame = f
13594
13595 f = f.f_back
13596
13597 return frame
13598
13599
13600
13601 class CSignalHandler:
13602 def __del__(self):
13603 while len(g_signals_pending) != 0:
13604 (handler, signum, frameobj) = g_signals_pending.pop(0)
13605 print_debug('Handling pending signal: %s, %s' % (repr(signum), repr(frameobj)))
13606
13607 try:
13608 handler(signum, frameobj)
13609
13610 except:
13611 #
13612 # Can not raise from inside a destructor. Report that handler
13613 # exception will be ignored.
13614 #
13615 (t, v, tb) = sys.exc_info()
13616
13617 _t = safe_repr(t)
13618 if _t.startswith("<type '"):
13619 _t = _t.split("'")[1]
13620
13621 event = CEventSignalException(signum, '%s: %s' % (_t, safe_repr(v)))
13622 g_debugger.m_event_dispatcher.fire_event(event)
13623
13624
13625
13626 def signal_handler(signum, frameobj):
13627 frame = __find_debugger_frame()
13628 if frame == None:
13629 #
13630 # A debugger tracing frame was not found in the stack.
13631 # This means that the handler can be run without risk
13632 # for state corruption.
13633 #
13634 handler = signal.getsignal(signum)
13635 return handler(signum, frameobj)
13636
13637 if frame.f_code.co_name == 'profile' and frame.f_locals['event'] != 'return':
13638 #
13639 # signal was caught inside the profile hook but not while
13640 # doing some debugger stuff. Call the handler but in case
13641 # of exception schedule the debugger to re-enable the
13642 # profile hook.
13643 #
13644 try:
13645 handler = signal.getsignal(signum)
13646 return handler(signum, frameobj)
13647 except:
13648 ctx = g_debugger.get_ctx(thread.get_ident())
13649 ctx.set_tracers(fsignal_exception = True)
13650 raise
13651
13652 #
13653 # Set the handler to be run when the debugger is about
13654 # to return from the tracing code.
13655 #
13656
13657 print_debug('Intercepted signal: %s, %s' % (repr(signum), repr(frameobj)))
13658
13659 f = frameobj
13660 while f != None:
13661 if f == frame:
13662 frameobj = frame.f_back
13663 break
13664
13665 f = f.f_back
13666
13667 handler = signal.getsignal(signum)
13668 g_signals_pending.append((handler, signum, frameobj))
13669
13670 if not 'signal_handler' in frame.f_locals:
13671 frame.f_locals.update({'signal_handler': CSignalHandler()})
13672
13673 event = CEventSignalIntercepted(signum)
13674 g_debugger.m_event_dispatcher.fire_event(event)
13675
13676 if signum == signal.SIGINT and g_debugger.is_waiting_for_attach():
13677 g_debugger.set_request_go_timer(0)
13678
13679
13680
13681 def __getsignal(signum):
13682 handler = g_signal_handlers.get(signum, g_signal_getsignal(signum))
13683 return handler
13684
13685
13686
13687 g_signal_getsignal = None
13688
13689 if __name__ == 'rpdb2' and 'getsignal' in dir(signal) and signal.getsignal != __getsignal:
13690 g_signal_getsignal = signal.getsignal
13691 signal.getsignal = __getsignal
13692
13693
13694
13695 def __signal(signum, handler):
13696 old_handler = __getsignal(signum)
13697
13698 if handler in [signal.SIG_IGN, signal.SIG_DFL]:
13699 g_signal_signal(signum, handler)
13700 return old_handler
13701
13702 g_signal_signal(signum, signal_handler)
13703 g_signal_handlers[signum] = handler
13704
13705 return old_handler
13706
13707
13708
13709 g_signal_signal = None
13710
13711 if __name__ == 'rpdb2' and 'signal' in dir(signal) and signal.signal != __signal:
13712 g_signal_signal = signal.signal
13713 signal.signal = __signal
13714
13715
13716
13717 """
13718 def __setprofile(foo):
13719 global g_profile
13720
13721 print_debug('*** setprofile to %s' % repr(foo))
13722 traceback.print_stack(file = sys.__stderr__)
13723
13724 if thread_get_name(current_thread()) == 'MainThread':
13725 g_profile = foo
13726
13727 g_sys_setprofile(foo)
13728
13729
13730
13731 g_sys_setprofile = None
13732
13733 if __name__ == 'rpdb2' and sys.setprofile != __setprofile:
13734 g_sys_setprofile = sys.setprofile
13735 sys.setprofile = __setprofile
13736 """
13737
13738
13739
13740 def __fork():
13741 global g_forktid
13742
13743 if not g_fignorefork:
13744 g_forktid = setbreak()
13745
13746 #
13747 # os.fork() has been called.
13748 #
13749 # You can choose if you would like the debugger
13750 # to continue with the parent or child fork with
13751 # the 'fork' console command.
13752 #
13753 # For example: 'fork child' or 'fork parent'
13754 # Type: 'help fork' for more information.
13755 #
13756 # WARNING:
13757 # On some Posix OS such as FreeBSD,
13758 # Stepping into the child fork can result in
13759 # termination of the child process.
13760 #
13761 # *** RPDB2 SAYS: Read the entire comment! ***
13762 #
13763 return g_os_fork()
13764
13765
13766
13767 g_os_fork = None
13768
13769 if __name__ == 'rpdb2' and 'fork' in dir(os) and os.fork != __fork:
13770 g_os_fork = os.fork
13771 os.fork = __fork
13772
13773
13774
13775 def __exit(n):
13776 global g_fos_exit
13777
13778 if type(n) == int:
13779 g_fos_exit = (setbreak() != None)
13780
13781 #
13782 # os._exit(n) has been called.
13783 #
13784 # Stepping on from this point will result
13785 # in program termination.
13786 #
13787 return g_os_exit(n)
13788
13789
13790
13791 g_os_exit = None
13792
13793 if __name__ == 'rpdb2' and '_exit' in dir(os) and os._exit != __exit:
13794 g_os_exit = os._exit
13795 os._exit = __exit
13796
13797
13798
13799 def __close(fd):
13800 global g_fos_exit
13801
13802 try:
13803 if fd == g_server.m_server.socket._sock.fileno():
13804 g_fos_exit = (setbreak() != None)
13805 except:
13806 pass
13807
13808 #
13809 # os.close(fd) has been called by the debugged script to close
13810 # the debugger communication channel.
13811 #
13812 # This can normally happen if it is trying to spawn a new process
13813 # in its place.
13814 #
13815 # Stepping on from this point will result in termination of the
13816 # debugging session.
13817 #
13818 return g_os_close(fd)
13819
13820
13821
13822 g_os_close = None
13823
13824 if __name__ == 'rpdb2' and 'close' in dir(os) and os.close != __close:
13825 g_os_close = os.close
13826 os.close = __close
13827
13828
13829
13830 def __dup2(fd, fd2):
13831 global g_fos_exit
13832
13833 try:
13834 if fd2 == g_server.m_server.socket._sock.fileno():
13835 g_fos_exit = (setbreak() != None)
13836 except:
13837 pass
13838
13839 #
13840 # os.dup2(fd, fd2) has been called by the debugged script to close
13841 # the debugger communication channel.
13842 #
13843 # This can normally happen if it is trying to spawn a new process
13844 # in its place.
13845 #
13846 # Stepping on from this point will result in termination of the
13847 # debugging session.
13848 #
13849 return g_os_dup2(fd, fd2)
13850
13851
13852
13853 g_os_dup2 = None
13854
13855 if __name__ == 'rpdb2' and 'dup2' in dir(os) and os.dup2 != __dup2:
13856 g_os_dup2 = os.dup2
13857 os.dup2 = __dup2
13858
13859
13860
13861 def __execv(path, args):
13862 global g_exectid
13863
13864 if os.path.isfile(path) and not g_fignorefork:
13865 g_exectid = setbreak()
13866
13867 #
13868 # os.execv() has been called.
13869 #
13870 # Stepping on from this point will result
13871 # in termination of the debug session if
13872 # the exec operation completes successfully.
13873 #
13874 return g_os_execv(path, args)
13875
13876
13877
13878 g_os_execv = None
13879
13880 if __name__ == 'rpdb2' and 'execv' in dir(os) and os.execv != __execv:
13881 g_os_execv = os.execv
13882 os.execv = __execv
13883
13884
13885
13886 def __execve(path, args, env):
13887 global g_exectid
13888
13889 if os.path.isfile(path) and not g_fignorefork:
13890 g_exectid = setbreak()
13891
13892 #
13893 # os.execve() has been called.
13894 #
13895 # Stepping on from this point will result
13896 # in termination of the debug session if
13897 # the exec operation completes successfully.
13898 #
13899 return g_os_execve(path, args, env)
13900
13901
13902
13903 g_os_execve = None
13904
13905 if __name__ == 'rpdb2' and 'execve' in dir(os) and os.execve != __execve:
13906 g_os_execve = os.execve
13907 os.execve = __execve
13908
13909
13910
13911 def __excepthook(type, value, traceback, next_excepthook, index):
13912 if index + 1 < len(g_excepthooks):
13913 return next_excepthook(type, value, traceback)
13914
13915 if traceback.tb_frame.f_back == None:
13916 return next_excepthook(type, value, traceback)
13917
13918 if not g_debugger.m_ftrap:
13919 return next_excepthook(type, value, traceback)
13920
13921 settrace()
13922 ctx = g_debugger.get_ctx(thread.get_ident())
13923 ctx.m_fUnhandledException = True
13924 setbreak()
13925
13926 #
13927 # Debuggee breaks (pauses) here
13928 # on unhandled exceptions.
13929 # Use analyze mode for post mortem.
13930 # type 'help analyze' for more information.
13931 #
13932 return next_excepthook(type, value, traceback)
13933
13934
13935
13936 g_excepthooks = []
13937
13938 g_excepthook = None
13939
13940 #
13941 # Set the debugger hook for unhandled exceptions. It only kicks in on
13942 # unhandled exceptions that are declared unhandled in the middle of the
13943 # stack as in wxPython. Normally unhandled exceptions are trapped at the
13944 # last stack frame by another mechanism.
13945 #
13946 # This mechaism is designed to work even if the excepthook is over-written.
13947 # by the debugged script.
13948 #
13949 def set_excepthook():
13950 global g_excepthook
13951
13952 if len(g_excepthooks) >= 4:
13953 #
13954 # Give up. We have been over-written 4 times already.
13955 #
13956 return
13957
13958 next_excepthook = sys.excepthook
13959 index = len(g_excepthooks)
13960
13961 eh = lambda type, value, traceback: __excepthook(type, value, traceback, next_excepthook, index)
13962
13963 g_excepthooks.append(eh)
13964 g_excepthook = eh
13965 sys.excepthook = eh
13966
13967
13968
13969 def __function_wrapper(function, args, kwargs):
13970 __settrace(depth = 1)
13971
13972 #
13973 # Debuggee breaks (pauses) here
13974 # on unhandled exceptions.
13975 # Use analyze mode for post mortem.
13976 # type 'help analyze' for more information.
13977 #
13978 return function(*args, **kwargs)
13979
13980
13981
13982 def __start_new_thread(function, args, kwargs = {}):
13983 return g_thread_start_new_thread(__function_wrapper, (function, args, kwargs))
13984
13985
13986
13987 g_thread_start_new_thread = None
13988
13989 if __name__ == 'rpdb2' and 'start_new_thread' in dir(thread) and thread.start_new_thread != __start_new_thread:
13990 g_thread_start_new_thread = thread.start_new_thread
13991 thread.start_new_thread = __start_new_thread
13992
13993
13994
13995 #
13996 # ---------------------------------------- main ------------------------------------
13997 #
13998
13999
14000
14001 def __settrace(depth = 2):
14002 if g_debugger is None:
14003 return
14004
14005 f = sys._getframe(depth)
14006 g_debugger.settrace(f, f_break_on_init = False)
14007
14008
14009
14010 def __setbreak(depth = 2):
14011 if g_debugger is None:
14012 return
14013
14014 f = sys._getframe(depth)
14015 g_debugger.setbreak(f)
14016
14017 return thread.get_ident()
14018
14019
14020
14021 def __set_temp_breakpoint(path, scopename, lineno):
14022 return g_debugger.m_bp_manager.set_temp_breakpoint(path, scopename, lineno)
14023
14024
14025
14026 def _atexit(fabort = False):
14027 if g_fignore_atexit:
14028 return
14029
14030 print_debug("Entered _atexit() in pid %d" % _getpid())
14031
14032 if g_debugger is None:
14033 return
14034
14035 if not fabort:
14036 g_debugger.stoptrace()
14037
14038 g_debugger.send_event_exit()
14039
14040 time.sleep(1.0)
14041
14042 g_server.shutdown()
14043 g_debugger.shutdown()
14044
14045 if not fabort:
14046 return
14047
14048 if hasattr(os, 'kill') and hasattr(signal, 'SIGKILL'):
14049 os.kill(os.getpid(), signal.SIGKILL)
14050 else:
14051 os.abort()
14052
14053
14054
14055 def my_pickle_import(*args, **kwargs):
14056 name = ''
14057
14058 if len(args) > 0:
14059 name = args[0]
14060
14061 if 'name' in kwargs:
14062 name = kwargs['name']
14063
14064 if name == 'rpdb2':
14065 return
14066
14067 return __import__(*args, **kwargs)
14068
14069
14070
14071 #
14072 # MOD
14073 #
14074 def workaround_import_deadlock():
14075 if is_py3k() and hasattr(pickle, '_Pickler'):
14076 pickle.Pickler = pickle._Pickler
14077
14078 xmlrpclib.loads(XML_DATA)
14079 s = as_bytes("(S'hello'\np0\nS'world'\np1\ntp2\n.")
14080 #s = as_bytes('(S\'\\xb3\\x95\\xf9\\x1d\\x105c\\xc6\\xe2t\\x9a\\xa5_`\\xa59\'\np0\nS"(I0\\nI1\\nS\'5657827\'\\np0\\n(S\'server_info\'\\np1\\n(tI0\\ntp2\\ntp3\\n."\np1\ntp2\n.0000000')
14081 pickle.loads(s)
14082 pickle.__import__ = my_pickle_import
14083
14084
14085
14086 def __start_embedded_debugger(_rpdb2_pwd, fAllowUnencrypted, fAllowRemote, timeout, source_provider, fDebug, depth):
14087 global g_server
14088 global g_debugger
14089 global g_fDebug
14090 global g_initial_cwd
14091 global g_source_provider_aux
14092
14093 _rpdb2_pwd = as_unicode(_rpdb2_pwd)
14094
14095 try:
14096 g_server_lock.acquire()
14097
14098 if g_debugger is not None and timeout == 0:
14099 f = sys._getframe(depth)
14100 g_debugger.settrace(f, f_break_on_init = False)
14101 return
14102
14103 if g_debugger is not None:
14104 f = sys._getframe(depth)
14105 g_debugger.record_client_heartbeat(0, True, False)
14106 g_debugger.setbreak(f)
14107 return
14108
14109 if not is_valid_pwd(_rpdb2_pwd):
14110 raise BadArgument(STR_PASSWORD_BAD)
14111
14112 g_fDebug = fDebug
14113 g_source_provider_aux = source_provider
14114
14115 workaround_import_deadlock()
14116
14117 if (not fAllowUnencrypted) and not is_encryption_supported():
14118 raise EncryptionNotSupported
14119
14120 f = sys._getframe(depth)
14121 filename = calc_frame_path(f)
14122
14123 #
14124 # This is an attempt to address the Python problem of recording only
14125 # relative paths in __file__ members of modules in the following case.
14126 #
14127 if sys.path[0] == '':
14128 try:
14129 g_initial_cwd = [getcwd(), getcwdu()]
14130
14131 except UnicodeDecodeError:
14132 #
14133 # This exception can be raised in py3k (alpha) on nt.
14134 #
14135 g_initial_cwd = [getcwdu()]
14136
14137
14138 atexit.register(_atexit)
14139
14140 g_debugger = CDebuggerEngine(fembedded = True)
14141
14142 g_server = CDebuggeeServer(filename, g_debugger, _rpdb2_pwd, fAllowUnencrypted, fAllowRemote)
14143 g_server.start()
14144
14145 if timeout == 0:
14146 g_debugger.settrace(f, f_break_on_init = False)
14147 return
14148
14149 g_debugger.settrace(f, timeout = timeout)
14150
14151 finally:
14152 g_server_lock.release()
14153
14154
14155
14156 def StartServer(args, fchdir, _rpdb2_pwd, fAllowUnencrypted, fAllowRemote, rid):
14157 assert(is_unicode(_rpdb2_pwd))
14158
14159 global g_server
14160 global g_debugger
14161 global g_module_main
14162
14163 try:
14164 ExpandedFilename = FindFile(args[0])
14165 _path = g_found_unicode_files.get(ExpandedFilename, ExpandedFilename)
14166
14167 if fchdir:
14168 os.chdir(os.path.dirname(_path))
14169
14170 if ExpandedFilename in g_found_unicode_files:
14171 prefix = os.path.join(getcwdu(), '')
14172 _path = _path.replace(winlower(prefix), '')
14173
14174 except IOError:
14175 _print('File ' + args[0] + ' not found.')
14176 return
14177
14178 print_debug('Starting server with: %s' % ExpandedFilename)
14179
14180 workaround_import_deadlock()
14181
14182 #
14183 # Replace the rpdb2.py directory with the script directory in
14184 # the search path
14185 #
14186
14187 spe = ExpandedFilename
14188 if os.path.islink(ExpandedFilename):
14189 spe = os.path.realpath(ExpandedFilename)
14190
14191 sys.path[0] = os.path.dirname(spe)
14192
14193 encoding = detect_locale()
14194 argv = [as_string(arg, encoding) for arg in args]
14195 sys.argv = argv
14196
14197 atexit.register(_atexit)
14198
14199 g_debugger = CDebuggerEngine()
14200
14201 g_server = CDebuggeeServer(ExpandedFilename, g_debugger, _rpdb2_pwd, fAllowUnencrypted, fAllowRemote, rid)
14202 g_server.start()
14203
14204 try:
14205 g_debugger.m_bp_manager.set_temp_breakpoint(ExpandedFilename, '', 1, fhard = True)
14206 except:
14207 pass
14208
14209 f = sys._getframe(0)
14210 g_debugger.settrace(f, f_break_on_init = False, builtins_hack = ExpandedFilename)
14211
14212 g_module_main = -1
14213 del sys.modules['__main__']
14214
14215 #
14216 # An exception in this line occurs if
14217 # there is a syntax error in the debugged script or if
14218 # there was a problem loading the debugged script.
14219 #
14220 imp.load_source('__main__', _path)
14221
14222
14223
14224 def StartClient(command_line, fAttach, fchdir, _rpdb2_pwd, fAllowUnencrypted, fAllowRemote, host):
14225 assert(is_unicode(command_line))
14226 assert(_rpdb2_pwd == None or is_unicode(_rpdb2_pwd))
14227
14228 if (not fAllowUnencrypted) and not is_encryption_supported():
14229 _print(STR_ENCRYPTION_SUPPORT_ERROR)
14230 return 2
14231
14232 sm = CSessionManager(_rpdb2_pwd, fAllowUnencrypted, fAllowRemote, host)
14233 c = CConsole(sm)
14234 c.start()
14235
14236 time.sleep(1.0)
14237
14238 try:
14239 if fAttach:
14240 sm.attach(command_line)
14241 elif command_line != '':
14242 sm.launch(fchdir, command_line)
14243
14244 except (socket.error, CConnectionException):
14245 sm.report_exception(*sys.exc_info())
14246 except CException:
14247 sm.report_exception(*sys.exc_info())
14248 except:
14249 sm.report_exception(*sys.exc_info())
14250 print_debug_exception(True)
14251
14252 c.join()
14253 sm.shutdown()
14254
14255
14256
14257 def PrintUsage(fExtended = False):
14258 scriptName = os.path.basename(sys.argv[0])
14259 _print(""" %(rpdb)s [options] [<script-name> [<script-args>...]]
14260
14261 %(rpdb)s uses the client-server model where the debugger UI/console is
14262 the client and the debugged script is the server (also called debuggee).
14263 The client and the server are separate processes and communicate over
14264 sockets.
14265
14266 Example: The following command starts the debugger UI/console and then
14267 launches and attaches to the specified script:
14268 %(rpdb)s some_script.py
14269
14270 Options can be a combination of the following:
14271 -h, --help Print this help.
14272 -d, --debuggee Start the debugged script (server) and wait for a
14273 debugger console (client) to attach.
14274 -a, --attach Start the debugger console (client) and attach to the
14275 specified debugged script (server).
14276 -o, --host= Specify host (or IP address) for remote connections.
14277 -r, --remote Allow debuggees to accept connections from remote machines.
14278 -e, --encrypt Force encrypted socket communication.
14279 -p, --pwd= Specify password for socket communication.
14280 This flag is available only on Windows. On other
14281 systems the password will be queried interactively
14282 if it is needed.
14283 -s, --screen Use the Unix screen utility when starting the debuggee.
14284 Note that the debugger should be started as follows:
14285 screen rpdb2 -s [options] [<script-name> [<script-args>...]]
14286 -c, --chdir Change the working directory to that of the launched
14287 script.
14288 -v, --version Print version information.
14289 --debug Debug prints.
14290
14291 Note that each option is available in short form (example -e) and in a
14292 long form (example --encrypt).
14293
14294 Options that end with '=' accept an argument that should follow without
14295 a space. For example to specify 192.168.0.10 as host use the following
14296 option:
14297
14298 long form: --host=192.168.0.10
14299 short form: -o192.168.0.10
14300 """ % {"rpdb": scriptName})
14301
14302 if not fExtended:
14303 return
14304
14305 _print(__doc__)
14306
14307
14308
14309 def main(StartClient_func = StartClient, version = RPDB_TITLE):
14310 global g_fScreen
14311 global g_fDebug
14312 global g_fFirewallTest
14313
14314 create_rpdb_settings_folder()
14315
14316 encoding = detect_locale()
14317 argv = [as_unicode(arg, encoding) for arg in sys.argv]
14318
14319 try:
14320 options, _rpdb2_args = getopt.getopt(
14321 argv[1:],
14322 'hdao:rtep:scv',
14323 ['help', 'debugee', 'debuggee', 'attach', 'host=', 'remote', 'plaintext', 'encrypt', 'pwd=', 'rid=', 'screen', 'chdir', 'base64=', 'nofwtest', 'version', 'debug']
14324 )
14325
14326 except getopt.GetoptError:
14327 PrintUsage()
14328 return 2
14329
14330 fWrap = False
14331 fAttach = False
14332 fSpawn = False
14333 fStart = False
14334
14335 encoded_path = None
14336 secret = None
14337 host = None
14338 _rpdb2_pwd = None
14339 fchdir = False
14340 fAllowRemote = False
14341 fAllowUnencrypted = True
14342
14343 for o, a in options:
14344 if o in ['-h', '--help']:
14345 PrintUsage()
14346 return 0
14347 if o in ['-v', '--version']:
14348 _print(version)
14349 return 0
14350 if o in ['--debug']:
14351 g_fDebug = True
14352 if o in ['-d', '--debugee', '--debuggee']:
14353 fWrap = True
14354 if o in ['-a', '--attach']:
14355 fAttach = True
14356 if o in ['-o', '--host']:
14357 host = a
14358 if o in ['-r', '--remote']:
14359 fAllowRemote = True
14360 if o in ['-t', '--plaintext']:
14361 fAllowUnencrypted = True
14362 if o in ['-e', '--encrypt']:
14363 fAllowUnencrypted = False
14364 if o in ['-p', '--pwd']:
14365 _rpdb2_pwd = a
14366 if o in ['--rid']:
14367 secret = a
14368 if o in ['-s', '--screen']:
14369 g_fScreen = True
14370 if o in ['-c', '--chdir']:
14371 fchdir = True
14372 if o in ['--base64']:
14373 encoded_path = a
14374 if o in ['--nofwtest']:
14375 g_fFirewallTest = False
14376
14377 arg = None
14378 argv = None
14379 options = None
14380 o = None
14381 a = None
14382
14383 if (_rpdb2_pwd is not None) and (os.name != 'nt'):
14384 _print(STR_PASSWORD_NOT_SUPPORTED)
14385 return 2
14386
14387 if _rpdb2_pwd is not None and not is_valid_pwd(_rpdb2_pwd):
14388 _print(STR_PASSWORD_BAD)
14389 return 2
14390
14391 if fWrap and (len(_rpdb2_args) == 0):
14392 _print("--debuggee option requires a script name with optional <script-arg> arguments")
14393 return 2
14394
14395 if fWrap and fAttach:
14396 _print("--debuggee and --attach can not be used together.")
14397 return 2
14398
14399 if fAttach and (len(_rpdb2_args) == 0):
14400 _print("--attach option requires a script name to attach to.")
14401 return 2
14402
14403 if fAttach and (len(_rpdb2_args) > 1):
14404 _print("--attach option does not accept <script-arg> arguments.")
14405 return 2
14406
14407 if fAttach and fAllowRemote:
14408 _print("--attach and --remote can not be used together.")
14409 return 2
14410
14411 if (host is not None) and not fAttach:
14412 _print("--host can only be used together with --attach.")
14413 return 2
14414
14415 if host is None:
14416 host = LOCALHOST
14417
14418 fSpawn = (len(_rpdb2_args) != 0) and (not fWrap) and (not fAttach)
14419 fStart = (len(_rpdb2_args) == 0)
14420
14421 if fchdir and not (fWrap or fSpawn):
14422 _print("-c can only be used when launching or starting a script from command line.")
14423 return 2
14424
14425 assert (fWrap + fAttach + fSpawn + fStart) == 1
14426
14427 if fAttach and (os.name == POSIX):
14428 try:
14429 int(_rpdb2_args[0])
14430
14431 _rpdb2_pwd = read_pwd_file(_rpdb2_args[0])
14432 delete_pwd_file(_rpdb2_args[0])
14433
14434 except (ValueError, IOError):
14435 pass
14436
14437 if (secret is not None) and (os.name == POSIX):
14438 _rpdb2_pwd = read_pwd_file(secret)
14439
14440 if (fWrap or fAttach) and not is_valid_pwd(_rpdb2_pwd):
14441 _print(STR_PASSWORD_MUST_BE_SET)
14442
14443 while True:
14444 _rpdb2_pwd = _raw_input(STR_PASSWORD_INPUT)
14445 if is_valid_pwd(_rpdb2_pwd):
14446 break
14447
14448 _print(STR_PASSWORD_BAD)
14449
14450 _print(STR_PASSWORD_CONFIRM)
14451
14452 if fWrap or fSpawn:
14453 try:
14454 if encoded_path != None:
14455 _b = as_bytes(encoded_path).translate(g_safe_base64_from)
14456 _u = base64.decodestring(_b)
14457 _path = as_unicode(_u)
14458 _rpdb2_args[0] = _path
14459
14460 FindFile(_rpdb2_args[0])
14461 except IOError:
14462 _print(STR_FILE_NOT_FOUND % _rpdb2_args[0])
14463 return 2
14464
14465 if fWrap:
14466 if (not fAllowUnencrypted) and not is_encryption_supported():
14467 _print(STR_ENCRYPTION_SUPPORT_ERROR)
14468 return 2
14469
14470 StartServer(_rpdb2_args, fchdir, _rpdb2_pwd, fAllowUnencrypted, fAllowRemote, secret)
14471
14472 elif fAttach:
14473 StartClient_func(_rpdb2_args[0], fAttach, fchdir, _rpdb2_pwd, fAllowUnencrypted, fAllowRemote, host)
14474
14475 elif fStart:
14476 StartClient_func(as_unicode(''), fAttach, fchdir, _rpdb2_pwd, fAllowUnencrypted, fAllowRemote, host)
14477
14478 else:
14479 if len(_rpdb2_args) == 0:
14480 _rpdb2_args = ''
14481 else:
14482 _rpdb2_args = '"' + '" "'.join(_rpdb2_args) + '"'
14483
14484 StartClient_func(_rpdb2_args, fAttach, fchdir, _rpdb2_pwd, fAllowUnencrypted, fAllowRemote, host)
14485
14486 return 0
14487
14488
14489
14490 if __name__ == '__main__':
14491 import rpdb2
14492
14493 #
14494 # Debuggee breaks (pauses) here
14495 # on unhandled exceptions.
14496 # Use analyze mode for post mortem.
14497 # type 'help analyze' for more information.
14498 #
14499 ret = rpdb2.main()
14500
14501 #
14502 # Debuggee breaks (pauses) here
14503 # before program termination.
14504 #
14505 # You can step to debug any exit handlers.
14506 #
14507 rpdb2.setbreak()
14508
14509
14510