summaryrefslogtreecommitdiff
path: root/python/helpers/pydev/pydevd.py
blob: 2077903ea09160820dbaecbdabdd5943bc74d0a7 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
#IMPORTANT: pydevd_constants must be the 1st thing defined because it'll keep a reference to the original sys._getframe
import traceback

from django_debug import DjangoLineBreakpoint
from pydevd_signature import SignatureFactory
from pydevd_frame import add_exception_to_frame
import pydev_imports
from pydevd_breakpoints import * #@UnusedWildImport
import fix_getpass
from pydevd_comm import  CMD_CHANGE_VARIABLE, \
                         CMD_EVALUATE_EXPRESSION, \
                         CMD_EXEC_EXPRESSION, \
                         CMD_GET_COMPLETIONS, \
                         CMD_GET_FRAME, \
                         CMD_GET_VARIABLE, \
                         CMD_LIST_THREADS, \
                         CMD_REMOVE_BREAK, \
                         CMD_RUN, \
                         CMD_SET_BREAK, \
                         CMD_SET_NEXT_STATEMENT,\
                         CMD_STEP_INTO, \
                         CMD_STEP_OVER, \
                         CMD_STEP_RETURN, \
                         CMD_THREAD_CREATE, \
                         CMD_THREAD_KILL, \
                         CMD_THREAD_RUN, \
                         CMD_THREAD_SUSPEND, \
                         CMD_RUN_TO_LINE, \
                         CMD_RELOAD_CODE, \
                         CMD_VERSION, \
                         CMD_CONSOLE_EXEC, \
                         CMD_ADD_EXCEPTION_BREAK, \
                         CMD_REMOVE_EXCEPTION_BREAK, \
                         CMD_LOAD_SOURCE, \
                         CMD_ADD_DJANGO_EXCEPTION_BREAK, \
                         CMD_REMOVE_DJANGO_EXCEPTION_BREAK, \
                         CMD_SMART_STEP_INTO,\
    InternalChangeVariable, \
                         InternalGetCompletions, \
                         InternalEvaluateExpression, \
                         InternalConsoleExec, \
                         InternalGetFrame, \
                         InternalGetVariable, \
                         InternalTerminateThread, \
                         InternalRunThread, \
                         InternalStepThread, \
                         NetCommand, \
                         NetCommandFactory, \
                         PyDBDaemonThread, \
                         _queue, \
                         ReaderThread, \
                         SetGlobalDebugger, \
                         WriterThread, \
                         PydevdFindThreadById, \
                         PydevdLog, \
                         StartClient, \
                         StartServer, \
                         InternalSetNextStatementThread, ReloadCodeCommand
from pydevd_file_utils import NormFileToServer, GetFilenameAndBase
import pydevd_file_utils
import pydevd_vars
import pydevd_vm_type
import pydevd_tracing
import pydevd_io
import pydev_monkey
from pydevd_additional_thread_info import PyDBAdditionalThreadInfo
from pydevd_custom_frames import CustomFramesContainer, CustomFramesContainerInit


if USE_LIB_COPY:
    import _pydev_time as time
    import _pydev_threading as threading
else:
    import time
    import threading

import os


threadingEnumerate = threading.enumerate
threadingCurrentThread = threading.currentThread


DONT_TRACE = {
              # commonly used things from the stdlib that we don't want to trace
              'threading.py':1,
              'Queue.py':1,
              'queue.py':1,
              'socket.py':1,
              'weakref.py':1,
              'linecache.py':1,
              'threading.py':1,

              #things from pydev that we don't want to trace
              'pydevd.py':1 ,
              'pydevd_additional_thread_info.py':1,
              'pydevd_custom_frames.py':1,
              'pydevd_comm.py':1,
              'pydevd_console.py':1 ,
              'pydevd_constants.py':1,
              'pydevd_exec.py':1,
              'pydevd_exec2.py':1,
              'pydevd_file_utils.py':1,
              'pydevd_frame.py':1,
              'pydevd_import_class.py':1 ,
              'pydevd_io.py':1 ,
              'pydevd_psyco_stub.py':1,
              'pydevd_reload.py':1 ,
              'pydevd_resolver.py':1 ,
              'pydevd_stackless.py':1 ,
              'pydevd_traceproperty.py':1,
              'pydevd_tracing.py':1 ,
              'pydevd_signature.py':1,
              'pydevd_utils.py':1,
              'pydevd_vars.py':1,
              'pydevd_vm_type.py':1,
              '_pydev_execfile.py':1,
              '_pydev_jython_execfile.py':1
            }

if IS_PY3K:
    # if we try to trace io.py it seems it can get halted (see http://bugs.python.org/issue4716)
    DONT_TRACE['io.py'] = 1

    # Don't trace common encodings too
    DONT_TRACE['cp1252.py'] = 1
    DONT_TRACE['utf_8.py'] = 1


connected = False
bufferStdOutToServer = False
bufferStdErrToServer = False
remote = False

from _pydev_filesystem_encoding import getfilesystemencoding
file_system_encoding = getfilesystemencoding()

def isThreadAlive(t):
    try:
        # If thread is not started yet we treat it as alive.
        # It is required to debug threads started by start_new_thread in Python 3.4
        if hasattr(t, '_is_stopped'):
            alive = not t._is_stopped
        else:
            alive = not t.__stopped
    except:
        alive = t.isAlive()
    return alive

#=======================================================================================================================
# PyDBCommandThread
#=======================================================================================================================
class PyDBCommandThread(PyDBDaemonThread):

    def __init__(self, pyDb):
        PyDBDaemonThread.__init__(self)
        self._py_db_command_thread_event = pyDb._py_db_command_thread_event
        self.pyDb = pyDb
        self.setName('pydevd.CommandThread')

    def OnRun(self):
        for i in range(1, 10):
            time.sleep(0.5) #this one will only start later on (because otherwise we may not have any non-daemon threads
            if self.killReceived:
                return

        if self.dontTraceMe:
            self.pyDb.SetTrace(None) # no debugging on this thread

        try:
            while not self.killReceived:
                try:
                    self.pyDb.processInternalCommands()
                except:
                    PydevdLog(0, 'Finishing debug communication...(2)')
                self._py_db_command_thread_event.clear()
                self._py_db_command_thread_event.wait(0.5)
        except:
            pydev_log.debug(sys.exc_info()[0])

            #only got this error in interpreter shutdown
            #PydevdLog(0, 'Finishing debug communication...(3)')


def killAllPydevThreads():
    threads = threadingEnumerate()
    for t in threads:
        if hasattr(t, 'doKillPydevThread'):
            t.doKillPydevThread()
    

#=======================================================================================================================
# PyDBCheckAliveThread
#=======================================================================================================================
class PyDBCheckAliveThread(PyDBDaemonThread):

    def __init__(self, pyDb):
        PyDBDaemonThread.__init__(self)
        self.pyDb = pyDb
        self.setDaemon(False)
        self.setName('pydevd.CheckAliveThread')

    def OnRun(self):
            if self.dontTraceMe:
                self.pyDb.SetTrace(None) # no debugging on this thread
            while not self.killReceived:
                if not self.pyDb.haveAliveThreads():
                    try:
                        pydev_log.debug("No alive threads, finishing debug session")
                        self.pyDb.FinishDebuggingSession()
                        killAllPydevThreads()
                    except:
                        traceback.print_exc()

                    self.killReceived = True
                    return

                time.sleep(0.3)

    def doKillPydevThread(self):
        pass

