-
Notifications
You must be signed in to change notification settings - Fork 24
/
rpdb2.py
7079 lines (4935 loc) · 190 KB
/
rpdb2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! /usr/bin/env python
"""
rpdb2.py
A remote Python debugger for CPython
Copyright (C) 2013-2017 Philippe Fremy
Copyright (C) 2005-2009 Nir Aides
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 2 of the License, or any later
version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02111-1307 USA
"""
import rpdb.globals
import rpdb.source_provider
from rpdb.breakinfo import CScopeBreakInfo, CalcValidLines
from rpdb.breakpoint import CBreakPointsManager
from rpdb.compat import sets, unicode, str8, base64_decodestring
from rpdb.const import *
from rpdb.const import POSIX, \
STR_STATE_BROKEN, STATE_BROKEN, STATE_RUNNING, STATE_ANALYZE, STATE_DETACHED, DEBUGGER_FILENAME, THREADING_FILENAME, \
DEFAULT_NUMBER_OF_LINES, DICT_KEY_TID, DICT_KEY_STACK, \
DICT_KEY_CODE_LIST, DICT_KEY_CURRENT_TID, DICT_KEY_BROKEN, DICT_KEY_BREAKPOINTS, DICT_KEY_LINES, DICT_KEY_FILENAME, \
DICT_KEY_FIRST_LINENO, DICT_KEY_FRAME_LINENO, DICT_KEY_EVENT, DICT_KEY_EXPR, DICT_KEY_NAME, DICT_KEY_REPR, \
DICT_KEY_IS_VALID, DICT_KEY_TYPE, DICT_KEY_SUBNODES, DICT_KEY_N_SUBNODES, DICT_KEY_ERROR, PYTHON_FILE_EXTENSION, PYTHONW_FILE_EXTENSION
from rpdb.crypto import is_encryption_supported
from rpdb.debugee import CDebuggeeServer
from rpdb.events import CEventNull, CEventEmbeddedSync, CEventClearSourceCache, CEventSignalIntercepted, \
CEventSignalException, CEventPsycoWarning, CEventConflictingModules, CEventSyncReceivers, \
CEventForkSwitch, CEventExecSwitch, CEventExit, CEventState, CEventSynchronicity, CEventBreakOnExit, CEventTrap, \
CEventForkMode, CEventUnhandledException, CEventNamespace, CEventNoThreads, CEventThreads, CEventThreadBroken, \
CEventStack, CEventStackDepth, CEventBreakpoint, CEventSync, breakpoint_copy, CEventDispatcher
from rpdb.exceptions import InvalidScopeName, CException, NotPythonSource, BadArgument, ThreadNotFound, \
NoThreads, ThreadDone, DebuggerNotBroken, InvalidFrame, NoExceptionFound, CConnectionException, NotAttached, EncryptionNotSupported
from rpdb.repr import clip_filename, safe_str, safe_repr, parse_type, repr_ltd, calc_suffix
from rpdb.rpc import CThread
from rpdb.session_manager import CSessionManager, is_valid_pwd, calc_pwd_file_path, delete_pwd_file
from rpdb.state_manager import CStateManager, lock_notify_all, g_alertable_waiters
from rpdb.utils import is_unicode, as_unicode, as_string, as_bytes, print_debug, print_debug_exception, winlower, _print, \
thread_is_alive, thread_get_name, current_thread, \
detect_encoding, detect_locale, get_python_executable, ENCODING_AUTO, ENCODING_RAW, ENCODING_RAW_I, safe_wait, \
my_os_path_join, FindFile, my_abspath, CalcScriptName, getcwd, getcwdu, g_safe_base64_from, _getpid
from rpdb.source_provider import MODULE_SCOPE, MODULE_SCOPE2, lines_cache, g_lines_cache, get_source_line, \
is_provider_filesystem, ENCODING_SOURCE
if '.' in __name__:
raise ImportError('rpdb2 must not be imported as part of a package!')
import threading
import traceback
import platform
import operator
import os.path
import pickle
import socket
import getopt
import atexit
import codecs
import signal
import time
import copy
import sys
import cmd
import imp
import os
if sys.version_info[:2] < (3,2):
print(STR_BAD_PYTHON_VERSION)
sys.exit(-1)
import xmlrpc.client as xmlrpclib
import _thread as thread
import numbers
#
#-------------------------------- Design Notes -------------------------------
#
"""
Design:
RPDB2 divides the world into two main parts: debugger and debuggee.
The debuggee is the script that needs to be debugged.
The debugger is another script that attaches to the debuggee for the
purpose of debugging.
Thus RPDB2 includes two main components: The debuggee-server that runs
in the debuggee and the session-manager that runs in the debugger.
The session manager and the debuggee-server communicate via XML-RPC.
The main classes are: CSessionManager and CDebuggeeServer
"""
#
#--------------------------------- Export functions ------------------------
#
def start_embedded_debugger(
_rpdb2_pwd,
fAllowUnencrypted = True,
fAllowRemote = False,
timeout =TIMEOUT_FIVE_MINUTES,
source_provider = None,
fDebug = False,
depth = 0
):
"""
Use 'start_embedded_debugger' to invoke the debugger engine in embedded
scripts. put the following line as the first line in your script:
import rpdb2; rpdb2.start_embedded_debugger(<some-password-string>)
This will cause the script to freeze until a debugger console attaches.
_rpdb2_pwd - The password that governs security of client/server communication.
fAllowUnencrypted - Allow unencrypted communications. Communication will
be authenticated but encrypted only if possible.
fAllowRemote - Allow debugger consoles from remote machines to connect.
timeout - Seconds to wait for attachment before giving up. Once the
timeout period expires, the debuggee will resume execution.
If None, never give up. If 0, do not wait at all.
source_provider - When script source is not available on file system it is
possible to specify a function that receives a "filename" and returns
its source. If filename specifies a file that does not fall under
the jurisdiction of this function it should raise IOError. If this
function is responsible for the specified file but the source is
not available it should raise IOError(SOURCE_NOT_AVAILABLE). You can
study the way source_provider_blender() works. Note that a misbehaving
function can break the debugger.
fDebug - debug output.
depth - Depth of the frame in which the debugger should be started. This
defaults to '0' so the top of stack will be in the code where
start_embedded_debugger is called.
IMPORTNAT SECURITY NOTE:
USING A HARDCODED PASSWORD MAY BE UNSECURE SINCE ANYONE WITH READ
PERMISSION TO THE SCRIPT WILL BE ABLE TO READ THE PASSWORD AND CONNECT TO
THE DEBUGGER AND DO WHATEVER THEY WISH VIA THE 'EXEC' DEBUGGER COMMAND.
It is safer to use: start_embedded_debugger_interactive_password()
"""
return __start_embedded_debugger(
_rpdb2_pwd,
fAllowUnencrypted,
fAllowRemote,
timeout,
source_provider,
fDebug,
depth + 2
)
def start_embedded_debugger_interactive_password(
fAllowUnencrypted = True,
fAllowRemote = False,
timeout =TIMEOUT_FIVE_MINUTES,
source_provider = None,
fDebug = False,
stdin = sys.stdin,
stdout = sys.stdout,
depth = 0
):
if rpdb.globals.g_server is not None:
return
while True:
if stdout is not None:
stdout.write('Please type password:')
_rpdb2_pwd = stdin.readline().rstrip('\n')
_rpdb2_pwd = as_unicode(_rpdb2_pwd, detect_encoding(stdin), fstrict = True)
try:
return __start_embedded_debugger(
_rpdb2_pwd,
fAllowUnencrypted,
fAllowRemote,
timeout,
source_provider,
fDebug,
depth + 2
)
except BadArgument:
stdout.write(STR_PASSWORD_BAD)
def settrace():
"""
Trace threads that were created with thread.start_new_thread()
To trace, call this function from the thread target function.
NOTE: The main thread and any threads created with the threading module
are automatically traced, and there is no need to invoke this function
for them.
Note: This call does not pause the script.
"""
return __settrace()
def setbreak(depth = 0):
"""
Pause the script for inspection at next script statement.
"""
return __setbreak(depth + 2)
def set_temp_breakpoint(path, scopename = '', lineno = 1):
"""
Set a temporary breakpoint in a file. path must be an absolute path.
scopename can either be an empty string or a fully qualified scope name
(For example u'g_debugger.m_bp_manager.set_temp_breakpoint'). lineno is
either relative to file start or to scope start.
To set a temporary breakpoint to hit when a file is first
imported or exec-uted call set_temp_breakpoint(path)
This function may throw a varaiety of exceptions.
"""
path = as_unicode(path, fstrict = True)
scopename = as_unicode(scopename, fstrict = True)
return __set_temp_breakpoint(path, scopename, lineno)
#
#----------------------------------- Interfaces ------------------------------
#
class CConsole:
"""
Interface to a debugger console.
"""
def __init__(
self,
session_manager,
stdin = None,
stdout = None,
fSplit = False
):
"""
Constructor of CConsole
session_manager - session manager object.
stdin, stdout - redirection for IO.
fsplit - Set flag to True when Input and Ouput belong to different
panes. For example take a look at Winpdb.
"""
self.m_ci = CConsoleInternal(
session_manager,
stdin,
stdout,
fSplit
)
def start(self):
return self.m_ci.start()
def join(self):
"""
Wait until the console ends.
"""
return self.m_ci.join()
def set_filename(self, filename):
"""
Set current filename for the console. The current filename can change
from outside the console when the console is embeded in other
components, for example take a look at Winpdb.
"""
filename = as_unicode(filename)
return self.m_ci.set_filename(filename)
def complete(self, text, state):
"""
Return the next possible completion for 'text'.
If a command has not been entered, then complete against command list.
Otherwise try to call complete_<command> to get list of completions.
"""
text = as_unicode(text)
return self.m_ci.complete(text, state)
def printer(self, text):
text = as_unicode(text)
return self.m_ci.printer(text)
#
# ---------------------------- Exceptions ----------------------------------
#
#
#----------------- unicode handling for compatibility with py3k ----------------
#
def is_py3k():
return sys.version_info[0] >= 3
#
#----------------------- Infinite List of Globals ---------------------------
#
#
# According to PEP-8: "Use 4 spaces per indentation level."
#
FORK_CHILD = 'child'
FORK_PARENT = 'parent'
FORK_MANUAL = 'manual'
FORK_AUTO = 'auto'
ENCRYPTION_ENABLED = 'encrypted'
ENCRYPTION_DISABLED = 'plain-text'
STATE_ENABLED = 'enabled'
STATE_DISABLED = 'disabled'
BP_FILENAME_SEP = ':'
BP_EVAL_SEP = ','
RPDB_EXEC_INFO = as_unicode('rpdb_exception_info')
MODE_ON = 'ON'
MODE_OFF = 'OFF'
MAX_EVALUATE_LENGTH = 256 * 1024
MAX_NAMESPACE_ITEMS = 1024
MAX_SORTABLE_LENGTH = 256 * 1024
REPR_ID_LENGTH = 4096
MAX_NAMESPACE_WARNING = {
DICT_KEY_EXPR: STR_MAX_NAMESPACE_WARNING_TITLE,
DICT_KEY_NAME: STR_MAX_NAMESPACE_WARNING_TITLE,
DICT_KEY_REPR: STR_MAX_NAMESPACE_WARNING_MSG,
DICT_KEY_IS_VALID: False,
DICT_KEY_TYPE: STR_MAX_NAMESPACE_WARNING_TYPE,
DICT_KEY_N_SUBNODES: 0
}
MAX_EVENT_LIST_LENGTH = 1000
CONFLICTING_MODULES = ['psyco', 'pdb', 'bdb', 'doctest']
XML_DATA = """<?xml version='1.0'?>
<methodCall>
<methodName>dispatcher_method</methodName>
<params>
<param>
<value><string>%s</string></value>
</param>
</params>
</methodCall>""" % RPDB_COMPATIBILITY_VERSION
ERROR_NO_ATTRIBUTE = 'Error: No attribute.'
g_debugger = None
#
# These globals are related to handling the os.fork() os._exit() and exec
# pattern.
#
g_forkpid = None
g_forktid = None
g_fignorefork = False
g_exectid = None
g_execpid = None
g_fos_exit = False
#
# To hold a reference to __main__ to prevent its release if an unhandled
# exception is raised.
#
g_module_main = None
g_found_conflicting_modules = []
g_fignore_atexit = False
g_frames_path = {}
g_signal_handlers = {}
g_signals_pending = []
#g_profile = None
g_fbreakonexit = False
#
# ---------------------------- General Utils ------------------------------
#
def parse_console_launch( arg ):
'''Split a the console command launch into chdir option, interprter option and real commandline
Returns: (fchdir, intrepreter, arg)
'''
(fchdir, interpreter) = (True, get_python_executable())
if arg == '':
return (fchdir, interpreter, arg)
idx = 0
while idx < len(arg):
if arg[:2] == '-k':
fchdir = False
arg = arg[2:].strip()
elif arg[:2] == '-i':
arg = arg[2:].strip()
if arg[0] in ('"', "'"):
st = 1
end = arg.find(arg[0],1 )
interpreter = '"%s"' % arg[st:end]
else:
st = 0
end = arg.find(' ', 1 )
interpreter = arg[st:end]
arg = arg[end+1:].strip()
else:
# no more arguments for us
break
return (fchdir, interpreter, arg)
def job_wrapper(event, foo, *args, **kwargs):
try:
#print_debug('Thread %d doing job %s' % (thread.get_ident(), foo.__name__))
foo(*args, **kwargs)
finally:
event.set()
def send_job(tid, timeout, foo, *args, **kwargs):
#
# Attempt to send job to thread tid.
# Will throw KeyError if thread tid is not available for jobs.
#
(lock, jobs) = g_alertable_waiters[tid]
event = threading.Event()
f = lambda: job_wrapper(event, foo, *args, **kwargs)
jobs.append(f)
try:
lock.acquire()
lock_notify_all(lock)
finally:
lock.release()
safe_wait(event, timeout)
def event_is_set(event):
return event.is_set()
# TODO: adjust
def _raw_input(s):
return input(s)
def calc_frame_path(frame):
globals_filename = frame.f_globals.get('__file__', None)
filename = frame.f_code.co_filename
if filename.startswith('<'):
if globals_filename == None:
return filename
else:
filename = CalcScriptName(os.path.basename(globals_filename))
if filename in g_frames_path:
return g_frames_path[filename]
if globals_filename != None:
dirname = os.path.dirname(globals_filename)
basename = os.path.basename(filename)
path = my_os_path_join(dirname, basename)
if os.path.isabs(path):
abspath = my_abspath(path)
lowered = winlower(abspath)
g_frames_path[filename] = lowered
return lowered
try:
abspath = FindFile(path, fModules = True)
lowered = winlower(abspath)
g_frames_path[filename] = lowered
return lowered
except IOError:
pass
if os.path.isabs(filename):
abspath = my_abspath(filename)
lowered = winlower(abspath)
g_frames_path[filename] = lowered
return lowered
try:
abspath = FindFile(filename, fModules = True)
lowered = winlower(abspath)
g_frames_path[filename] = lowered
return lowered
except IOError:
lowered = winlower(filename)
return lowered
#
# MOD
#
def IsPythonSourceFile(path):
if path.endswith(PYTHON_FILE_EXTENSION):
return True
if path.endswith(PYTHONW_FILE_EXTENSION):
return True
path = rpdb.globals.g_found_unicode_files.get(path, path)
for lineno in range(1, 10):
line = get_source_line(path, lineno)
if line.startswith('#!') and 'python' in line:
return True
# In doubt, return True
# in the past, we would try to parse the file successfully but
# this is too complicated in Python 3
def get_file_encoding(filename):
(lines, encoding, ffilesystem) = lines_cache(filename)
return encoding
def calc_prefix(_str, n):
"""
Return an n charaters prefix of the argument string of the form
'prefix...'.
"""
if len(_str) <= n:
return _str
return _str[: (n - 3)] + '...'
def create_rpdb_settings_folder():
"""
Create the settings folder on Posix systems:
'~/.rpdb2_settings' with mode 700.
"""
if os.name != POSIX:
return
home = os.path.expanduser('~')
rsf = os.path.join(home, RPDB_SETTINGS_FOLDER)
if not os.path.exists(rsf):
os.mkdir(rsf, int('0700', 8))
pwds = os.path.join(home, RPDB_PWD_FOLDER)
if not os.path.exists(pwds):
os.mkdir(pwds, int('0700', 8))
bpl = os.path.join(home, RPDB_BPL_FOLDER)
if not os.path.exists(bpl):
os.mkdir(bpl, int('0700', 8))
def read_pwd_file(rid):
"""
Read password from password file for Posix systems.
"""
assert(os.name == POSIX)
path = calc_pwd_file_path(rid)
p = open(path, 'r')
_rpdb2_pwd = p.read()
p.close()
_rpdb2_pwd = as_unicode(_rpdb2_pwd, fstrict = True)
return _rpdb2_pwd
def IsFilteredAttribute(a):
if not (a.startswith('__') and a.endswith('__')):
return False
if a in ['__class__', '__bases__', '__file__', '__doc__', '__name__', '__all__', '__builtins__']:
return False
return True
def IsFilteredAttribute2(r, a):
try:
o = getattr(r, a)
r = parse_type(type(o))
if 'function' in r or 'method' in r or r == 'type':
return True
return False
except:
return False
def CalcFilteredDir(r, filter_level):
d = dir(r)
if 'finfo' in d and parse_type(type(r)) == 'mp_request':
#
# Workaround mod_python segfault in type(req.finfo) by
# removing this attribute from the namespace viewer.
#
d.remove('finfo')
if filter_level == 0:
return d
fd = [a for a in d if not IsFilteredAttribute(a)]
return fd
def CalcIdentity(r, filter_level):
if filter_level == 0:
return r
if not hasattr(r, 'im_func'):
return r
return r.im_func
def getattr_nothrow(o, a):
try:
return getattr(o, a)
except AttributeError:
return ERROR_NO_ATTRIBUTE
except:
print_debug_exception()
return ERROR_NO_ATTRIBUTE
def calc_attribute_list(r, filter_level):
d = CalcFilteredDir(r, filter_level)
rs = set(d)
c = getattr_nothrow(r, '__class__')
if not c is ERROR_NO_ATTRIBUTE:
d = CalcFilteredDir(c, False)
cs = set(d)
s = rs & cs
for e in s:
o1 = getattr_nothrow(r, e)
o2 = getattr_nothrow(c, e)
if o1 is ERROR_NO_ATTRIBUTE or CalcIdentity(o1, filter_level) is CalcIdentity(o2, filter_level):
rs.discard(e)
try:
if filter_level == 1 and getattr(o1, '__self__') is getattr(o2, '__self__'):
rs.discard(e)
except:
pass
bl = getattr_nothrow(r, '__bases__')
if type(bl) == tuple:
for b in bl:
d = CalcFilteredDir(b, False)
bs = set(d)
s = rs & bs
for e in s:
o1 = getattr_nothrow(r, e)
o2 = getattr_nothrow(b, e)
if o1 is ERROR_NO_ATTRIBUTE or CalcIdentity(o1, filter_level) is CalcIdentity(o2, filter_level):
rs.discard(e)
try:
if filter_level == 1 and getattr(o1, '__self__') is getattr(o2, '__self__'):
rs.discard(e)
except:
pass
l = [a for a in rs if (filter_level < 2 or not IsFilteredAttribute2(r, a))]
if hasattr(r, '__class__') and not '__class__' in l:
l = ['__class__'] + l
if hasattr(r, '__bases__') and not '__bases__' in l:
l = ['__bases__'] + l
al = [a for a in l if hasattr(r, a)]
return al
class _RPDB2_FindRepr:
def __init__(self, o, repr_limit):
self.m_object = o
self.m_repr_limit = repr_limit
def __getitem__(self, key):
index = 0
for i in self.m_object:
if repr_ltd(i, self.m_repr_limit, encoding =ENCODING_RAW_I).replace('"', '"') == key:
if isinstance(self.m_object, dict):
return self.m_object[i]
return i
index += 1
if index > MAX_SORTABLE_LENGTH:
return None
def __setitem__(self, key, value):
if not isinstance(self.m_object, dict):
return
index = 0
for i in self.m_object:
if repr_ltd(i, self.m_repr_limit, encoding =ENCODING_RAW_I).replace('"', '"') == key:
self.m_object[i] = value
return
index += 1
if index > MAX_SORTABLE_LENGTH:
return
#
# Since on Python 3000 the comparison of different types raises exceptions and
# the __cmp__ method was removed, sorting of namespace items is based on
# lexicographic order except for numbers which are sorted normally and appear
# before all other types.
#
def sort(s):
s.sort(key = sort_key)
def sort_key(e):
if is_py3k() and isinstance(e, numbers.Number):
return (0, e)
if not is_py3k() and operator.isNumberType(e):
return (0, e)
return (1, repr_ltd(e, 256, encoding =ENCODING_RAW_I))
def recalc_sys_path(old_pythonpath):
opl = old_pythonpath.split(os.path.pathsep)
del sys.path[1: 1 + len(opl)]
pythonpath = os.environ.get('PYTHONPATH', '')
ppl = pythonpath.split(os.path.pathsep)
for i, p in enumerate(ppl):
abspath = my_abspath(p)
lowered = winlower(abspath)
sys.path.insert(1 + i, lowered)
#
# Similar to traceback.extract_stack() but fixes path with calc_frame_path()
#
def my_extract_stack(f):
'''
:param f: frame object
:return: similar to traceback.extract_stack()
- list of : (filename, line number, function name, text of source code)
'''
if f == None:
return []
try:
rpdb.globals.g_traceback_lock.acquire()
_s = traceback.extract_stack(f)
finally:
rpdb.globals.g_traceback_lock.release()
_s.reverse()
s = []
for (p, ln, fn, text) in _s:
path = as_unicode(calc_frame_path(f), sys.getfilesystemencoding())
if text == None:
text = ''
s.append((path, ln, as_unicode(fn), as_unicode(text)))
f = f.f_back
if f == None:
break
s.reverse()
return s
#
# Similar to traceback.extract_tb() but fixes path with calc_frame_path()
#
def my_extract_tb(tb):
'''
:param tb: traceback object
:return: similar to traceback.extract_tb()
- list of : (filename, line number, function name, text of source code)
'''
try:
rpdb.globals.g_traceback_lock.acquire()
_s = traceback.extract_tb(tb)
finally:
rpdb.globals.g_traceback_lock.release()
s = []
for (p, ln, fn, text) in _s:
path = as_unicode(calc_frame_path(tb.tb_frame), sys.getfilesystemencoding())
if text == None:
text = ''
s.append((path, ln, as_unicode(fn), as_unicode(text)))
tb = tb.tb_next
if tb == None:
break
return s
def get_traceback(frame, ctx):
if is_py3k():
if ctx.get_exc_info() != None:
return ctx.get_exc_info()[2]
else:
if frame.f_exc_traceback != None:
return frame.f_exc_traceback
locals = copy.copy(frame.f_locals)
if not 'traceback' in locals:
return None
tb = locals['traceback']
if dir(tb) == ['tb_frame', 'tb_lasti', 'tb_lineno', 'tb_next']:
return tb
#
# ---------------------------------- CThread ---------------------------------------
#
#
#--------------------------------------- Crypto ---------------------------------------
#
#
# --------------------------------- Events List --------------------------
#
#
# --------------------------------- Event Manager --------------------------
#
class CEventQueue:
"""
Add queue semantics above an event dispatcher.
Instead of firing event callbacks, new events are returned in a list
upon request.
Events are stored in a FIFO of size MAX_EVENT_LIST_LENGTH (defaults to 1000)
"""
def __init__(self, event_dispatcher, max_event_list_length = MAX_EVENT_LIST_LENGTH):
self.m_event_dispatcher = event_dispatcher
self.m_event_lock = threading.Condition()
self.m_max_event_list_length = max_event_list_length
self.m_event_list = []
self.m_event_index = 0
self.m_n_waiters = []
def shutdown(self):
self.m_event_dispatcher.remove_callback(self.event_handler)
def register_event_types(self, event_type_dict):
self.m_event_dispatcher.register_callback(self.event_handler, event_type_dict, fSingleUse = False)
def event_handler(self, event):
try:
self.m_event_lock.acquire()