-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathpython.c
3163 lines (2634 loc) · 90.5 KB
/
python.c
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
/* General python/gdb code
Copyright (C) 2008-2024 Free Software Foundation, Inc.
This file is part of GDB.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include "arch-utils.h"
#include "command.h"
#include "ui-out.h"
#include "cli/cli-script.h"
#include "cli/cli-cmds.h"
#include "progspace.h"
#include "objfiles.h"
#include "value.h"
#include "language.h"
#include "gdbsupport/event-loop.h"
#include "readline/tilde.h"
#include "python.h"
#include "extension-priv.h"
#include "cli/cli-utils.h"
#include <ctype.h>
#include "location.h"
#include "run-on-main-thread.h"
#include "observable.h"
#include "build-id.h"
#include "cli/cli-style.h"
#if GDB_SELF_TEST
#include "gdbsupport/selftest.h"
#endif
/* Declared constants and enum for python stack printing. */
static const char python_excp_none[] = "none";
static const char python_excp_full[] = "full";
static const char python_excp_message[] = "message";
/* "set python print-stack" choices. */
static const char *const python_excp_enums[] =
{
python_excp_none,
python_excp_full,
python_excp_message,
NULL
};
/* The exception printing variable. 'full' if we want to print the
error message and stack, 'none' if we want to print nothing, and
'message' if we only want to print the error message. 'message' is
the default. */
static const char *gdbpy_should_print_stack = python_excp_message;
#ifdef HAVE_PYTHON
#include "cli/cli-decode.h"
#include "charset.h"
#include "top.h"
#include "ui.h"
#include "python-internal.h"
#include "linespec.h"
#include "source.h"
#include "gdbsupport/version.h"
#include "target.h"
#include "gdbthread.h"
#include "interps.h"
#include "event-top.h"
#include "py-event.h"
#include "py-color.h"
/* True if Python has been successfully initialized, false
otherwise. */
int gdb_python_initialized;
extern PyMethodDef python_GdbMethods[];
PyObject *gdb_module;
PyObject *gdb_python_module;
/* Some string constants we may wish to use. */
PyObject *gdbpy_to_string_cst;
PyObject *gdbpy_children_cst;
PyObject *gdbpy_display_hint_cst;
PyObject *gdbpy_doc_cst;
PyObject *gdbpy_enabled_cst;
PyObject *gdbpy_value_cst;
/* The GdbError exception. */
PyObject *gdbpy_gdberror_exc;
/* The `gdb.error' base class. */
PyObject *gdbpy_gdb_error;
/* The `gdb.MemoryError' exception. */
PyObject *gdbpy_gdb_memory_error;
static script_sourcer_func gdbpy_source_script;
static objfile_script_sourcer_func gdbpy_source_objfile_script;
static objfile_script_executor_func gdbpy_execute_objfile_script;
static void gdbpy_initialize (const struct extension_language_defn *);
static int gdbpy_initialized (const struct extension_language_defn *);
static void finalize_python (const struct extension_language_defn *);
static void gdbpy_eval_from_control_command
(const struct extension_language_defn *, struct command_line *cmd);
static void gdbpy_start_type_printers (const struct extension_language_defn *,
struct ext_lang_type_printers *);
static enum ext_lang_rc gdbpy_apply_type_printers
(const struct extension_language_defn *,
const struct ext_lang_type_printers *, struct type *,
gdb::unique_xmalloc_ptr<char> *);
static void gdbpy_free_type_printers (const struct extension_language_defn *,
struct ext_lang_type_printers *);
static void gdbpy_set_quit_flag (const struct extension_language_defn *);
static bool gdbpy_check_quit_flag (const struct extension_language_defn *);
static enum ext_lang_rc gdbpy_before_prompt_hook
(const struct extension_language_defn *, const char *current_gdb_prompt);
static std::optional<std::string> gdbpy_colorize
(const std::string &filename, const std::string &contents);
static std::optional<std::string> gdbpy_colorize_disasm
(const std::string &content, gdbarch *gdbarch);
static ext_lang_missing_file_result gdbpy_handle_missing_debuginfo
(const struct extension_language_defn *extlang, struct objfile *objfile);
static ext_lang_missing_file_result gdbpy_find_objfile_from_buildid
(const struct extension_language_defn *extlang, program_space *pspace,
const struct bfd_build_id *build_id, const char *missing_filename);
/* The interface between gdb proper and loading of python scripts. */
static const struct extension_language_script_ops python_extension_script_ops =
{
gdbpy_source_script,
gdbpy_source_objfile_script,
gdbpy_execute_objfile_script,
gdbpy_auto_load_enabled
};
/* The interface between gdb proper and python extensions. */
static const struct extension_language_ops python_extension_ops =
{
gdbpy_initialize,
gdbpy_initialized,
finalize_python,
gdbpy_eval_from_control_command,
gdbpy_start_type_printers,
gdbpy_apply_type_printers,
gdbpy_free_type_printers,
gdbpy_apply_val_pretty_printer,
gdbpy_apply_frame_filter,
gdbpy_load_ptwrite_filter,
gdbpy_preserve_values,
gdbpy_breakpoint_has_cond,
gdbpy_breakpoint_cond_says_stop,
gdbpy_set_quit_flag,
gdbpy_check_quit_flag,
gdbpy_before_prompt_hook,
gdbpy_get_matching_xmethod_workers,
gdbpy_colorize,
gdbpy_colorize_disasm,
gdbpy_print_insn,
gdbpy_handle_missing_debuginfo,
gdbpy_find_objfile_from_buildid
};
#endif /* HAVE_PYTHON */
/* The main struct describing GDB's interface to the Python
extension language. */
const struct extension_language_defn extension_language_python =
{
EXT_LANG_PYTHON,
"python",
"Python",
".py",
"-gdb.py",
python_control,
#ifdef HAVE_PYTHON
&python_extension_script_ops,
&python_extension_ops
#else
NULL,
NULL
#endif
};
#ifdef HAVE_PYTHON
/* Architecture and language to be used in callbacks from
the Python interpreter. */
struct gdbarch *gdbpy_enter::python_gdbarch;
gdbpy_enter::gdbpy_enter (struct gdbarch *gdbarch,
const struct language_defn *language)
: m_gdbarch (python_gdbarch),
m_language (language == nullptr ? nullptr : current_language)
{
/* We should not ever enter Python unless initialized. */
if (!gdb_python_initialized)
error (_("Python not initialized"));
m_previous_active = set_active_ext_lang (&extension_language_python);
m_state = PyGILState_Ensure ();
python_gdbarch = gdbarch;
if (language != nullptr)
set_language (language->la_language);
/* Save it and ensure ! PyErr_Occurred () afterwards. */
m_error.emplace ();
}
gdbpy_enter::~gdbpy_enter ()
{
/* Leftover Python error is forbidden by Python Exception Handling. */
if (PyErr_Occurred ())
{
/* This order is similar to the one calling error afterwards. */
gdbpy_print_stack ();
warning (_("internal error: Unhandled Python exception"));
}
m_error->restore ();
python_gdbarch = m_gdbarch;
if (m_language != nullptr)
set_language (m_language->la_language);
restore_active_ext_lang (m_previous_active);
PyGILState_Release (m_state);
}
struct gdbarch *
gdbpy_enter::get_gdbarch ()
{
if (python_gdbarch != nullptr)
return python_gdbarch;
return get_current_arch ();
}
void
gdbpy_enter::finalize ()
{
python_gdbarch = current_inferior ()->arch ();
}
/* Set the quit flag. */
static void
gdbpy_set_quit_flag (const struct extension_language_defn *extlang)
{
PyErr_SetInterrupt ();
}
/* Return true if the quit flag has been set, false otherwise. */
static bool
gdbpy_check_quit_flag (const struct extension_language_defn *extlang)
{
if (!gdb_python_initialized)
return false;
gdbpy_gil gil;
return PyOS_InterruptOccurred ();
}
/* Evaluate a Python command like PyRun_SimpleString, but takes a
Python start symbol, and does not automatically print the stack on
errors. FILENAME is used to set the file name in error messages;
NULL means that this is evaluating a string, not the contents of a
file. */
static int
eval_python_command (const char *command, int start_symbol,
const char *filename = nullptr)
{
PyObject *m, *d;
m = PyImport_AddModule ("__main__");
if (m == NULL)
return -1;
d = PyModule_GetDict (m);
if (d == NULL)
return -1;
bool file_set = false;
if (filename != nullptr)
{
gdbpy_ref<> file = host_string_to_python_string ("__file__");
if (file == nullptr)
return -1;
/* PyDict_GetItemWithError returns a borrowed reference. */
PyObject *found = PyDict_GetItemWithError (d, file.get ());
if (found == nullptr)
{
if (PyErr_Occurred ())
return -1;
gdbpy_ref<> filename_obj = host_string_to_python_string (filename);
if (filename_obj == nullptr)
return -1;
if (PyDict_SetItem (d, file.get (), filename_obj.get ()) < 0)
return -1;
if (PyDict_SetItemString (d, "__cached__", Py_None) < 0)
return -1;
file_set = true;
}
}
/* Use this API because it is in Python 3.2. */
gdbpy_ref<> code (Py_CompileStringExFlags (command,
filename == nullptr
? "<string>"
: filename,
start_symbol,
nullptr, -1));
int result = -1;
if (code != nullptr)
{
gdbpy_ref<> eval_result (PyEval_EvalCode (code.get (), d, d));
if (eval_result != nullptr)
result = 0;
}
if (file_set)
{
/* If there's already an exception occurring, preserve it and
restore it before returning from this function. */
std::optional<gdbpy_err_fetch> save_error;
if (result < 0)
save_error.emplace ();
/* CPython also just ignores errors here. These should be
expected to be exceedingly rare anyway. */
if (PyDict_DelItemString (d, "__file__") < 0)
PyErr_Clear ();
if (PyDict_DelItemString (d, "__cached__") < 0)
PyErr_Clear ();
if (save_error.has_value ())
save_error->restore ();
}
return result;
}
/* Implementation of the gdb "python-interactive" command. */
static void
python_interactive_command (const char *arg, int from_tty)
{
struct ui *ui = current_ui;
int err;
scoped_restore save_async = make_scoped_restore (¤t_ui->async, 0);
arg = skip_spaces (arg);
gdbpy_enter enter_py;
if (arg && *arg)
{
std::string script = std::string (arg) + "\n";
/* Py_single_input causes the result to be displayed. */
err = eval_python_command (script.c_str (), Py_single_input);
}
else
{
err = PyRun_InteractiveLoop (ui->instream, "<stdin>");
dont_repeat ();
}
if (err)
gdbpy_handle_exception ();
}
/* Like PyRun_SimpleFile, but if there is an exception, it is not
automatically displayed. FILE is the Python script to run named
FILENAME.
On Windows hosts few users would build Python themselves (this is no
trivial task on this platform), and thus use binaries built by
someone else instead. There may happen situation where the Python
library and GDB are using two different versions of the C runtime
library. Python, being built with VC, would use one version of the
msvcr DLL (Eg. msvcr100.dll), while MinGW uses msvcrt.dll.
A FILE * from one runtime does not necessarily operate correctly in
the other runtime. */
static int
python_run_simple_file (FILE *file, const char *filename)
{
std::string contents = read_remainder_of_file (file);
return eval_python_command (contents.c_str (), Py_file_input, filename);
}
/* Given a command_line, return a command string suitable for passing
to Python. Lines in the string are separated by newlines. */
static std::string
compute_python_string (struct command_line *l)
{
struct command_line *iter;
std::string script;
for (iter = l; iter; iter = iter->next)
{
script += iter->line;
script += '\n';
}
return script;
}
/* Take a command line structure representing a 'python' command, and
evaluate its body using the Python interpreter. */
static void
gdbpy_eval_from_control_command (const struct extension_language_defn *extlang,
struct command_line *cmd)
{
if (cmd->body_list_1 != nullptr)
error (_("Invalid \"python\" block structure."));
gdbpy_enter enter_py;
std::string script = compute_python_string (cmd->body_list_0.get ());
int ret = eval_python_command (script.c_str (), Py_file_input);
if (ret != 0)
gdbpy_handle_exception ();
}
/* Implementation of the gdb "python" command. */
static void
python_command (const char *arg, int from_tty)
{
gdbpy_enter enter_py;
scoped_restore save_async = make_scoped_restore (¤t_ui->async, 0);
arg = skip_spaces (arg);
if (arg && *arg)
{
int ret = eval_python_command (arg, Py_file_input);
if (ret != 0)
gdbpy_handle_exception ();
}
else
{
counted_command_line l = get_command_line (python_control, "");
execute_control_command_untraced (l.get ());
}
}
/* Transform a gdb parameters's value into a Python value. May return
NULL (and set a Python exception) on error. Helper function for
get_parameter. */
PyObject *
gdbpy_parameter_value (const setting &var)
{
switch (var.type ())
{
case var_string:
case var_string_noescape:
case var_optional_filename:
case var_filename:
case var_enum:
{
const char *str;
if (var.type () == var_enum)
str = var.get<const char *> ();
else
str = var.get<std::string> ().c_str ();
return host_string_to_python_string (str).release ();
}
case var_color:
{
const ui_file_style::color &color = var.get<ui_file_style::color> ();
return create_color_object (color).release ();
}
case var_boolean:
{
if (var.get<bool> ())
Py_RETURN_TRUE;
else
Py_RETURN_FALSE;
}
case var_auto_boolean:
{
enum auto_boolean ab = var.get<enum auto_boolean> ();
if (ab == AUTO_BOOLEAN_TRUE)
Py_RETURN_TRUE;
else if (ab == AUTO_BOOLEAN_FALSE)
Py_RETURN_FALSE;
else
Py_RETURN_NONE;
}
case var_uinteger:
case var_integer:
case var_pinteger:
{
LONGEST value
= (var.type () == var_uinteger
? static_cast<LONGEST> (var.get<unsigned int> ())
: static_cast<LONGEST> (var.get<int> ()));
if (var.extra_literals () != nullptr)
for (const literal_def *l = var.extra_literals ();
l->literal != nullptr;
l++)
if (value == l->use)
{
if (strcmp (l->literal, "unlimited") == 0)
{
/* Compatibility hack for API brokenness. */
if (var.type () == var_pinteger
&& l->val.has_value ()
&& *l->val == -1)
value = -1;
else
Py_RETURN_NONE;
}
else if (l->val.has_value ())
value = *l->val;
else
return host_string_to_python_string (l->literal).release ();
}
if (var.type () == var_uinteger)
return
gdb_py_object_from_ulongest
(static_cast<unsigned int> (value)).release ();
else
return
gdb_py_object_from_longest
(static_cast<int> (value)).release ();
}
}
return PyErr_Format (PyExc_RuntimeError,
_("Programmer error: unhandled type."));
}
/* A Python function which returns a gdb parameter's value as a Python
value. */
static PyObject *
gdbpy_parameter (PyObject *self, PyObject *args)
{
struct cmd_list_element *alias, *prefix, *cmd;
const char *arg;
int found = -1;
if (! PyArg_ParseTuple (args, "s", &arg))
return NULL;
std::string newarg = std::string ("show ") + arg;
try
{
found = lookup_cmd_composition (newarg.c_str (), &alias, &prefix, &cmd);
}
catch (const gdb_exception &ex)
{
return gdbpy_handle_gdb_exception (nullptr, ex);
}
if (cmd == CMD_LIST_AMBIGUOUS)
return PyErr_Format (PyExc_RuntimeError,
_("Parameter `%s' is ambiguous."), arg);
else if (!found)
return PyErr_Format (PyExc_RuntimeError,
_("Could not find parameter `%s'."), arg);
if (!cmd->var.has_value ())
return PyErr_Format (PyExc_RuntimeError,
_("`%s' is not a parameter."), arg);
return gdbpy_parameter_value (*cmd->var);
}
/* Wrapper for target_charset. */
static PyObject *
gdbpy_target_charset (PyObject *self, PyObject *args)
{
const char *cset = target_charset (gdbpy_enter::get_gdbarch ());
return PyUnicode_Decode (cset, strlen (cset), host_charset (), NULL);
}
/* Wrapper for target_wide_charset. */
static PyObject *
gdbpy_target_wide_charset (PyObject *self, PyObject *args)
{
const char *cset = target_wide_charset (gdbpy_enter::get_gdbarch ());
return PyUnicode_Decode (cset, strlen (cset), host_charset (), NULL);
}
/* Implement gdb.host_charset(). */
static PyObject *
gdbpy_host_charset (PyObject *self, PyObject *args)
{
const char *cset = host_charset ();
return PyUnicode_Decode (cset, strlen (cset), host_charset (), NULL);
}
/* A Python function which evaluates a string using the gdb CLI. */
static PyObject *
execute_gdb_command (PyObject *self, PyObject *args, PyObject *kw)
{
const char *arg;
PyObject *from_tty_obj = nullptr;
PyObject *to_string_obj = nullptr;
PyObject *styling = nullptr;
static const char *keywords[]
= { "command", "from_tty", "to_string", "styling", nullptr };
if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "s|O!O!O!", keywords, &arg,
&PyBool_Type, &from_tty_obj,
&PyBool_Type, &to_string_obj,
&PyBool_Type, &styling))
return nullptr;
bool from_tty = false;
if (from_tty_obj != nullptr)
{
int cmp = PyObject_IsTrue (from_tty_obj);
if (cmp < 0)
return nullptr;
from_tty = (cmp != 0);
}
bool to_string = false;
if (to_string_obj != nullptr)
{
int cmp = PyObject_IsTrue (to_string_obj);
if (cmp < 0)
return nullptr;
to_string = (cmp != 0);
}
bool styling_p = !to_string;
if (styling != nullptr)
{
int cmp = PyObject_IsTrue (styling);
if (cmp < 0)
return nullptr;
styling_p = (cmp != 0);
}
std::string to_string_res;
scoped_restore preventer = prevent_dont_repeat ();
/* If the executed command raises an exception, we may have to
enable stdin and recover the GDB prompt.
Stdin should not be re-enabled if it is already blocked because,
for example, we are running a command in the context of a
synchronous execution command ("run", "continue", etc.). Like
this:
User runs "continue"
--> command blocks the prompt
--> Python API is invoked, e.g. via events
--> gdb.execute(C) invoked inside Python
--> command C raises an exception
In this case case, GDB would go back to the top "continue" command
and move on with its normal course of execution. That is, it
would enable stdin in the way it normally does.
Similarly, if the command we are about to execute enables the
stdin while we are still in the context of a synchronous
execution command, we would be displaying the prompt too early,
before the surrounding command completes.
For these reasons, we keep the prompt blocked, if it already is. */
bool prompt_was_blocked = (current_ui->prompt_state == PROMPT_BLOCKED);
scoped_restore save_prompt_state
= make_scoped_restore (¤t_ui->keep_prompt_blocked,
prompt_was_blocked);
try
{
gdbpy_allow_threads allow_threads;
struct interp *interp;
std::string arg_copy = arg;
bool first = true;
char *save_ptr = nullptr;
auto reader
= [&] (std::string &buffer)
{
const char *result = strtok_r (first ? &arg_copy[0] : nullptr,
"\n", &save_ptr);
first = false;
return result;
};
counted_command_line lines = read_command_lines_1 (reader, 1, nullptr);
{
scoped_restore save_async = make_scoped_restore (¤t_ui->async,
0);
scoped_restore save_uiout = make_scoped_restore (¤t_uiout);
/* If the Python 'styling' argument was False then temporarily
disable styling. Otherwise, don't do anything, styling could
already be disabled for some other reason, we shouldn't override
that and force styling on. */
std::optional<scoped_disable_styling> disable_styling;
if (!styling_p)
disable_styling.emplace ();
/* Use the console interpreter uiout to have the same print format
for console or MI. */
interp = interp_lookup (current_ui, "console");
current_uiout = interp->interp_ui_out ();
if (to_string)
{
/* Pass 'true' here to always request styling, however, if
the scoped_disable_styling disabled styling, or the user
has globally disabled styling, then the output will not be
styled. */
to_string_res
= execute_control_commands_to_string (lines.get (), from_tty,
true);
}
else
execute_control_commands (lines.get (), from_tty);
}
/* Do any commands attached to breakpoint we stopped at. */
bpstat_do_actions ();
}
catch (const gdb_exception &except)
{
/* If an exception occurred then we won't hit normal_stop (), or have
an exception reach the top level of the event loop, which are the
two usual places in which stdin would be re-enabled. So, before we
convert the exception and continue back in Python, we should
re-enable stdin here. */
async_enable_stdin ();
return gdbpy_handle_gdb_exception (nullptr, except);
}
if (to_string)
return PyUnicode_Decode (to_string_res.c_str (), to_string_res.size (),
host_charset (), nullptr);
Py_RETURN_NONE;
}
/* Implementation of Python rbreak command. Take a REGEX and
optionally a MINSYMS, THROTTLE and SYMTABS keyword and return a
Python list that contains newly set breakpoints that match that
criteria. REGEX refers to a GDB format standard regex pattern of
symbols names to search; MINSYMS is an optional boolean (default
False) that indicates if the function should search GDB's minimal
symbols; THROTTLE is an optional integer (default unlimited) that
indicates the maximum amount of breakpoints allowable before the
function exits (note, if the throttle bound is passed, no
breakpoints will be set and a runtime error returned); SYMTABS is
an optional Python iterable that contains a set of gdb.Symtabs to
constrain the search within. */
static PyObject *
gdbpy_rbreak (PyObject *self, PyObject *args, PyObject *kw)
{
char *regex = NULL;
std::vector<symbol_search> symbols;
unsigned long count = 0;
PyObject *symtab_list = NULL;
PyObject *minsyms_p_obj = NULL;
int minsyms_p = 0;
unsigned int throttle = 0;
static const char *keywords[] = {"regex","minsyms", "throttle",
"symtabs", NULL};
if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "s|O!IO", keywords,
®ex, &PyBool_Type,
&minsyms_p_obj, &throttle,
&symtab_list))
return NULL;
/* Parse minsyms keyword. */
if (minsyms_p_obj != NULL)
{
int cmp = PyObject_IsTrue (minsyms_p_obj);
if (cmp < 0)
return NULL;
minsyms_p = cmp;
}
global_symbol_searcher spec (SEARCH_FUNCTION_DOMAIN, regex);
/* The "symtabs" keyword is any Python iterable object that returns
a gdb.Symtab on each iteration. If specified, iterate through
the provided gdb.Symtabs and extract their full path. As
python_string_to_target_string returns a
gdb::unique_xmalloc_ptr<char> and a vector containing these types
cannot be coerced to a const char **p[] via the vector.data call,
release the value from the unique_xmalloc_ptr and place it in a
simple type symtab_list_type (which holds the vector and a
destructor that frees the contents of the allocated strings. */
if (symtab_list != NULL)
{
gdbpy_ref<> iter (PyObject_GetIter (symtab_list));
if (iter == NULL)
return NULL;
while (true)
{
gdbpy_ref<> next (PyIter_Next (iter.get ()));
if (next == NULL)
{
if (PyErr_Occurred ())
return NULL;
break;
}
gdbpy_ref<> obj_name (PyObject_GetAttrString (next.get (),
"filename"));
if (obj_name == NULL)
return NULL;
/* Is the object file still valid? */
if (obj_name == Py_None)
continue;
gdb::unique_xmalloc_ptr<char> filename =
python_string_to_target_string (obj_name.get ());
if (filename == NULL)
return NULL;
spec.add_filename (std::move (filename));
}
}
/* The search spec. */
symbols = spec.search ();
/* Count the number of symbols (both symbols and optionally minimal
symbols) so we can correctly check the throttle limit. */
for (const symbol_search &p : symbols)
{
/* Minimal symbols included? */
if (minsyms_p)
{
if (p.msymbol.minsym != NULL)
count++;
}
if (p.symbol != NULL)
count++;
}
/* Check throttle bounds and exit if in excess. */
if (throttle != 0 && count > throttle)
{
PyErr_SetString (PyExc_RuntimeError,
_("Number of breakpoints exceeds throttled maximum."));
return NULL;
}
gdbpy_ref<> return_list (PyList_New (0));
if (return_list == NULL)
return NULL;
/* Construct full path names for symbols and call the Python
breakpoint constructor on the resulting names. Be tolerant of
individual breakpoint failures. */
for (const symbol_search &p : symbols)
{
std::string symbol_name;
/* Skipping minimal symbols? */
if (minsyms_p == 0)
if (p.msymbol.minsym != NULL)
continue;
if (p.msymbol.minsym == NULL)
{
struct symtab *symtab = p.symbol->symtab ();
const char *fullname = symtab_to_fullname (symtab);
symbol_name = fullname;
symbol_name += ":";
symbol_name += p.symbol->linkage_name ();
}
else
symbol_name = p.msymbol.minsym->linkage_name ();
gdbpy_ref<> argList (Py_BuildValue("(s)", symbol_name.c_str ()));
gdbpy_ref<> obj (PyObject_CallObject ((PyObject *)
&breakpoint_object_type,
argList.get ()));
/* Tolerate individual breakpoint failures. */
if (obj == NULL)
gdbpy_print_stack ();
else
{
if (PyList_Append (return_list.get (), obj.get ()) == -1)
return NULL;
}
}
return return_list.release ();
}
/* A Python function which is a wrapper for decode_line_1. */
static PyObject *
gdbpy_decode_line (PyObject *self, PyObject *args)
{
const char *arg = NULL;
gdbpy_ref<> result;
gdbpy_ref<> unparsed;
location_spec_up locspec;
if (! PyArg_ParseTuple (args, "|s", &arg))
return NULL;
/* Treat a string consisting of just whitespace the same as
NULL. */
if (arg != NULL)
{
arg = skip_spaces (arg);
if (*arg == '\0')
arg = NULL;
}
if (arg != NULL)
locspec = string_to_location_spec_basic (&arg, current_language,
symbol_name_match_type::WILD);
std::vector<symtab_and_line> decoded_sals;
symtab_and_line def_sal;
gdb::array_view<symtab_and_line> sals;
try
{
if (locspec != NULL)