if USE_LIB_COPY:
    import _pydev_thread as thread
else:
    try:
        import thread
    except ImportError:
        import _thread as thread #Py3K changed it.

_original_start_new_thread = thread.start_new_thread

if getattr(thread, '_original_start_new_thread', None) is None:
    thread._original_start_new_thread = thread.start_new_thread

#=======================================================================================================================
# NewThreadStartup
#=======================================================================================================================
class NewThreadStartup:

    def __init__(self, original_func, args, kwargs):
        self.original_func = original_func
        self.args = args
        self.kwargs = kwargs

    def __call__(self):
        global_debugger = GetGlobalDebugger()
        global_debugger.SetTrace(global_debugger.trace_dispatch)
        self.original_func(*self.args, **self.kwargs)

thread.NewThreadStartup = NewThreadStartup

#=======================================================================================================================
# pydev_start_new_thread
#=======================================================================================================================
def _pydev_start_new_thread(function, args, kwargs={}):
    '''
    We need to replace the original thread.start_new_thread with this function so that threads started through
    it and not through the threading module are properly traced.
    '''
    if USE_LIB_COPY:
        import _pydev_thread as thread
    else:
        try:
            import thread
        except ImportError:
            import _thread as thread #Py3K changed it.

    return thread._original_start_new_thread(thread.NewThreadStartup(function, args, kwargs), ())

class PydevStartNewThread(object):
    def __get__(self, obj, type=None):
        return self

    def __call__(self, function, args, kwargs={}):
        return _pydev_start_new_thread(function, args, kwargs)

pydev_start_new_thread = PydevStartNewThread()


