-
Notifications
You must be signed in to change notification settings - Fork 663
/
jerry-client-ws.py
executable file
·1305 lines (1034 loc) · 45.6 KB
/
jerry-client-ws.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
# Copyright JS Foundation and other contributors, http://js.foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function
from cmd import Cmd
from pprint import pprint # For the readable stack printing.
import argparse
import logging
import re
import select
import socket
import struct
import sys
import math
import time
# Expected debugger protocol version.
JERRY_DEBUGGER_VERSION = 3
# Messages sent by the server to client.
JERRY_DEBUGGER_CONFIGURATION = 1
JERRY_DEBUGGER_PARSE_ERROR = 2
JERRY_DEBUGGER_BYTE_CODE_CP = 3
JERRY_DEBUGGER_PARSE_FUNCTION = 4
JERRY_DEBUGGER_BREAKPOINT_LIST = 5
JERRY_DEBUGGER_BREAKPOINT_OFFSET_LIST = 6
JERRY_DEBUGGER_SOURCE_CODE = 7
JERRY_DEBUGGER_SOURCE_CODE_END = 8
JERRY_DEBUGGER_SOURCE_CODE_NAME = 9
JERRY_DEBUGGER_SOURCE_CODE_NAME_END = 10
JERRY_DEBUGGER_FUNCTION_NAME = 11
JERRY_DEBUGGER_FUNCTION_NAME_END = 12
JERRY_DEBUGGER_WAITING_AFTER_PARSE = 13
JERRY_DEBUGGER_RELEASE_BYTE_CODE_CP = 14
JERRY_DEBUGGER_MEMSTATS_RECEIVE = 15
JERRY_DEBUGGER_BREAKPOINT_HIT = 16
JERRY_DEBUGGER_EXCEPTION_HIT = 17
JERRY_DEBUGGER_EXCEPTION_STR = 18
JERRY_DEBUGGER_EXCEPTION_STR_END = 19
JERRY_DEBUGGER_BACKTRACE = 20
JERRY_DEBUGGER_BACKTRACE_END = 21
JERRY_DEBUGGER_EVAL_RESULT = 22
JERRY_DEBUGGER_EVAL_RESULT_END = 23
JERRY_DEBUGGER_WAIT_FOR_SOURCE = 24
JERRY_DEBUGGER_OUTPUT_RESULT = 25
JERRY_DEBUGGER_OUTPUT_RESULT_END = 26
# Subtypes of eval
JERRY_DEBUGGER_EVAL_EVAL = "\0"
JERRY_DEBUGGER_EVAL_THROW = "\1"
JERRY_DEBUGGER_EVAL_ABORT = "\2"
# Subtypes of eval result
JERRY_DEBUGGER_EVAL_OK = 1
JERRY_DEBUGGER_EVAL_ERROR = 2
# Subtypes of output
JERRY_DEBUGGER_OUTPUT_OK = 1
JERRY_DEBUGGER_OUTPUT_ERROR = 2
JERRY_DEBUGGER_OUTPUT_WARNING = 3
JERRY_DEBUGGER_OUTPUT_DEBUG = 4
JERRY_DEBUGGER_OUTPUT_TRACE = 5
# Messages sent by the client to server.
JERRY_DEBUGGER_FREE_BYTE_CODE_CP = 1
JERRY_DEBUGGER_UPDATE_BREAKPOINT = 2
JERRY_DEBUGGER_EXCEPTION_CONFIG = 3
JERRY_DEBUGGER_PARSER_CONFIG = 4
JERRY_DEBUGGER_MEMSTATS = 5
JERRY_DEBUGGER_STOP = 6
JERRY_DEBUGGER_PARSER_RESUME = 7
JERRY_DEBUGGER_CLIENT_SOURCE = 8
JERRY_DEBUGGER_CLIENT_SOURCE_PART = 9
JERRY_DEBUGGER_NO_MORE_SOURCES = 10
JERRY_DEBUGGER_CONTEXT_RESET = 11
JERRY_DEBUGGER_CONTINUE = 12
JERRY_DEBUGGER_STEP = 13
JERRY_DEBUGGER_NEXT = 14
JERRY_DEBUGGER_FINISH = 15
JERRY_DEBUGGER_GET_BACKTRACE = 16
JERRY_DEBUGGER_EVAL = 17
JERRY_DEBUGGER_EVAL_PART = 18
MAX_BUFFER_SIZE = 128
WEBSOCKET_BINARY_FRAME = 2
WEBSOCKET_FIN_BIT = 0x80
def arguments_parse():
parser = argparse.ArgumentParser(description="JerryScript debugger client")
parser.add_argument("address", action="store", nargs="?", default="localhost:5001",
help="specify a unique network address for connection (default: %(default)s)")
parser.add_argument("-v", "--verbose", action="store_true", default=False,
help="increase verbosity (default: %(default)s)")
parser.add_argument("--non-interactive", action="store_true", default=False,
help="disable stop when newline is pressed (default: %(default)s)")
parser.add_argument("--color", action="store_true", default=False,
help="enable color highlighting on source commands (default: %(default)s)")
parser.add_argument("--display", action="store", default=None, type=int,
help="set display range")
parser.add_argument("--exception", action="store", default=None, type=int, choices=[0, 1],
help="set exception config, usage 1: [Enable] or 0: [Disable]")
parser.add_argument("--client-source", action="store", default=[], type=str, nargs="+",
help="specify a javascript source file to execute")
args = parser.parse_args()
if args.verbose:
logging.basicConfig(format="%(levelname)s: %(message)s", level=logging.DEBUG)
logging.debug("Debug logging mode: ON")
return args
class JerryBreakpoint(object):
def __init__(self, line, offset, function):
self.line = line
self.offset = offset
self.function = function
self.active_index = -1
def __str__(self):
result = self.function.source_name or "<unknown>"
result += ":%d" % (self.line)
if self.function.is_func:
result += " (in "
result += self.function.name or "function"
result += "() at line:%d, col:%d)" % (self.function.line, self.function.column)
return result
def __repr__(self):
return ("Breakpoint(line:%d, offset:%d, active_index:%d)"
% (self.line, self.offset, self.active_index))
class JerryPendingBreakpoint(object):
def __init__(self, line=None, source_name=None, function=None):
self.function = function
self.line = line
self.source_name = source_name
self.index = -1
def __str__(self):
result = self.source_name or ""
if self.line:
result += ":%d" % (self.line)
else:
result += "%s()" % (self.function)
return result
class JerryFunction(object):
# pylint: disable=too-many-instance-attributes,too-many-arguments
def __init__(self, is_func, byte_code_cp, source, source_name, line, column, name, lines, offsets):
self.is_func = is_func
self.byte_code_cp = byte_code_cp
self.source = re.split("\r\n|[\r\n]", source)
self.source_name = source_name
self.name = name
self.lines = {}
self.offsets = {}
self.line = line
self.column = column
self.first_breakpoint_line = lines[0]
self.first_breakpoint_offset = offsets[0]
if len(self.source) > 1 and not self.source[-1]:
self.source.pop()
for i, line in enumerate(lines):
offset = offsets[i]
breakpoint = JerryBreakpoint(line, offset, self)
self.lines[line] = breakpoint
self.offsets[offset] = breakpoint
def __repr__(self):
result = ("Function(byte_code_cp:0x%x, source_name:%r, name:%r, line:%d, column:%d { "
% (self.byte_code_cp, self.source_name, self.name, self.line, self.column))
result += ','.join([str(breakpoint) for breakpoint in self.lines.values()])
return result + " })"
class DebuggerPrompt(Cmd):
def __init__(self, debugger):
Cmd.__init__(self)
self.debugger = debugger
self.stop = False
self.quit = False
self.cont = True
self.non_interactive = False
self.client_sources = []
def precmd(self, line):
self.stop = False
self.cont = False
if self.non_interactive:
print("%s" % line)
return line
def postcmd(self, stop, line):
return self.stop
def do_quit(self, args):
""" Exit JerryScript debugger """
self.do_delete("all")
self.do_exception("0") # disable the exception handler
self._exec_command(args, JERRY_DEBUGGER_CONTINUE)
self.stop = True
self.quit = True
def do_break(self, args):
""" Insert breakpoints on the given lines or functions """
if args == "":
print("Error: Breakpoint index expected")
elif ':' in args:
try:
args_second = int(args.split(':', 1)[1])
if args_second < 0:
print("Error: Positive breakpoint index expected")
else:
set_breakpoint(self.debugger, args, False)
except ValueError as val_errno:
print("Error: Positive breakpoint index expected: %s" % val_errno)
else:
set_breakpoint(self.debugger, args, False)
do_b = do_break
def _exec_command(self, args, command_id):
self.stop = True
if args != "":
print("Error: No argument expected")
else:
self.debugger.send_command(command_id)
def do_continue(self, args):
""" Continue execution """
self._exec_command(args, JERRY_DEBUGGER_CONTINUE)
self.stop = True
self.cont = True
if not self.non_interactive:
print("Press enter to stop JavaScript execution.")
do_c = do_continue
def do_step(self, args):
""" Next breakpoint, step into functions """
self._exec_command(args, JERRY_DEBUGGER_STEP)
self.cont = True
do_s = do_step
def do_next(self, args):
""" Next breakpoint in the same context """
if not args:
args = 0
else:
try:
args = int(args)
if args <= 0:
raise ValueError(args)
except ValueError as val_errno:
print("Error: expected a positive integer: %s" % val_errno)
return
args = min(args, len(self.debugger.last_breakpoint_hit.function.lines) -
self.debugger.last_breakpoint_hit.function.line) - 1
self.debugger.repeats_remain = args
self._exec_command("", JERRY_DEBUGGER_NEXT)
self.cont = True
do_n = do_next
def do_finish(self, args):
""" Continue running until the current function returns """
self._exec_command(args, JERRY_DEBUGGER_FINISH)
self.cont = True
do_f = do_finish
def do_list(self, _):
""" Lists the available breakpoints """
if self.debugger.active_breakpoint_list:
print("=== %sActive breakpoints %s ===" % (self.debugger.green_bg, self.debugger.nocolor))
for breakpoint in self.debugger.active_breakpoint_list.values():
print(" %d: %s" % (breakpoint.active_index, breakpoint))
if self.debugger.pending_breakpoint_list:
print("=== %sPending breakpoints%s ===" % (self.debugger.yellow_bg, self.debugger.nocolor))
for breakpoint in self.debugger.pending_breakpoint_list.values():
print(" %d: %s (pending)" % (breakpoint.index, breakpoint))
if not self.debugger.active_breakpoint_list and not self.debugger.pending_breakpoint_list:
print("No breakpoints")
def do_delete(self, args):
""" Delete the given breakpoint, use 'delete all|active|pending' to clear all the given breakpoints """
if not args:
print("Error: Breakpoint index expected")
return
elif args == "all":
self.debugger.delete_active()
self.debugger.delete_pending()
elif args == "pending":
self.debugger.delete_pending()
elif args == "active":
self.debugger.delete_active()
else:
try:
breakpoint_index = int(args)
except ValueError as val_errno:
print("Error: Integer number expected, %s" % (val_errno))
return
if breakpoint_index in self.debugger.active_breakpoint_list:
breakpoint = self.debugger.active_breakpoint_list[breakpoint_index]
del self.debugger.active_breakpoint_list[breakpoint_index]
breakpoint.active_index = -1
self.debugger.send_breakpoint(breakpoint)
elif breakpoint_index in self.debugger.pending_breakpoint_list:
del self.debugger.pending_breakpoint_list[breakpoint_index]
if not self.debugger.pending_breakpoint_list:
self.debugger.send_parser_config(0)
else:
print("Error: Breakpoint %d not found" % (breakpoint_index))
def do_backtrace(self, args):
""" Get backtrace data from debugger """
max_depth = 0
if args:
try:
max_depth = int(args)
if max_depth <= 0:
print("Error: Positive integer number expected")
return
except ValueError as val_errno:
print("Error: Positive integer number expected, %s" % (val_errno))
return
message = struct.pack(self.debugger.byte_order + "BBIB" + self.debugger.idx_format,
WEBSOCKET_BINARY_FRAME | WEBSOCKET_FIN_BIT,
WEBSOCKET_FIN_BIT + 1 + 4,
0,
JERRY_DEBUGGER_GET_BACKTRACE,
max_depth)
self.debugger.send_message(message)
self.stop = True
do_bt = do_backtrace
def do_src(self, args):
""" Get current source code """
if args:
line_num = src_check_args(args)
if line_num >= 0:
print_source(self.debugger, line_num, 0)
elif line_num == 0:
print_source(self.debugger, self.debugger.default_viewrange, 0)
else:
return
do_source = do_src
def _scroll_direction(self, args):
""" Helper function for do_scroll """
self.debugger.src_offset_diff = int(max(math.floor(self.debugger.display / 3), 1))
if args in "up":
self.debugger.src_offset -= self.debugger.src_offset_diff
print_source(self.debugger, self.debugger.display, self.debugger.src_offset)
else:
self.debugger.src_offset += self.debugger.src_offset_diff
print_source(self.debugger, self.debugger.display, self.debugger.src_offset)
def do_scroll(self, _):
""" Scroll the source up or down """
while True:
key = sys.stdin.readline()
if key == 'w\n':
self._scroll_direction("up")
elif key == 's\n':
self._scroll_direction("down")
elif key == 'q\n':
break
else:
print("Invalid key")
def do_display(self, args):
""" Toggle source code display after breakpoints """
if args:
line_num = src_check_args(args)
if line_num >= 0:
self.debugger.display = line_num
else:
return
else:
print("Non-negative integer number expected, 0 turns off this function")
return
def do_dump(self, args):
""" Dump all of the debugger data """
if args:
print("Error: No argument expected")
return
pprint(self.debugger.function_list)
def _send_string(self, args, message_type):
size = len(args)
# 1: length of type byte
# 4: length of an uint32 value
message_header = 1 + 4
max_fragment = min(self.debugger.max_message_size - message_header, size)
message = struct.pack(self.debugger.byte_order + "BBIBI",
WEBSOCKET_BINARY_FRAME | WEBSOCKET_FIN_BIT,
WEBSOCKET_FIN_BIT + max_fragment + message_header,
0,
message_type,
size)
if size == max_fragment:
self.debugger.send_message(message + args)
self.stop = True
return
self.debugger.send_message(message + args[0:max_fragment])
offset = max_fragment
if message_type == JERRY_DEBUGGER_EVAL:
message_type = JERRY_DEBUGGER_EVAL_PART
else:
message_type = JERRY_DEBUGGER_CLIENT_SOURCE_PART
# 1: length of type byte
message_header = 1
max_fragment = self.debugger.max_message_size - message_header
while offset < size:
next_fragment = min(max_fragment, size - offset)
message = struct.pack(self.debugger.byte_order + "BBIB",
WEBSOCKET_BINARY_FRAME | WEBSOCKET_FIN_BIT,
WEBSOCKET_FIN_BIT + next_fragment + message_header,
0,
message_type)
prev_offset = offset
offset += next_fragment
self.debugger.send_message(message + args[prev_offset:offset])
self.stop = True
def do_eval(self, args):
""" Evaluate JavaScript source code """
self._send_string(JERRY_DEBUGGER_EVAL_EVAL + args, JERRY_DEBUGGER_EVAL)
do_e = do_eval
def do_throw(self, args):
""" Throw an exception """
self._send_string(JERRY_DEBUGGER_EVAL_THROW + args, JERRY_DEBUGGER_EVAL)
def do_abort(self, args):
""" Throw an exception """
self._send_string(JERRY_DEBUGGER_EVAL_ABORT + args, JERRY_DEBUGGER_EVAL)
def do_exception(self, args):
""" Config the exception handler module """
if not args:
print("Error: Status expected!")
return
enable = int(args)
if enable == 1:
logging.debug("Stop at exception enabled")
elif enable == 0:
logging.debug("Stop at exception disabled")
else:
print("Error: Invalid input! Usage 1: [Enable] or 0: [Disable].")
return
self.debugger.send_exception_config(enable)
def do_memstats(self, args):
""" Memory statistics """
self._exec_command(args, JERRY_DEBUGGER_MEMSTATS)
return
do_ms = do_memstats
def store_client_sources(self, args):
self.client_sources = args
def send_client_source(self):
# Send no more source message if there is no source
if not self.client_sources:
self.send_no_more_source()
return
path = self.client_sources.pop(0)
if not path.lower().endswith('.js'):
sys.exit("Error: Javascript file expected!")
return
with open(path, 'r') as src_file:
content = path + "\0" + src_file.read()
self._send_string(content, JERRY_DEBUGGER_CLIENT_SOURCE)
def send_no_more_source(self):
self._exec_command("", JERRY_DEBUGGER_NO_MORE_SOURCES)
self.cont = True
class Multimap(object):
def __init__(self):
self.map = {}
def get(self, key):
if key in self.map:
return self.map[key]
return []
def insert(self, key, value):
if key in self.map:
self.map[key].append(value)
else:
self.map[key] = [value]
def delete(self, key, value):
items = self.map[key]
if len(items) == 1:
del self.map[key]
else:
del items[items.index(value)]
def __repr__(self):
return "Multimap(%r)" % (self.map)
class JerryDebugger(object):
# pylint: disable=too-many-instance-attributes,too-many-statements
def __init__(self, address):
if ":" not in address:
self.host = address
self.port = 5001 # use default port
else:
self.host, self.port = address.split(":")
self.port = int(self.port)
print("Connecting to: %s:%s" % (self.host, self.port))
self.message_data = b""
self.function_list = {}
self.last_breakpoint_hit = None
self.next_breakpoint_index = 0
self.active_breakpoint_list = {}
self.pending_breakpoint_list = {}
self.line_list = Multimap()
self.display = 0
self.default_viewrange = 3
self.green = ''
self.red = ''
self.yellow = ''
self.green_bg = ''
self.yellow_bg = ''
self.blue = ''
self.nocolor = ''
self.src_offset = 0
self.src_offset_diff = 0
self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.client_socket.connect((self.host, self.port))
self.repeats_remain = 0
self.send_message(b"GET /jerry-debugger HTTP/1.1\r\n" +
b"Upgrade: websocket\r\n" +
b"Connection: Upgrade\r\n" +
b"Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\r\n")
result = b""
expected = (b"HTTP/1.1 101 Switching Protocols\r\n" +
b"Upgrade: websocket\r\n" +
b"Connection: Upgrade\r\n" +
b"Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n\r\n")
len_expected = len(expected)
while len(result) < len_expected:
result += self.client_socket.recv(1024)
len_result = len(result)
if result[0:len_expected] != expected:
raise Exception("Unexpected handshake")
if len_result > len_expected:
result = result[len_expected:]
else:
result = b""
len_expected = 7
# Network configurations, which has the following struct:
# header [2] - opcode[1], size[1]
# type [1]
# max_message_size [1]
# cpointer_size [1]
# little_endian [1]
# version [1]
while len(result) < len_expected:
result += self.client_socket.recv(1024)
len_result = len(result)
expected = struct.pack("BBB",
WEBSOCKET_BINARY_FRAME | WEBSOCKET_FIN_BIT,
5,
JERRY_DEBUGGER_CONFIGURATION)
if result[0:3] != expected:
raise Exception("Unexpected configuration")
self.max_message_size = ord(result[3])
self.cp_size = ord(result[4])
self.little_endian = ord(result[5])
self.version = ord(result[6])
if self.version != JERRY_DEBUGGER_VERSION:
raise Exception("Incorrect debugger version from target: %d expected: %d" %
(self.version, JERRY_DEBUGGER_VERSION))
if self.little_endian:
self.byte_order = "<"
logging.debug("Little-endian machine")
else:
self.byte_order = ">"
logging.debug("Big-endian machine")
if self.cp_size == 2:
self.cp_format = "H"
else:
self.cp_format = "I"
self.idx_format = "I"
logging.debug("Compressed pointer size: %d", self.cp_size)
if len_result > len_expected:
self.message_data = result[len_expected:]
def __del__(self):
self.client_socket.close()
def send_message(self, message):
size = len(message)
while size > 0:
bytes_send = self.client_socket.send(message)
if bytes_send < size:
message = message[bytes_send:]
size -= bytes_send
def delete_active(self):
for i in self.active_breakpoint_list.values():
breakpoint = self.active_breakpoint_list[i.active_index]
del self.active_breakpoint_list[i.active_index]
breakpoint.active_index = -1
self.send_breakpoint(breakpoint)
def delete_pending(self):
if self.pending_breakpoint_list:
self.pending_breakpoint_list.clear()
self.send_parser_config(0)
def breakpoint_pending_exists(self, breakpoint):
for existing_bp in self.pending_breakpoint_list.values():
if (breakpoint.line and existing_bp.source_name == breakpoint.source_name and \
existing_bp.line == breakpoint.line) \
or (not breakpoint.line and existing_bp.function == breakpoint.function):
return True
return False
def send_breakpoint(self, breakpoint):
message = struct.pack(self.byte_order + "BBIBB" + self.cp_format + self.idx_format,
WEBSOCKET_BINARY_FRAME | WEBSOCKET_FIN_BIT,
WEBSOCKET_FIN_BIT + 1 + 1 + self.cp_size + 4,
0,
JERRY_DEBUGGER_UPDATE_BREAKPOINT,
int(breakpoint.active_index >= 0),
breakpoint.function.byte_code_cp,
breakpoint.offset)
self.send_message(message)
def send_bytecode_cp(self, byte_code_cp):
message = struct.pack(self.byte_order + "BBIB" + self.cp_format,
WEBSOCKET_BINARY_FRAME | WEBSOCKET_FIN_BIT,
WEBSOCKET_FIN_BIT + 1 + self.cp_size,
0,
JERRY_DEBUGGER_FREE_BYTE_CODE_CP,
byte_code_cp)
self.send_message(message)
def send_command(self, command):
message = struct.pack(self.byte_order + "BBIB",
WEBSOCKET_BINARY_FRAME | WEBSOCKET_FIN_BIT,
WEBSOCKET_FIN_BIT + 1,
0,
command)
self.send_message(message)
def send_exception_config(self, enable):
message = struct.pack(self.byte_order + "BBIBB",
WEBSOCKET_BINARY_FRAME | WEBSOCKET_FIN_BIT,
WEBSOCKET_FIN_BIT + 1 + 1,
0,
JERRY_DEBUGGER_EXCEPTION_CONFIG,
enable)
self.send_message(message)
def send_parser_config(self, enable):
message = struct.pack(self.byte_order + "BBIBB",
WEBSOCKET_BINARY_FRAME | WEBSOCKET_FIN_BIT,
WEBSOCKET_FIN_BIT + 1 + 1,
0,
JERRY_DEBUGGER_PARSER_CONFIG,
enable)
self.send_message(message)
def set_colors(self):
self.nocolor = '\033[0m'
self.green = '\033[92m'
self.red = '\033[31m'
self.yellow = '\033[93m'
self.green_bg = '\033[42m\033[30m'
self.yellow_bg = '\033[43m\033[30m'
self.blue = '\033[94m'
def get_message(self, blocking):
# Connection was closed
if self.message_data is None:
return None
while True:
if len(self.message_data) >= 2:
if ord(self.message_data[0]) != WEBSOCKET_BINARY_FRAME | WEBSOCKET_FIN_BIT:
raise Exception("Unexpected data frame")
size = ord(self.message_data[1])
if size == 0 or size >= 126:
raise Exception("Unexpected data frame")
if len(self.message_data) >= size + 2:
result = self.message_data[0:size + 2]
self.message_data = self.message_data[size + 2:]
return result
if not blocking:
select_result = select.select([self.client_socket], [], [], 0)[0]
if self.client_socket not in select_result:
return b''
data = self.client_socket.recv(MAX_BUFFER_SIZE)
if not data:
self.message_data = None
return None
self.message_data += data
# pylint: disable=too-many-branches,too-many-locals,too-many-statements
def parse_source(debugger, data):
source_code = ""
source_code_name = ""
function_name = ""
stack = [{"line": 1,
"column": 1,
"name": "",
"lines": [],
"offsets": []}]
new_function_list = {}
while True:
if data is None:
return
buffer_type = ord(data[2])
buffer_size = ord(data[1]) - 1
logging.debug("Parser buffer type: %d, message size: %d", buffer_type, buffer_size)
if buffer_type == JERRY_DEBUGGER_PARSE_ERROR:
logging.error("Parser error!")
return
elif buffer_type in [JERRY_DEBUGGER_SOURCE_CODE, JERRY_DEBUGGER_SOURCE_CODE_END]:
source_code += data[3:]
elif buffer_type in [JERRY_DEBUGGER_SOURCE_CODE_NAME, JERRY_DEBUGGER_SOURCE_CODE_NAME_END]:
source_code_name += data[3:]
elif buffer_type in [JERRY_DEBUGGER_FUNCTION_NAME, JERRY_DEBUGGER_FUNCTION_NAME_END]:
function_name += data[3:]
elif buffer_type == JERRY_DEBUGGER_PARSE_FUNCTION:
logging.debug("Source name: %s, function name: %s", source_code_name, function_name)
position = struct.unpack(debugger.byte_order + debugger.idx_format + debugger.idx_format,
data[3: 3 + 4 + 4])
stack.append({"source": source_code,
"source_name": source_code_name,
"line": position[0],
"column": position[1],
"name": function_name,
"lines": [],
"offsets": []})
function_name = ""
elif buffer_type in [JERRY_DEBUGGER_BREAKPOINT_LIST, JERRY_DEBUGGER_BREAKPOINT_OFFSET_LIST]:
name = "lines"
if buffer_type == JERRY_DEBUGGER_BREAKPOINT_OFFSET_LIST:
name = "offsets"
logging.debug("Breakpoint %s received", name)
buffer_pos = 3
while buffer_size > 0:
line = struct.unpack(debugger.byte_order + debugger.idx_format,
data[buffer_pos: buffer_pos + 4])
stack[-1][name].append(line[0])
buffer_pos += 4
buffer_size -= 4
elif buffer_type == JERRY_DEBUGGER_BYTE_CODE_CP:
byte_code_cp = struct.unpack(debugger.byte_order + debugger.cp_format,
data[3: 3 + debugger.cp_size])[0]
logging.debug("Byte code cptr received: {0x%x}", byte_code_cp)
func_desc = stack.pop()
# We know the last item in the list is the general byte code.
if len(stack) == 0:
func_desc["source"] = source_code
func_desc["source_name"] = source_code_name
function = JerryFunction(len(stack) != 0,
byte_code_cp,
func_desc["source"],
func_desc["source_name"],
func_desc["line"],
func_desc["column"],
func_desc["name"],
func_desc["lines"],
func_desc["offsets"])
new_function_list[byte_code_cp] = function
if len(stack) == 0:
logging.debug("Parse completed.")
break
elif buffer_type == JERRY_DEBUGGER_RELEASE_BYTE_CODE_CP:
# Redefined functions are dropped during parsing.
byte_code_cp = struct.unpack(debugger.byte_order + debugger.cp_format,
data[3: 3 + debugger.cp_size])[0]
if byte_code_cp in new_function_list:
del new_function_list[byte_code_cp]
debugger.send_bytecode_cp(byte_code_cp)
else:
release_function(debugger, data)
else:
logging.error("Parser error!")
return
data = debugger.get_message(True)
# Copy the ready list to the global storage.
debugger.function_list.update(new_function_list)
for function in new_function_list.values():
for line, breakpoint in function.lines.items():
debugger.line_list.insert(line, breakpoint)
# Try to set the pending breakpoints
if debugger.pending_breakpoint_list:
logging.debug("Pending breakpoints list: %s", debugger.pending_breakpoint_list)
bp_list = debugger.pending_breakpoint_list
for breakpoint_index, breakpoint in bp_list.items():
for src in debugger.function_list.values():
if src.source_name == breakpoint.source_name:
source_lines = len(src.source)
else:
source_lines = 0
if breakpoint.line:
if breakpoint.line <= source_lines:
command = breakpoint.source_name + ":" + str(breakpoint.line)
if set_breakpoint(debugger, command, True):
del bp_list[breakpoint_index]
elif breakpoint.function:
command = breakpoint.function
if set_breakpoint(debugger, command, True):
del bp_list[breakpoint_index]
if not bp_list:
debugger.send_parser_config(0)
else:
logging.debug("No pending breakpoints")
def src_check_args(args):
try:
line_num = int(args)
if line_num < 0:
print("Error: Non-negative integer number expected")
return -1
return line_num
except ValueError as val_errno:
print("Error: Non-negative integer number expected: %s" % (val_errno))
return -1
def print_source(debugger, line_num, offset):
last_bp = debugger.last_breakpoint_hit
if not last_bp:
return
lines = last_bp.function.source
if last_bp.function.source_name:
print("Source: %s" % (last_bp.function.source_name))
if line_num == 0:
start = 0
end = len(last_bp.function.source)
else:
start = max(last_bp.line - line_num, 0)
end = min(last_bp.line + line_num - 1, len(last_bp.function.source))
if offset:
if start + offset < 0:
debugger.src_offset += debugger.src_offset_diff
offset += debugger.src_offset_diff
elif end + offset > len(last_bp.function.source):
debugger.src_offset -= debugger.src_offset_diff
offset -= debugger.src_offset_diff
start = max(start + offset, 0)
end = min(end + offset, len(last_bp.function.source))
for i in range(start, end):
if i == last_bp.line - 1:
print("%s%4d%s %s>%s %s" % (debugger.green, i + 1, debugger.nocolor, debugger.red, \
debugger.nocolor, lines[i]))
else:
print("%s%4d%s %s" % (debugger.green, i + 1, debugger.nocolor, lines[i]))
def release_function(debugger, data):
byte_code_cp = struct.unpack(debugger.byte_order + debugger.cp_format,
data[3: 3 + debugger.cp_size])[0]
function = debugger.function_list[byte_code_cp]
for line, breakpoint in function.lines.items():
debugger.line_list.delete(line, breakpoint)
if breakpoint.active_index >= 0:
del debugger.active_breakpoint_list[breakpoint.active_index]