#=======================================================================================================================
# PyDB
#=======================================================================================================================
class PyDB:
    """ Main debugging class
    Lots of stuff going on here:

    PyDB starts two threads on startup that connect to remote debugger (RDB)
    The threads continuously read & write commands to RDB.
    PyDB communicates with these threads through command queues.
       Every RDB command is processed by calling processNetCommand.
       Every PyDB net command is sent to the net by posting NetCommand to WriterThread queue

       Some commands need to be executed on the right thread (suspend/resume & friends)
       These are placed on the internal command queue.
    """


    def __init__(self):
        SetGlobalDebugger(self)
        pydevd_tracing.ReplaceSysSetTraceFunc()
        self.reader = None
        self.writer = None
        self.quitting = None
        self.cmdFactory = NetCommandFactory()
        self._cmd_queue = {}  # the hash of Queues. Key is thread id, value is thread
        self.breakpoints = {}
        self.django_breakpoints = {}
        self.exception_set = {}
        self.always_exception_set = set()
        self.django_exception_break = {}
        self.readyToRun = False
        self._main_lock = threading.Lock()
        self._lock_running_thread_ids = threading.Lock()
        self._py_db_command_thread_event = threading.Event()
        CustomFramesContainer._py_db_command_thread_event = self._py_db_command_thread_event
        self._finishDebuggingSession = False
        self._terminationEventSent = False
        self.force_post_mortem_stop = 0
        self.signature_factory = None
        self.SetTrace = pydevd_tracing.SetTrace

        #this is a dict of thread ids pointing to thread ids. Whenever a command is passed to the java end that
        #acknowledges that a thread was created, the thread id should be passed here -- and if at some time we do not
        #find that thread alive anymore, we must remove it from this list and make the java side know that the thread
        #was killed.
        self._running_thread_ids = {}

    def haveAliveThreads(self):
        for t in threadingEnumerate():
            if not isinstance(t, PyDBDaemonThread) and isThreadAlive(t) and not t.isDaemon():
                return True

        return False

    def FinishDebuggingSession(self):
        self._finishDebuggingSession = True

    def acquire(self):
        if PyDBUseLocks:
            self.lock.acquire()
        return True

    def release(self):
        if PyDBUseLocks:
            self.lock.release()
        return True

    def initializeNetwork(self, sock):
        try:
            sock.settimeout(None)  # infinite, no timeouts from now on - jython does not have it
        except:
            pass
        self.writer = WriterThread(sock)
        self.reader = ReaderThread(sock)
        self.writer.start()
        self.reader.start()

        time.sleep(0.1)  # give threads time to start

    def connect(self, host, port):
        if host:
            s = StartClient(host, port)
        else:
            s = StartServer(port)

        self.initializeNetwork(s)


    def getInternalQueue(self, thread_id):
        """ returns internal command queue for a given thread.
        if new queue is created, notify the RDB about it """
        if thread_id.startswith('__frame__'):
            thread_id = thread_id[thread_id.rfind('|') + 1:]
        try:
            return self._cmd_queue[thread_id]
        except KeyError:
            return self._cmd_queue.setdefault(thread_id, _queue.Queue()) #@UndefinedVariable


    def postInternalCommand(self, int_cmd, thread_id):
        """ if thread_id is *, post to all """
        if thread_id == "*":
            threads = threadingEnumerate()
            for t in threads:
                thread_name = t.getName()
                if not thread_name.startswith('pydevd.') or thread_name == 'pydevd.CommandThread':
                    thread_id = GetThreadId(t)
                    queue = self.getInternalQueue(thread_id)
                    queue.put(int_cmd)

        else:
            queue = self.getInternalQueue(thread_id)
            queue.put(int_cmd)

    def checkOutputRedirect(self):
        global bufferStdOutToServer
        global bufferStdErrToServer

        if bufferStdOutToServer:
                initStdoutRedirect()
                self.checkOutput(sys.stdoutBuf, 1) #@UndefinedVariable

        if bufferStdErrToServer:
                initStderrRedirect()
                self.checkOutput(sys.stderrBuf, 2) #@UndefinedVariable

    def checkOutput(self, out, outCtx):
        '''Checks the output to see if we have to send some buffered output to the debug server

        @param out: sys.stdout or sys.stderr
        @param outCtx: the context indicating: 1=stdout and 2=stderr (to know the colors to write it)
        '''

        try:
            v = out.getvalue()

            if v:
                self.cmdFactory.makeIoMessage(v, outCtx, self)
        except:
            traceback.print_exc()


    def processInternalCommands(self):
        '''This function processes internal commands
        '''
        self._main_lock.acquire()
        try:

            self.checkOutputRedirect()

            curr_thread_id = GetThreadId(threadingCurrentThread())
            program_threads_alive = {}
            all_threads = threadingEnumerate()
            program_threads_dead = []
            self._lock_running_thread_ids.acquire()
            try:
                for t in all_threads:
                    thread_id = GetThreadId(t)

                    if not isinstance(t, PyDBDaemonThread) and isThreadAlive(t):
                        program_threads_alive[thread_id] = t

                        if not DictContains(self._running_thread_ids, thread_id):
                            if not hasattr(t, 'additionalInfo'):
                                # see http://sourceforge.net/tracker/index.php?func=detail&aid=1955428&group_id=85796&atid=577329
                                # Let's create the additional info right away!
                                t.additionalInfo = PyDBAdditionalThreadInfo()
                            self._running_thread_ids[thread_id] = t
                            self.writer.addCommand(self.cmdFactory.makeThreadCreatedMessage(t))


                        queue = self.getInternalQueue(thread_id)
                        cmdsToReadd = []  # some commands must be processed by the thread itself... if that's the case,
                                            # we will re-add the commands to the queue after executing.
                        try:
                            while True:
                                int_cmd = queue.get(False)
                                if int_cmd.canBeExecutedBy(curr_thread_id):
                                    PydevdLog(2, "processing internal command ", str(int_cmd))
                                    int_cmd.doIt(self)
                                else:
                                    PydevdLog(2, "NOT processing internal command ", str(int_cmd))
                                    cmdsToReadd.append(int_cmd)

                        except _queue.Empty: #@UndefinedVariable
                            for int_cmd in cmdsToReadd:
                                queue.put(int_cmd)
                            # this is how we exit


                thread_ids = list(self._running_thread_ids.keys())
                for tId in thread_ids:
                    if not DictContains(program_threads_alive, tId):
                        program_threads_dead.append(tId)
            finally:
                self._lock_running_thread_ids.release()

            for tId in program_threads_dead:
                try:
                    self.processThreadNotAlive(tId)
                except:
                    sys.stderr.write('Error iterating through %s (%s) - %s\n' % (
                        program_threads_alive, program_threads_alive.__class__, dir(program_threads_alive)))
                    raise


            if len(program_threads_alive) == 0:
                self.FinishDebuggingSession()
                for t in all_threads:
                    if hasattr(t, 'doKillPydevThread'):
                        t.doKillPydevThread()

        finally:
            self._main_lock.release()


    def setTracingForUntracedContexts(self, ignore_frame=None, overwrite_prev_trace=False):
        # Enable the tracing for existing threads (because there may be frames being executed that
        # are currently untraced).
        threads = threadingEnumerate()
        try:
            for t in threads:
                if not t.getName().startswith('pydevd.'):
                    # TODO: optimize so that we only actually add that tracing if it's in
                    # the new breakpoint context.
                    additionalInfo = None
                    try:
                        additionalInfo = t.additionalInfo
                    except AttributeError:
                        pass  # that's ok, no info currently set

                    if additionalInfo is not None:
                        for frame in additionalInfo.IterFrames():
                            if frame is not ignore_frame:
                                self.SetTraceForFrameAndParents(frame, overwrite_prev_trace=overwrite_prev_trace)
        finally:
            frame = None
            t = None
            threads = None
            additionalInfo = None


    def processNetCommand(self, cmd_id, seq, text):
        '''Processes a command received from the Java side

        @param cmd_id: the id of the command
        @param seq: the sequence of the command
        @param text: the text received in the command

        @note: this method is run as a big switch... after doing some tests, it's not clear whether changing it for
        a dict id --> function call will have better performance result. A simple test with xrange(10000000) showed
        that the gains from having a fast access to what should be executed are lost because of the function call in
        a way that if we had 10 elements in the switch the if..elif are better -- but growing the number of choices
        makes the solution with the dispatch look better -- so, if this gets more than 20-25 choices at some time,
        it may be worth refactoring it (actually, reordering the ifs so that the ones used mostly come before
        probably will give better performance).
        '''

        self._main_lock.acquire()
        try:
            try:
                cmd = None
                if cmd_id == CMD_RUN:
                    self.readyToRun = True

                elif cmd_id == CMD_VERSION:
                    # response is version number
                    local_version, pycharm_os = text.split('\t', 1)

                    pydevd_file_utils.set_pycharm_os(pycharm_os)

                    cmd = self.cmdFactory.makeVersionMessage(seq)

                elif cmd_id == CMD_LIST_THREADS:
                    # response is a list of threads
                    cmd = self.cmdFactory.makeListThreadsMessage(seq)

                elif cmd_id == CMD_THREAD_KILL:
                    int_cmd = InternalTerminateThread(text)
                    self.postInternalCommand(int_cmd, text)

                elif cmd_id == CMD_THREAD_SUSPEND:
                    # Yes, thread suspend is still done at this point, not through an internal command!
                    t = PydevdFindThreadById(text)
                    if t:
                        additionalInfo = None
                        try:
                            additionalInfo = t.additionalInfo
                        except AttributeError:
                            pass  # that's ok, no info currently set

                        if additionalInfo is not None:
                            for frame in additionalInfo.IterFrames():
                                self.SetTraceForFrameAndParents(frame)
                                del frame

                        self.setSuspend(t, CMD_THREAD_SUSPEND)
                    elif text.startswith('__frame__:'):
                        sys.stderr.write("Can't suspend tasklet: %s\n" % (text,))

                elif cmd_id == CMD_THREAD_RUN:
                    t = PydevdFindThreadById(text)
                    if t:
                        thread_id = GetThreadId(t)
                        int_cmd = InternalRunThread(thread_id)
                        self.postInternalCommand(int_cmd, thread_id)

                    elif text.startswith('__frame__:'):
                        sys.stderr.write("Can't make tasklet run: %s\n" % (text,))


                elif cmd_id == CMD_STEP_INTO or cmd_id == CMD_STEP_OVER or cmd_id == CMD_STEP_RETURN:
                    # we received some command to make a single step
                    t = PydevdFindThreadById(text)
                    if t:
                        thread_id = GetThreadId(t)
                        int_cmd = InternalStepThread(thread_id, cmd_id)
                        self.postInternalCommand(int_cmd, thread_id)

                    elif text.startswith('__frame__:'):
                        sys.stderr.write("Can't make tasklet step command: %s\n" % (text,))


                elif cmd_id == CMD_RUN_TO_LINE or cmd_id == CMD_SET_NEXT_STATEMENT or cmd_id == CMD_SMART_STEP_INTO:
                    # we received some command to make a single step
                    thread_id, line, func_name = text.split('\t', 2)
                    t = PydevdFindThreadById(thread_id)
                    if t:
                        int_cmd = InternalSetNextStatementThread(thread_id, cmd_id, line, func_name)
                        self.postInternalCommand(int_cmd, thread_id)
                    elif thread_id.startswith('__frame__:'):
                        sys.stderr.write("Can't set next statement in tasklet: %s\n" % (thread_id,))


                elif cmd_id == CMD_RELOAD_CODE:
                    # we received some command to make a reload of a module
                    module_name = text.strip()

                    thread_id = '*'  # Any thread

                    # Note: not going for the main thread because in this case it'd only do the load
                    # when we stopped on a breakpoint.
                    # for tid, t in self._running_thread_ids.items(): #Iterate in copy
                    #    thread_name = t.getName()
                    #
                    #    print thread_name, GetThreadId(t)
                    #    #Note: if possible, try to reload on the main thread
                    #    if thread_name == 'MainThread':
                    #        thread_id = tid

                    int_cmd = ReloadCodeCommand(module_name, thread_id)
                    self.postInternalCommand(int_cmd, thread_id)


                elif cmd_id == CMD_CHANGE_VARIABLE:
                    # the text is: thread\tstackframe\tFRAME|GLOBAL\tattribute_to_change\tvalue_to_change
                    try:
                        thread_id, frame_id, scope, attr_and_value = text.split('\t', 3)

                        tab_index = attr_and_value.rindex('\t')
                        attr = attr_and_value[0:tab_index].replace('\t', '.')
                        value = attr_and_value[tab_index + 1:]
                        int_cmd = InternalChangeVariable(seq, thread_id, frame_id, scope, attr, value)
                        self.postInternalCommand(int_cmd, thread_id)

                    except:
                        traceback.print_exc()

                elif cmd_id == CMD_GET_VARIABLE:
                    # we received some command to get a variable
                    # the text is: thread_id\tframe_id\tFRAME|GLOBAL\tattributes*
                    try:
                        thread_id, frame_id, scopeattrs = text.split('\t', 2)

                        if scopeattrs.find('\t') != -1:  # there are attributes beyond scope
                            scope, attrs = scopeattrs.split('\t', 1)
                        else:
                            scope, attrs = (scopeattrs, None)

                        int_cmd = InternalGetVariable(seq, thread_id, frame_id, scope, attrs)
                        self.postInternalCommand(int_cmd, thread_id)

                    except:
                        traceback.print_exc()

                elif cmd_id == CMD_GET_COMPLETIONS:
                    # we received some command to get a variable
                    # the text is: thread_id\tframe_id\tactivation token
                    try:
                        thread_id, frame_id, scope, act_tok = text.split('\t', 3)

                        int_cmd = InternalGetCompletions(seq, thread_id, frame_id, act_tok)
                        self.postInternalCommand(int_cmd, thread_id)

                    except:
                        traceback.print_exc()

                elif cmd_id == CMD_GET_FRAME:
                    thread_id, frame_id, scope = text.split('\t', 2)

                    int_cmd = InternalGetFrame(seq, thread_id, frame_id)
                    self.postInternalCommand(int_cmd, thread_id)

                elif cmd_id == CMD_SET_BREAK:
                    # func name: 'None': match anything. Empty: match global, specified: only method context.

                    # command to add some breakpoint.
                    # text is file\tline. Add to breakpoints dictionary
                    type, file, line, condition, expression = text.split('\t', 4)

                    if not IS_PY3K:  # In Python 3, the frame object will have unicode for the file, whereas on python 2 it has a byte-array encoded with the filesystem encoding.
                        file = file.encode(file_system_encoding)

                    if condition.startswith('**FUNC**'):
                        func_name, condition = condition.split('\t', 1)

                        # We must restore new lines and tabs as done in
                        # AbstractDebugTarget.breakpointAdded
                        condition = condition.replace("@_@NEW_LINE_CHAR@_@", '\n').\
                            replace("@_@TAB_CHAR@_@", '\t').strip()

                        func_name = func_name[8:]
                    else:
                        func_name = 'None'  # Match anything if not specified.


                    file = NormFileToServer(file)

                    if not pydevd_file_utils.exists(file):
                        sys.stderr.write('pydev debugger: warning: trying to add breakpoint'\
                            ' to file that does not exist: %s (will have no effect)\n' % (file,))
                        sys.stderr.flush()

                    line = int(line)

                    if len(condition) <= 0 or condition is None or condition == "None":
                        condition = None

                    if len(expression) <= 0 or expression is None or expression == "None":
                        expression = None

                    if type == 'python-line':
                        breakpoint = LineBreakpoint(type, True, condition, func_name, expression)
                        breakpoint.add(self.breakpoints, file, line, func_name)
                    elif type == 'django-line':
                        breakpoint = DjangoLineBreakpoint(type, file, line, True, condition, func_name, expression)
                        breakpoint.add(self.django_breakpoints, file, line, func_name)
                    else:
                        raise NameError(type)

                    self.setTracingForUntracedContexts()

                elif cmd_id == CMD_REMOVE_BREAK:
                    #command to remove some breakpoint
                    #text is file\tline. Remove from breakpoints dictionary
                    type, file, line = text.split('\t', 2)
                    file = NormFileToServer(file)
                    try:
                        line = int(line)
                    except ValueError:
                        pass

                    else:
                        found = False
                        try:
                            if type == 'django-line':
                                del self.django_breakpoints[file][line]
                            elif type == 'python-line':
                                del self.breakpoints[file][line] #remove the breakpoint in that line
                            else:
                                try:
                                    del self.django_breakpoints[file][line]
                                    found = True
                                except:
                                    pass
                                try:
                                    del self.breakpoints[file][line] #remove the breakpoint in that line
                                    found = True
                                except:
                                    pass

                            if DebugInfoHolder.DEBUG_TRACE_BREAKPOINTS > 0:
                                sys.stderr.write('Removed breakpoint:%s - %s\n' % (file, line))
                                sys.stderr.flush()
                        except KeyError:
                            found = False

                        if not found:
                            #ok, it's not there...
                            if DebugInfoHolder.DEBUG_TRACE_BREAKPOINTS > 0:
                                #Sometimes, when adding a breakpoint, it adds a remove command before (don't really know why)
                                sys.stderr.write("breakpoint not found: %s - %s\n" % (file, line))
                                sys.stderr.flush()

                elif cmd_id == CMD_EVALUATE_EXPRESSION or cmd_id == CMD_EXEC_EXPRESSION:
                    #command to evaluate the given expression
                    #text is: thread\tstackframe\tLOCAL\texpression
                    thread_id, frame_id, scope, expression, trim = text.split('\t', 4)
                    int_cmd = InternalEvaluateExpression(seq, thread_id, frame_id, expression,
                        cmd_id == CMD_EXEC_EXPRESSION, int(trim) == 1)
                    self.postInternalCommand(int_cmd, thread_id)

                elif cmd_id == CMD_CONSOLE_EXEC:
                    #command to exec expression in console, in case expression is only partially valid 'False' is returned
                    #text is: thread\tstackframe\tLOCAL\texpression

                    thread_id, frame_id, scope, expression = text.split('\t', 3)

                    int_cmd = InternalConsoleExec(seq, thread_id, frame_id, expression)
                    self.postInternalCommand(int_cmd, thread_id)

                elif cmd_id == CMD_ADD_EXCEPTION_BREAK:
                    exception, notify_always, notify_on_terminate = text.split('\t', 2)

                    eb = ExceptionBreakpoint(exception, notify_always, notify_on_terminate)

                    self.exception_set[exception] = eb

                    if eb.notify_on_terminate:
                        update_exception_hook(self)
                    if DebugInfoHolder.DEBUG_TRACE_BREAKPOINTS > 0:
                        pydev_log.error("Exceptions to hook on terminate: %s\n" % (self.exception_set,))

                    if eb.notify_always:
                        self.always_exception_set.add(exception)
                        if DebugInfoHolder.DEBUG_TRACE_BREAKPOINTS > 0:
                            pydev_log.error("Exceptions to hook always: %s\n" % (self.always_exception_set,))
                        self.setTracingForUntracedContexts()

                elif cmd_id == CMD_REMOVE_EXCEPTION_BREAK:
                    exception = text
                    try:
                        del self.exception_set[exception]
                        self.always_exception_set.remove(exception)
                    except:
                        pydev_log.debug("Error while removing exception %s"%sys.exc_info()[0]);
                    update_exception_hook(self)

                elif cmd_id == CMD_LOAD_SOURCE:
                    path = text
                    try:
                        f = open(path, 'r')
                        source = f.read()
                        self.cmdFactory.makeLoadSourceMessage(seq, source, self)
                    except:
                        return self.cmdFactory.makeErrorMessage(seq, pydevd_tracing.GetExceptionTracebackStr())

                elif cmd_id == CMD_ADD_DJANGO_EXCEPTION_BREAK:
                    exception = text

                    self.django_exception_break[exception] = True
                    self.setTracingForUntracedContexts()

                elif cmd_id == CMD_REMOVE_DJANGO_EXCEPTION_BREAK:
                    exception = text

                    try:
                        del self.django_exception_break[exception]
                    except :
                        pass

                else:
                    #I have no idea what this is all about
                    cmd = self.cmdFactory.makeErrorMessage(seq, "unexpected command " + str(cmd_id))

                if cmd is not None:
                    self.writer.addCommand(cmd)
                    del cmd

            except Exception:
                traceback.print_exc()
                cmd = self.cmdFactory.makeErrorMessage(seq,
                    "Unexpected exception in processNetCommand.\nInitial params: %s" % ((cmd_id, seq, text),))

                self.writer.addCommand(cmd)
        finally:
            self._main_lock.release()

    def processThreadNotAlive(self, threadId):
        """ if thread is not alive, cancel trace_dispatch processing """
        self._lock_running_thread_ids.acquire()
        try:
            thread = self._running_thread_ids.pop(threadId, None)
            if thread is None:
                return

            wasNotified = thread.additionalInfo.pydev_notify_kill
            if not wasNotified:
                thread.additionalInfo.pydev_notify_kill = True

        finally:
            self._lock_running_thread_ids.release()

        cmd = self.cmdFactory.makeThreadKilledMessage(threadId)
        self.writer.addCommand(cmd)


    def setSuspend(self, thread, stop_reason):
        thread.additionalInfo.suspend_type = PYTHON_SUSPEND
        thread.additionalInfo.pydev_state = STATE_SUSPEND
        thread.stop_reason = stop_reason


    def doWaitSuspend(self, thread, frame, event, arg): #@UnusedVariable
        """ busy waits until the thread state changes to RUN
        it expects thread's state as attributes of the thread.
        Upon running, processes any outstanding Stepping commands.
        """
        self.processInternalCommands()

        message = getattr(thread.additionalInfo, "message", None)

        cmd = self.cmdFactory.makeThreadSuspendMessage(GetThreadId(thread), frame, thread.stop_reason, message)
        self.writer.addCommand(cmd)

        CustomFramesContainer.custom_frames_lock.acquire()
        try:
            from_this_thread = []

            for frame_id, custom_frame in CustomFramesContainer.custom_frames.items():
                if custom_frame.thread_id == thread.ident:
                    # print >> sys.stderr, 'Frame created: ', frame_id
                    self.writer.addCommand(self.cmdFactory.makeCustomFrameCreatedMessage(frame_id, custom_frame.name))
                    self.writer.addCommand(self.cmdFactory.makeThreadSuspendMessage(frame_id, custom_frame.frame, CMD_THREAD_SUSPEND, ""))

                from_this_thread.append(frame_id)

        finally:
            CustomFramesContainer.custom_frames_lock.release()



        info = thread.additionalInfo
        while info.pydev_state == STATE_SUSPEND and not self._finishDebuggingSession:
            self.processInternalCommands()
            time.sleep(0.01)

        # process any stepping instructions
        if info.pydev_step_cmd == CMD_STEP_INTO:
            info.pydev_step_stop = None
            info.pydev_smart_step_stop = None

        elif info.pydev_step_cmd == CMD_STEP_OVER:
            info.pydev_step_stop = frame
            info.pydev_smart_step_stop = None
            self.SetTraceForFrameAndParents(frame)

        elif info.pydev_step_cmd == CMD_SMART_STEP_INTO:
            self.SetTraceForFrameAndParents(frame)
            info.pydev_step_stop = None
            info.pydev_smart_step_stop = frame

        elif info.pydev_step_cmd == CMD_RUN_TO_LINE or info.pydev_step_cmd == CMD_SET_NEXT_STATEMENT :
            self.SetTraceForFrameAndParents(frame)

            if event == 'line' or event == 'exception':
                #If we're already in the correct context, we have to stop it now, because we can act only on
                #line events -- if a return was the next statement it wouldn't work (so, we have this code
                #repeated at pydevd_frame).
                stop = False
                curr_func_name = frame.f_code.co_name

                #global context is set with an empty name
                if curr_func_name in ('?', '<module>'):
                    curr_func_name = ''

                if curr_func_name == info.pydev_func_name:
                    line = info.pydev_next_line
                    if frame.f_lineno == line:
                        stop = True
                    else :
                        if frame.f_trace is None:
                            frame.f_trace = self.trace_dispatch
                        frame.f_lineno = line
                        frame.f_trace = None
                        stop = True
                if stop:
                    info.pydev_state = STATE_SUSPEND
                    self.doWaitSuspend(thread, frame, event, arg)
                    return


        elif info.pydev_step_cmd == CMD_STEP_RETURN:
            back_frame = frame.f_back
            if back_frame is not None:
                # steps back to the same frame (in a return call it will stop in the 'back frame' for the user)
                info.pydev_step_stop = frame
                self.SetTraceForFrameAndParents(frame)
            else:
                # No back frame?!? -- this happens in jython when we have some frame created from an awt event
                # (the previous frame would be the awt event, but this doesn't make part of 'jython', only 'java')
                # so, if we're doing a step return in this situation, it's the same as just making it run
                info.pydev_step_stop = None
                info.pydev_step_cmd = None
                info.pydev_state = STATE_RUN

        del frame
        cmd = self.cmdFactory.makeThreadRunMessage(GetThreadId(thread), info.pydev_step_cmd)
        self.writer.addCommand(cmd)

        CustomFramesContainer.custom_frames_lock.acquire()
        try:
            # The ones that remained on last_running must now be removed.
            for frame_id in from_this_thread:
                # print >> sys.stderr, 'Removing created frame: ', frame_id
                self.writer.addCommand(self.cmdFactory.makeThreadKilledMessage(frame_id))

        finally:
            CustomFramesContainer.custom_frames_lock.release()

    def handle_post_mortem_stop(self, additionalInfo, t):
        pydev_log.debug("We are stopping in post-mortem\n")
        self.force_post_mortem_stop -= 1
        frame, frames_byid = additionalInfo.pydev_force_stop_at_exception
        thread_id = GetThreadId(t)
        pydevd_vars.addAdditionalFrameById(thread_id, frames_byid)
        try:
            try:
                add_exception_to_frame(frame, additionalInfo.exception)
                self.setSuspend(t, CMD_ADD_EXCEPTION_BREAK)
                self.doWaitSuspend(t, frame, 'exception', None)
            except:
                pydev_log.error("We've got an error while stopping in post-mortem: %s\n"%sys.exc_info()[0])
        finally:
            additionalInfo.pydev_force_stop_at_exception = None
            pydevd_vars.removeAdditionalFrameById(thread_id)

    def trace_dispatch(self, frame, event, arg):
        ''' This is the callback used when we enter some context in the debugger.

        We also decorate the thread we are in with info about the debugging.
        The attributes added are:
            pydev_state
            pydev_step_stop
            pydev_step_cmd
            pydev_notify_kill
        '''
        try:
            if self._finishDebuggingSession and not self._terminationEventSent:
                #that was not working very well because jython gave some socket errors
                try:
                    threads = threadingEnumerate()
                    for t in threads:
                        if hasattr(t, 'doKillPydevThread'):
                            t.doKillPydevThread()
                except:
                    traceback.print_exc()
                self._terminationEventSent = True
                return None

            filename, base = GetFilenameAndBase(frame)

            is_file_to_ignore = DictContains(DONT_TRACE, base) #we don't want to debug threading or anything related to pydevd

            if is_file_to_ignore:
                return None

            #print('trace_dispatch', base, frame.f_lineno, event, frame.f_code.co_name)
            try:
                #this shouldn't give an exception, but it could happen... (python bug)
                #see http://mail.python.org/pipermail/python-bugs-list/2007-June/038796.html
                #and related bug: http://bugs.python.org/issue1733757
                t = threadingCurrentThread()
            except:
                frame.f_trace = self.trace_dispatch
                return self.trace_dispatch

            try:
                additionalInfo = t.additionalInfo
                if additionalInfo is None:
                    raise AttributeError()
            except:
                t.additionalInfo = PyDBAdditionalThreadInfo()
                additionalInfo = t.additionalInfo

            if additionalInfo is None:
                return None

            if additionalInfo.is_tracing:
                f = frame
                while f is not None:
                    fname, bs = GetFilenameAndBase(f)
                    if bs == 'pydevd_frame.py':
                        if 'trace_dispatch' == f.f_code.co_name:
                            return None  #we don't wan't to trace code invoked from pydevd_frame.trace_dispatch
                    f = f.f_back

            # if thread is not alive, cancel trace_dispatch processing
            if not isThreadAlive(t):
                self.processThreadNotAlive(GetThreadId(t))
                return None  # suspend tracing

            if is_file_to_ignore:
                return None

            # each new frame...
            return additionalInfo.CreateDbFrame((self, filename, additionalInfo, t, frame)).trace_dispatch(frame, event, arg)

        except SystemExit:
            return None

        except Exception:
            # Log it
            if traceback is not None:
                # This can actually happen during the interpreter shutdown in Python 2.7
                traceback.print_exc()
            return None

    if USE_PSYCO_OPTIMIZATION:
        try:
            import psyco
            trace_dispatch = psyco.proxy(trace_dispatch)
            processNetCommand = psyco.proxy(processNetCommand)
            processInternalCommands = psyco.proxy(processInternalCommands)
            doWaitSuspend = psyco.proxy(doWaitSuspend)
            getInternalQueue = psyco.proxy(getInternalQueue)
        except ImportError:
            if hasattr(sys, 'exc_clear'):  # jython does not have it
                sys.exc_clear()  # don't keep the traceback (let's keep it clear for when we go to the point of executing client code)

            if not IS_PY3K and not IS_PY27 and not IS_64_BITS and not sys.platform.startswith("java") and not sys.platform.startswith("cli"):
                sys.stderr.write("pydev debugger: warning: psyco not available for speedups (the debugger will still work correctly, but a bit slower)\n")
                sys.stderr.flush()



    def SetTraceForFrameAndParents(self, frame, also_add_to_passed_frame=True, overwrite_prev_trace=False):
        dispatch_func = self.trace_dispatch

        if also_add_to_passed_frame:
            self.update_trace(frame, dispatch_func, overwrite_prev_trace)

        frame = frame.f_back
        while frame:
            self.update_trace(frame, dispatch_func, overwrite_prev_trace)

            frame = frame.f_back
        del frame

    def update_trace(self, frame, dispatch_func, overwrite_prev):
        if frame.f_trace is None:
          frame.f_trace = dispatch_func
        else:
          if overwrite_prev:
              frame.f_trace = dispatch_func
          else:
              try:
                  #If it's the trace_exception, go back to the frame trace dispatch!
                  if frame.f_trace.im_func.__name__ == 'trace_exception':
                      frame.f_trace = frame.f_trace.im_self.trace_dispatch
              except AttributeError:
                  pass
              frame = frame.f_back
        del frame

    def prepareToRun(self):
        ''' Shared code to prepare debugging by installing traces and registering threads '''

        # for completeness, we'll register the pydevd.reader & pydevd.writer threads
        net = NetCommand(str(CMD_THREAD_CREATE), 0, '<xml><thread name="pydevd.reader" id="-1"/></xml>')
        self.writer.addCommand(net)
        net = NetCommand(str(CMD_THREAD_CREATE), 0, '<xml><thread name="pydevd.writer" id="-1"/></xml>')
        self.writer.addCommand(net)

        pydevd_tracing.SetTrace(self.trace_dispatch)
        self.patch_threads()


        PyDBCommandThread(self).start()
        PyDBCheckAliveThread(self).start()

    def patch_threads(self):
        try:
            # not available in jython!
            threading.settrace(self.trace_dispatch)  # for all future threads
        except:
            pass

        try:
            thread.start_new_thread = pydev_start_new_thread
            thread.start_new = pydev_start_new_thread
        except:
            pass


    def run(self, file, globals=None, locals=None, set_trace=True):
        if os.path.isdir(file):
            new_target = os.path.join(file, '__main__.py')
            if os.path.isfile(new_target):
                file = new_target

        if globals is None:
            # patch provided by: Scott Schlesier - when script is run, it does not
            # use globals from pydevd:
            # This will prevent the pydevd script from contaminating the namespace for the script to be debugged

            # pretend pydevd is not the main module, and
            # convince the file to be debugged that it was loaded as main
            sys.modules['pydevd'] = sys.modules['__main__']
            sys.modules['pydevd'].__name__ = 'pydevd'

            from imp import new_module
            m = new_module('__main__')
            sys.modules['__main__'] = m
            if hasattr(sys.modules['pydevd'], '__loader__'):
                setattr(m, '__loader__', getattr(sys.modules['pydevd'], '__loader__'))
                
            m.__file__ = file
            globals = m.__dict__
            try:
                globals['__builtins__'] = __builtins__
            except NameError:
                pass  # Not there on Jython...

        if locals is None:
            locals = globals

        if set_trace:
            # Predefined (writable) attributes: __name__ is the module's name;
            # __doc__ is the module's documentation string, or None if unavailable;
            # __file__ is the pathname of the file from which the module was loaded,
            # if it was loaded from a file. The __file__ attribute is not present for
            # C modules that are statically linked into the interpreter; for extension modules
            # loaded dynamically from a shared library, it is the pathname of the shared library file.


            # I think this is an ugly hack, bug it works (seems to) for the bug that says that sys.path should be the same in
            # debug and run.
            if m.__file__.startswith(sys.path[0]):
                # print >> sys.stderr, 'Deleting: ', sys.path[0]
                del sys.path[0]

            # now, the local directory has to be added to the pythonpath
            # sys.path.insert(0, os.getcwd())
            # Changed: it's not the local directory, but the directory of the file launched
            # The file being run ust be in the pythonpath (even if it was not before)
            sys.path.insert(0, os.path.split(file)[0])

            self.prepareToRun()

            while not self.readyToRun:
                time.sleep(0.1)  # busy wait until we receive run command


        pydev_imports.execfile(file, globals, locals)  # execute the script

    def exiting(self):
        sys.stdout.flush()
        sys.stderr.flush()
        self.checkOutputRedirect()
        cmd = self.cmdFactory.makeExitMessage()
        self.writer.addCommand(cmd)

def set_debug(setup):
    setup['DEBUG_RECORD_SOCKET_READS'] = True
    setup['DEBUG_TRACE_BREAKPOINTS'] = 1
    setup['DEBUG_TRACE_LEVEL'] = 3


def processCommandLine(argv):
    """ parses the arguments.
        removes our arguments from the command line """
    setup = {}
    setup['client'] = ''
    setup['server'] = False
    setup['port'] = 0
    setup['file'] = ''
    setup['multiproc'] = False
    setup['save-signatures'] = False
    i = 0
    del argv[0]
    while (i < len(argv)):
        if (argv[i] == '--port'):
            del argv[i]
            setup['port'] = int(argv[i])
            del argv[i]
        elif (argv[i] == '--vm_type'):
            del argv[i]
            setup['vm_type'] = argv[i]
            del argv[i]
        elif (argv[i] == '--client'):
            del argv[i]
            setup['client'] = argv[i]
            del argv[i]
        elif (argv[i] == '--server'):
            del argv[i]
            setup['server'] = True
        elif (argv[i] == '--file'):
            del argv[i]
            setup['file'] = argv[i]
            i = len(argv) # pop out, file is our last argument
        elif (argv[i] == '--DEBUG_RECORD_SOCKET_READS'):
            del argv[i]
            setup['DEBUG_RECORD_SOCKET_READS'] = True
        elif (argv[i] == '--DEBUG'):
            del argv[i]
            set_debug(setup)
        elif (argv[i] == '--multiproc'):
            del argv[i]
            setup['multiproc'] = True
        elif (argv[i] == '--save-signatures'):
            del argv[i]
            setup['save-signatures'] = True
        else:
            raise ValueError("unexpected option " + argv[i])
    return setup

def usage(doExit=0):
    sys.stdout.write('Usage:\n')
    sys.stdout.write('pydevd.py --port=N [(--client hostname) | --server] --file executable [file_options]\n')
    if doExit:
        sys.exit(0)

def SetTraceForParents(frame, dispatch_func):
    frame = frame.f_back
    while frame:
        if frame.f_trace is None:
            frame.f_trace = dispatch_func

        frame = frame.f_back
    del frame

def exit_hook():
    debugger = GetGlobalDebugger()
    debugger.exiting()

def initStdoutRedirect():
    if not getattr(sys, 'stdoutBuf', None):
        sys.stdoutBuf = pydevd_io.IOBuf()
        sys.stdout = pydevd_io.IORedirector(sys.stdout, sys.stdoutBuf) #@UndefinedVariable

def initStderrRedirect():
    if not getattr(sys, 'stderrBuf', None):
        sys.stderrBuf = pydevd_io.IOBuf()
        sys.stderr = pydevd_io.IORedirector(sys.stderr, sys.stderrBuf) #@UndefinedVariable

#=======================================================================================================================
# settrace
#=======================================================================================================================
def settrace(
    host=None,
    stdoutToServer=False,
    stderrToServer=False,
    port=5678,
    suspend=True,
    trace_only_current_thread=False,
    overwrite_prev_trace=False,
    patch_multiprocessing=False,
    ):
    '''Sets the tracing function with the pydev debug function and initializes needed facilities.

    @param host: the user may specify another host, if the debug server is not in the same machine (default is the local
        host)

    @param stdoutToServer: when this is true, the stdout is passed to the debug server

    @param stderrToServer: when this is true, the stderr is passed to the debug server
        so that they are printed in its console and not in this process console.

    @param port: specifies which port to use for communicating with the server (note that the server must be started
        in the same port). @note: currently it's hard-coded at 5678 in the client

    @param suspend: whether a breakpoint should be emulated as soon as this function is called.

    @param trace_only_current_thread: determines if only the current thread will be traced or all current and future
        threads will also have the tracing enabled.

    @param overwrite_prev_trace: if True we'll reset the frame.f_trace of frames which are already being traced

    @param patch_multiprocessing: if True we'll patch the functions which create new processes so that launched
        processes are debugged.
    '''
    _set_trace_lock.acquire()
    try:
        _locked_settrace(
            host,
            stdoutToServer,
            stderrToServer,
            port,
            suspend,
            trace_only_current_thread,
            overwrite_prev_trace,
            patch_multiprocessing,
        )
    finally:
        _set_trace_lock.release()



_set_trace_lock = threading.Lock()

def _locked_settrace(
    host,
    stdoutToServer,
    stderrToServer,
    port,
    suspend,
    trace_only_current_thread,
    overwrite_prev_trace,
    patch_multiprocessing,
    ):
    if patch_multiprocessing:
        try:
            import pydev_monkey #Jython 2.1 can't use it...
        except:
            pass
        else:
            pydev_monkey.patch_new_process_functions()

    if host is None:
        import pydev_localhost
        host = pydev_localhost.get_localhost()

    global connected
    global bufferStdOutToServer
    global bufferStdErrToServer

    if not connected :
        pydevd_vm_type.SetupType()

        debugger = PyDB()
        debugger.connect(host, port)  # Note: connect can raise error.

        # Mark connected only if it actually succeeded.
        connected = True
        bufferStdOutToServer = stdoutToServer
        bufferStdErrToServer = stderrToServer

        net = NetCommand(str(CMD_THREAD_CREATE), 0, '<xml><thread name="pydevd.reader" id="-1"/></xml>')
        debugger.writer.addCommand(net)
        net = NetCommand(str(CMD_THREAD_CREATE), 0, '<xml><thread name="pydevd.writer" id="-1"/></xml>')
        debugger.writer.addCommand(net)

        if bufferStdOutToServer:
            initStdoutRedirect()

        if bufferStdErrToServer:
            initStderrRedirect()

        debugger.SetTraceForFrameAndParents(GetFrame(), False, overwrite_prev_trace=overwrite_prev_trace)


        CustomFramesContainer.custom_frames_lock.acquire()
        try:
            for _frameId, custom_frame in CustomFramesContainer.custom_frames.items():
                debugger.SetTraceForFrameAndParents(custom_frame.frame, False)
        finally:
            CustomFramesContainer.custom_frames_lock.release()


        t = threadingCurrentThread()
        try:
            additionalInfo = t.additionalInfo
        except AttributeError:
            additionalInfo = PyDBAdditionalThreadInfo()
            t.additionalInfo = additionalInfo

        while not debugger.readyToRun:
            time.sleep(0.1)  # busy wait until we receive run command

        # note that we do that through pydevd_tracing.SetTrace so that the tracing
        # is not warned to the user!
        pydevd_tracing.SetTrace(debugger.trace_dispatch)

        if not trace_only_current_thread:
            # Trace future threads?
            debugger.patch_threads()

            # As this is the first connection, also set tracing for any untraced threads
            debugger.setTracingForUntracedContexts(ignore_frame=GetFrame(), overwrite_prev_trace=overwrite_prev_trace)

        sys.exitfunc = exit_hook
        #Suspend as the last thing after all tracing is in place.
        if suspend:
            debugger.setSuspend(t, CMD_SET_BREAK)

        PyDBCommandThread(debugger).start()
        PyDBCheckAliveThread(debugger).start()

    else:
        # ok, we're already in debug mode, with all set, so, let's just set the break
        debugger = GetGlobalDebugger()

        debugger.SetTraceForFrameAndParents(GetFrame(), False)

        t = threadingCurrentThread()
        try:
            additionalInfo = t.additionalInfo
        except AttributeError:
            additionalInfo = PyDBAdditionalThreadInfo()
            t.additionalInfo = additionalInfo

        pydevd_tracing.SetTrace(debugger.trace_dispatch)

        if not trace_only_current_thread:
            # Trace future threads?
            debugger.patch_threads()


        if suspend:
            debugger.setSuspend(t, CMD_SET_BREAK)


def stoptrace():
    global connected
    if connected:
        pydevd_tracing.RestoreSysSetTraceFunc()
        sys.settrace(None)
        try:
            #not available in jython!
            threading.settrace(None) # for all future threads
        except:
            pass
        
        try:
            thread.start_new_thread = _original_start_new_thread
            thread.start_new = _original_start_new_thread
        except:
            pass
    
        debugger = GetGlobalDebugger()
        
        if debugger:
            debugger.trace_dispatch = None
    
            debugger.SetTraceForFrameAndParents(GetFrame(), False)
        
            debugger.exiting()
        
            killAllPydevThreads()  
        
        connected = False

class Dispatcher(object):
    def __init__(self):
        self.port = None

    def connect(self, host, port):
        self.host  = host
        self.port = port
        self.client = StartClient(self.host, self.port)
        self.reader = DispatchReader(self)
        self.reader.dontTraceMe = False #we run reader in the same thread so we don't want to loose tracing
        self.reader.run()

    def close(self):
        try:
            self.reader.doKillPydevThread()
        except :
            pass

class DispatchReader(ReaderThread):
    def __init__(self, dispatcher):
        self.dispatcher = dispatcher
        ReaderThread.__init__(self, self.dispatcher.client)

    def handleExcept(self):
        ReaderThread.handleExcept(self)

    def processCommand(self, cmd_id, seq, text):
        if cmd_id == 99:
            self.dispatcher.port = int(text)
            self.killReceived = True


def dispatch():
    argv = sys.original_argv[:]
    setup = processCommandLine(argv)
    host = setup['client']
    port = setup['port']
    dispatcher = Dispatcher()
    try:
        dispatcher.connect(host, port)
        port = dispatcher.port
    finally:
        dispatcher.close()
    return host, port


def settrace_forked():
    host, port = dispatch()

    import pydevd_tracing
    pydevd_tracing.RestoreSysSetTraceFunc()

    if port is not None:
        global connected
        connected = False

        CustomFramesContainerInit()

        settrace(
            host,
            port=port,
            suspend=False,
            trace_only_current_thread=False,
            overwrite_prev_trace=True,
            patch_multiprocessing=True,
            )
#=======================================================================================================================
# main
#=======================================================================================================================
if __name__ == '__main__':
    # parse the command line. --file is our last argument that is required
    try:
        sys.original_argv = sys.argv[:]
        setup = processCommandLine(sys.argv)
    except ValueError:
        traceback.print_exc()
        usage(1)


    fix_getpass.fixGetpass()

    pydev_log.debug("Executing file %s" % setup['file'])
    pydev_log.debug("arguments: %s"% str(sys.argv))


    pydevd_vm_type.SetupType(setup.get('vm_type', None))

    if os.getenv('PYCHARM_DEBUG'):
        set_debug(setup)

    DebugInfoHolder.DEBUG_RECORD_SOCKET_READS = setup.get('DEBUG_RECORD_SOCKET_READS', False)
    DebugInfoHolder.DEBUG_TRACE_BREAKPOINTS = setup.get('DEBUG_TRACE_BREAKPOINTS', -1)
    DebugInfoHolder.DEBUG_TRACE_LEVEL = setup.get('DEBUG_TRACE_LEVEL', -1)

    port = setup['port']
    host = setup['client']
    f = setup['file']
    fix_app_engine_debug = False

    if setup['multiproc']:
        pydev_log.debug("Started in multiproc mode\n")

        dispatcher = Dispatcher()
        try:
            dispatcher.connect(host, port)
            if dispatcher.port is not None:
                port = dispatcher.port
                pydev_log.debug("Received port %d\n" %port)
                pydev_log.info("pydev debugger: process %d is connecting\n"% os.getpid())

                try:
                    pydev_monkey.patch_new_process_functions()
                except:
                    pydev_log.error("Error patching process functions\n")
                    traceback.print_exc()
            else:
                pydev_log.error("pydev debugger: couldn't get port for new debug process\n")
        finally:
            dispatcher.close()
    else:
        pydev_log.info("pydev debugger: starting\n")

        try:
            pydev_monkey.patch_new_process_functions_with_warning()
        except:
            pydev_log.error("Error patching process functions\n")
            traceback.print_exc()

        # Only do this patching if we're not running with multiprocess turned on.
        if f.find('dev_appserver.py') != -1:
            if os.path.basename(f).startswith('dev_appserver.py'):
                appserver_dir = os.path.dirname(f)
                version_file = os.path.join(appserver_dir, 'VERSION')
                if os.path.exists(version_file):
                    try:
                        stream = open(version_file, 'r')
                        try:
                            for line in stream.read().splitlines():
                                line = line.strip()
                                if line.startswith('release:'):
                                    line = line[8:].strip()
                                    version = line.replace('"', '')
                                    version = version.split('.')
                                    if int(version[0]) > 1:
                                        fix_app_engine_debug = True

                                    elif int(version[0]) == 1:
                                        if int(version[1]) >= 7:
                                            # Only fix from 1.7 onwards
                                            fix_app_engine_debug = True
                                    break
                        finally:
                            stream.close()
                    except:
                        traceback.print_exc()

    try:
        # In the default run (i.e.: run directly on debug mode), we try to patch stackless as soon as possible
        # on a run where we have a remote debug, we may have to be more careful because patching stackless means
        # that if the user already had a stackless.set_schedule_callback installed, he'd loose it and would need
        # to call it again (because stackless provides no way of getting the last function which was registered
        # in set_schedule_callback).
        #
        # So, ideally, if there's an application using stackless and the application wants to use the remote debugger
        # and benefit from stackless debugging, the application itself must call:
        #
        # import pydevd_stackless
        # pydevd_stackless.patch_stackless()
        #
        # itself to be able to benefit from seeing the tasklets created before the remote debugger is attached.
        import pydevd_stackless
        pydevd_stackless.patch_stackless()
    except:
        pass  # It's ok not having stackless there...

    if fix_app_engine_debug:
        sys.stderr.write("pydev debugger: google app engine integration enabled\n")
        curr_dir = os.path.dirname(__file__)
        app_engine_startup_file = os.path.join(curr_dir, 'pydev_app_engine_debug_startup.py')

        sys.argv.insert(1, '--python_startup_script=' + app_engine_startup_file)
        import json
        setup['pydevd'] = __file__
        sys.argv.insert(2, '--python_startup_args=%s' % json.dumps(setup),)
        sys.argv.insert(3, '--automatic_restart=no')
        sys.argv.insert(4, '--max_module_instances=1')

        debugger = PyDB()
        # Run the dev_appserver
        debugger.run(setup['file'], None, None, set_trace=False)

    else:
        # as to get here all our imports are already resolved, the psyco module can be
        # changed and we'll still get the speedups in the debugger, as those functions
        # are already compiled at this time.
        try:
            import psyco
        except ImportError:
            if hasattr(sys, 'exc_clear'):  # jython does not have it
                sys.exc_clear()  # don't keep the traceback -- clients don't want to see it
            pass  # that's ok, no need to mock psyco if it's not available anyways
        else:
            # if it's available, let's change it for a stub (pydev already made use of it)
            import pydevd_psyco_stub
            sys.modules['psyco'] = pydevd_psyco_stub

    debugger = PyDB()

    if setup['save-signatures']:
        if pydevd_vm_type.GetVmType() == pydevd_vm_type.PydevdVmType.JYTHON:
            sys.stderr.write("Collecting run-time type information is not supported for Jython\n")
        else:
            debugger.signature_factory = SignatureFactory()

    debugger.connect(host, port)

    connected = True #Mark that we're connected when started from inside ide.

    debugger.run(setup['file'], None, None)