summaryrefslogtreecommitdiff
path: root/gdb/poke.c
blob: cb1bb1431c4bad4226a0b15d6b9d332890258724 (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
/* GDB integration with GNU poke.

   Copyright (C) 2021 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 "defs.h"
#include "command.h"
#include "arch-utils.h"
#include "target.h"
#include "gdbcmd.h"
#include "user-regs.h"
extern "C" {
#include <libpoke.h>
}
#include <ctype.h>
#include <vector>
#include <algorithm>

/* Global poke incremental compiler.  */

static pk_compiler poke_compiler;
static bool poke_compiler_lives = false;

/* Global vector of the Poke code used to define types.  This is
   filled in by poke_add_type and used by poke_dump_types.  */

static std::vector<std::string> type_poke_strings;

/* Terminal hook that flushes the terminal.  */

static void
poke_term_flush (void)
{
  /* Do nothing here.  */
}

/* Terminal hook that prints a fixed string.  */

static void
poke_puts (const char *str)
{
  gdb_printf ("%s", str);
}

/* Terminal hook that prints a formatted string.  */

__attribute__ ((__format__ (__printf__, 1, 2)))
static void
poke_printf (const char *format, ...)
{
  va_list ap;
  char *str;
  int r;

  va_start (ap, format);
  r = vasprintf (&str, format, ap);
  if (r == -1)
    error (_("out of memory in vasprintf")); /* XXX fatal */
  va_end (ap);

  gdb_printf ("%s", str);
  free (str);
}

/* Terminal hook that indents to a given level.  */

static void
poke_term_indent (unsigned int lvl, unsigned int step)
{
  gdb_printf ("\n%*s", (step * lvl), "");
}

/* Terminal hook that starts a styling class.  */

static void
poke_term_class (const char *class_name)
{
  /* Do nothing here.  */
}

/* Terminal hook that finishes a styling class.  */

static int
poke_term_end_class (const char *class_name)
{
  /* Just report success.  */
  return 1;
}

/* Terminal hook that starts a terminal hyperlink.  */

static void
poke_term_hyperlink (const char *url, const char *id)
{
  /* Do nothing here.  */
}

/* Terminal hook that finishes a terminal hyperlink.  */

static int
poke_term_end_hyperlink (void)
{
  /* Just report success.  */
  return 1;
}

/* Terminal hook that returns the current terminal foreground
   color.  */

static struct pk_color
poke_term_get_color (void)
{
  /* Just return the default foreground color.  */
  struct pk_color dfl = {-1,-1,-1};
  return dfl;
}

/* Terminal hook that returns the current terminal background
   color.  */

static struct pk_color
poke_term_get_bgcolor (void)
{
  /* Just return the default background color.  */
  struct pk_color dfl = {-1,-1,-1};
  return dfl;
}

/* Terminal hook that sets the terminal foreground color.  */

static void
poke_term_set_color (struct pk_color color)
{
  /* Do nothing.  */
}

/* Terminal hook that sets the terminal background color.  */

static void
poke_term_set_bgcolor (struct pk_color color)
{
  /* Do nothing.  */
}

/* Implementation of the poke terminal interface, that uses the hooks
   defined above.  */

static struct pk_term_if poke_term_if =
  {
    .flush_fn = poke_term_flush,
    .puts_fn = poke_puts,
    .printf_fn = poke_printf,
    .indent_fn = poke_term_indent,
    .class_fn = poke_term_class,
    .end_class_fn = poke_term_end_class,
    .hyperlink_fn = poke_term_hyperlink,
    .end_hyperlink_fn = poke_term_end_hyperlink,
    .get_color_fn = poke_term_get_color,
    .get_bgcolor_fn = poke_term_get_bgcolor,
    .set_color_fn = poke_term_set_color,
    .set_bgcolor_fn = poke_term_set_bgcolor,
  };

/* Foreign IO device hook that returns an unique name identifying the
   kind of device.  */

static const char *
iod_get_if_name (void)
{
  return "GDB";
}

/* Foreign IO device hook that recognizes whether a given IO space
   handler refer to this kind of device, and normalizes it for further
   use.  */

static char *
iod_handler_normalize (const char *handler, uint64_t flags, int *error)
{
  char *new_handler = nullptr;

  if (strcmp (handler, "<gdb>") == 0)
    new_handler = xstrdup (handler);
  if (error != nullptr)
    *error = PK_IOD_OK;

  return new_handler;
}

/* Foreign IO device hook that opens a new device.  */

static int iod_opened_p = 0;

static void *
iod_open (const char *handler, uint64_t flags, int *error, void *data)
{
  iod_opened_p = 1;
  return &iod_opened_p;
}

/* Foreign IO device hook that reads data from a device.  */

static int
iod_pread (void *dev, void *buf, size_t count, pk_iod_off offset)
{
  int ret = target_read_memory (offset, (gdb_byte *) buf, count);
  return ret == -1 ? PK_IOD_ERROR : PK_IOD_OK;
}

/* Foreign IO device hook that writes data to a device.  */

static int
iod_pwrite (void *dev, const void *buf, size_t count, pk_iod_off offset)
{
  int ret = target_write_memory (offset, (gdb_byte *) buf, count);
  return ret == -1 ? PK_IOD_ERROR : PK_IOD_OK;
}

/* Foreign IO device hook that returns the flags of an IO device. */

static uint64_t
iod_get_flags (void *dev)
{
  return PK_IOS_F_READ | PK_IOS_F_WRITE;
}

/* Foreign IO device hook that returns the size of an IO device, in
   bytes.  */

static pk_iod_off
iod_size (void *dev)
{
  return (gdbarch_addr_bit (get_current_arch ()) == 32
	  ? 0xffffffff : 0xffffffffffffffff);
}

/* Foreign IO device hook that flushes an IO device.  */

static int
iod_flush (void *dev, pk_iod_off offset)
{
  /* Do nothing here.  */
  return PK_OK;
}

/* Foreign IO device hook that closes a given device.  */

static int
iod_close (void *dev)
{
  iod_opened_p = 0;
  return PK_OK;
}

/* Implementation of the poke foreign IO device interface, that uses
   the hooks defined above.  */

static struct pk_iod_if iod_if =
  {
    iod_get_if_name,
    iod_handler_normalize,
    iod_open,
    iod_close,
    iod_pread,
    iod_pwrite,
    iod_get_flags,
    iod_size,
    iod_flush
  };

/* Handler for alien tokens.  */

static struct pk_alien_token alien_token;

static struct pk_alien_token *
poke_alien_token_handler (const char *id, char **errmsg)
{
  /* In GDB alien poke tokens with the form $addr::FOO provide the
     address of the symbol `FOO' as an offset in bytes, i.e. it
     resolves to the GDB value &foo as a Poke offset with unit bytes.

     $FOO, on the other hand, provide the value of the symbol FOO
     incarnated in a proper Poke value.  */

  if (strncmp (id, "addr::", 6) == 0)
    {
      CORE_ADDR addr;

      std::string expr = "&";
      expr += id + 6;

      try
	{
	  addr = parse_and_eval_address (expr.c_str ());
	}
      catch (const gdb_exception_error &except)
	{
	  goto error;
	}

      alien_token.kind = PK_ALIEN_TOKEN_OFFSET;
      alien_token.value.offset.magnitude = addr;
      alien_token.value.offset.width
	= HOST_CHAR_BIT * sizeof (decltype (addr));
      alien_token.value.offset.signed_p = 0;
      alien_token.value.offset.unit
	= (gdbarch_addressable_memory_unit_size (target_gdbarch ())
	   * 8);
    }
  else if (strncmp (id, "reg::", 5) == 0)
    {
      const std::string regname { id + 5 };

      if (!target_has_registers ())
	{
	  *errmsg
	    = xstrdup (string_printf (_("cannot read register '%s': "
					"target has no registers"),
				      regname.c_str ()).c_str ());
	  return nullptr;
	}

      frame_info *frame = get_selected_frame ();
      struct gdbarch *gdbarch = get_frame_arch (frame);
      const int regnum
	= user_reg_map_name_to_regnum (gdbarch, regname.c_str (),
				       regname.length ());

      if (regnum == -1)
	{
	  *errmsg = xstrdup (string_printf (_("unknown register '%s'"),
					    regname.c_str ()).c_str ());
	  return nullptr;
	}

      struct value *reg_value;

      try
	{
	  reg_value = value_of_register (regnum, frame);
	}
      catch (const gdb_exception_error &except)
	{
	  *errmsg
	    = xstrdup (string_printf (_("failed to fetch register '%s' "
					"for selected frame"),
				      regname.c_str ()).c_str ());
	  return nullptr;
	}

      struct type *type = value_type (reg_value);

      alien_token.kind = PK_ALIEN_TOKEN_INTEGER;
      alien_token.value.integer.magnitude
	= value_as_long (reg_value);
      alien_token.value.integer.width
	= TYPE_LENGTH (type) * HOST_CHAR_BIT;
      alien_token.value.integer.signed_p
	= !type->is_unsigned ();
    }
  else
    {
      struct value *value;

      try
	{
	  value = parse_and_eval (id);
	}
      catch (const gdb_exception_error &except)
	{
	  goto error;
	}

      struct type *type = value_type (value);

      if (can_dereference (type))
	{
	  alien_token.kind = PK_ALIEN_TOKEN_OFFSET;
	  alien_token.value.offset.magnitude
	    = value_as_address (value);
	  alien_token.value.offset.width
	    = TYPE_LENGTH (type) * HOST_CHAR_BIT;
	  alien_token.value.offset.signed_p = 0;
	  alien_token.value.offset.unit
	    = gdbarch_addressable_memory_unit_size (target_gdbarch ()) * 8;
	}
      else if (is_integral_type (type))
	{
	  alien_token.kind = PK_ALIEN_TOKEN_INTEGER;
	  alien_token.value.integer.magnitude
	    = value_as_long (value);
	  alien_token.value.integer.width
	    = TYPE_LENGTH (type) * HOST_CHAR_BIT;
	  alien_token.value.integer.signed_p
	    = !type->is_unsigned ();
	}
      else
	goto error;
    }

  *errmsg = nullptr;
  return &alien_token;

 error:
  std::string emsg = "can't access GDB variable '";
  emsg += id;
  emsg += "'";
  *errmsg = xstrdup (emsg.c_str ());
  return nullptr;
}

/* Given a string, prefix it in order to avoid collision with Poke's
   keywords.  */

static const std::vector<std::string> poke_keywords
  {
    "pinned", "struct", "union", "else", "while", "until",
    "for", "in", "where", "if", "sizeof", "fun", "method",
    "type", "var", "unit", "break", "continue", "return",
    "string", "as", "try", "catch", "raise", "void", "any",
    "print", "printf", "isa", "unmap", "big", "little",
    "load", "lambda", "assert",
  };

static std::string
normalize_poke_identifier (std::string prefix, std::string str)
{
  if (std::find (poke_keywords.begin (),
		 poke_keywords.end (),
		 str) != poke_keywords.end ())
    str = prefix + str;

  return str;
}

/* Given a GDB type name, mangle it to a valid Poke type name.  */

static std::string
gdb_type_name_to_poke (std::string str, struct type *type = nullptr)
{
  for (int i = 0; i < str.length (); ++i)
    if (!(str.begin()[i] == '_'
	  || (str.begin()[i] >= 'a' && str.begin()[i] <= 'z')
	  || (str.begin()[i] >= '0' && str.begin()[i] <= '9')
	  || (str.begin()[i] >= 'A' && str.begin()[i] <= 'Z')))
      str.begin()[i] = '_';

  if (type)
    {
      /* Prepend struct and union tags with suitable prefixes.  This
	 is to avoid ending with recursive typedefs in C programs.  */
      if (type->code () == TYPE_CODE_STRUCT)
	str = "struct_" + str;
      else if (type->code () == TYPE_CODE_UNION)
	str = "union_" + str;
    }

  return str;
}

/* Command to feed the poke compiler with the definition of some given
   GDB type.  */

static void poke_command (const char *args, int from_tty);

static std::string
poke_add_type (struct type *type)
{
  std::string type_name;
  std::string str = "";

  if (type != nullptr)
    {
      if (type->name () != nullptr)
	type_name = type->name ();

      /* Do not try to add a type that is already defined.  */
      if (type_name != ""
	  && pk_decl_p (poke_compiler,
			gdb_type_name_to_poke (type_name, type).c_str (),
			PK_DECL_KIND_TYPE))
	return type_name;

      switch (type->code ())
	{
	case TYPE_CODE_PTR:
	  {
	    str = ("offset<uint<"
		   + (std::to_string (TYPE_LENGTH (type) * HOST_CHAR_BIT))
		   + ">,B>");
	    break;
	  }
	case TYPE_CODE_TYPEDEF:
	  {
	    struct type *target_type = check_typedef (type);
	    std::string target_type_code = poke_add_type (target_type);

	    if (target_type_code == "")
	      goto skip;

	    if (target_type->name () != nullptr)
	      str += gdb_type_name_to_poke (target_type->name (), target_type);
	    else
	      str += target_type_code;
	    break;
	  }
	case TYPE_CODE_INT:
	  {
	    size_t type_length = TYPE_LENGTH (type) * HOST_CHAR_BIT;

	    if (type_length > 64)
	      goto skip;

	    if (type->is_unsigned ())
	      str += "u";
	    str += "int<";
	    str += std::to_string (type_length);
	    str += ">";
	    break;
	  }
	case TYPE_CODE_ARRAY:
	  {
	    struct type *target_type = TYPE_TARGET_TYPE (type);
	    size_t target_type_length = TYPE_LENGTH (target_type);
	    std::string target_type_code
	      = poke_add_type (target_type);

	    if (target_type_code == "")
	      goto skip;

	    if (target_type->name ())
	      str = gdb_type_name_to_poke (target_type->name (), target_type);
	    else
	      str = target_type_code;

	    str += "[";
	    str += std::to_string (TYPE_LENGTH (type) / target_type_length);
	    str += "]";
	    break;
	  }
	case TYPE_CODE_STRUCT:
	  {
	    size_t natural_bitpos = 0;
	    str += "struct {";

	    for (int idx = 0; idx < type->num_fields (); idx++)
	      {
		std::string field_name
		  = normalize_poke_identifier ("__f",
					       type->field (idx).name ());
		struct type *field_type
		  = check_typedef (type->field (idx).type ());
		size_t field_bitpos = type->field (idx).loc_bitpos ();

		if (idx > 0)
		  str += " ";
		if (field_type->name () != nullptr)
		  {
		    if (poke_add_type (field_type) == "")
		      goto skip;
		    str += gdb_type_name_to_poke (field_type->name (),
						  field_type);
		  }
		else
		  {
		    std::string pstr = poke_add_type (field_type);
		    if (pstr == "")
		      goto skip;
		    str += pstr;
		  }
		str += " ";
		if (field_name != "")
		  str += field_name;
		if (field_bitpos != natural_bitpos)
		  {
		    const size_t target_byte_size
		      = (gdbarch_addressable_memory_unit_size (target_gdbarch ())
			 * 8);
		    str += " @ " + (field_bitpos % target_byte_size == 0
				    ? std::to_string (field_bitpos
						      / target_byte_size) + "#B"
				    : std::to_string (field_bitpos) + "#b");
		  }
		str += ";";

		natural_bitpos
		  = field_bitpos + TYPE_LENGTH (field_type) * HOST_CHAR_BIT;
	      }

	    str += "}";
	    break;
	  }
	default:
	  goto skip;
	  break;
	}

      if (type_name != "")
	{
	  std::string poke_type_name
	    = gdb_type_name_to_poke (type_name, type);

	  std::string deftype = "type ";
	  deftype += poke_type_name;
	  deftype += " = ";
	  deftype += str;

	  type_poke_strings.push_back (deftype);
	  poke_command (deftype.c_str(), 0 /* from_tty */);
	  gdb_printf ("added type %s\n", poke_type_name.c_str ());
	}
    }

  return str;

 skip:
  return "";
}

/* Definition of a handler for unhandled Poke exceptions.  */

static const char *poke_exception_handler="\
fun gdb_exception_handler = (Exception exception) void:\
{\
  if (exception.code != EC_exit && exception.code != EC_signal)\
  {\
    print (\"unhandled \"\
           + (exception.name == \"\" ? \"unknown\" : exception.name)\
           + \" exception\n\");\
\
    if (exception.location != \"\" || exception.msg != \"\")\
    {\
      if (exception.location != \"\")\
        print (exception.location + \" \");\
      print (exception.msg + \"\n\");\
    }\
  }\
}";

/* Call the default poke exception handler.  */

static void
poke_handle_exception (pk_val exception)
{
  pk_val handler = pk_decl_val (poke_compiler, "gdb_exception_handler");

  if (handler == PK_NULL)
    error (_("Couldn't get a handler for poke gdb_exception_handler"));
  if (pk_call (poke_compiler, handler, nullptr, nullptr, 1, exception)
      == PK_ERROR)
    error (_("Couldn't call gdb_exception_handler in poke"));
}

/* Start the poke incremental compiler.  */

static void
start_poke (void)
{
  pk_val exit_exception;

  /* Note how we are creating an incremental compiler without the
     standard Poke types (int, etc) because they collide with the C
     types.  */
  poke_compiler = pk_compiler_new_with_flags (&poke_term_if,
					      PK_F_NOSTDTYPES);
  if (poke_compiler == nullptr)
    error (_("Couldn't start the poke incremental compiler."));
  poke_compiler_lives = true;

  /* Install the handler for alien tokens that recognizes GDB
     symbols.  */
  pk_set_alien_token_fn (poke_compiler, poke_alien_token_handler);

  /* Use hexadecimal output by default.  */
  pk_set_obase (poke_compiler, 16);

  /* Use `tree' printing mode by default.  */
  pk_set_omode (poke_compiler, PK_PRINT_TREE);

  /* Define a handler that we will use for processing unhandled Poke
     exceptions.  */
  if (pk_compile_buffer (poke_compiler, poke_exception_handler,
			 nullptr, &exit_exception) != PK_OK
      || exit_exception != PK_NULL)
    error (_("Could not define the Poke default exception handler"));

  /* Install our foreign IO device interface to access the target's
     memory, and open it.  */
  if (pk_register_iod (poke_compiler, &iod_if) != PK_OK)
    error (_("Could not register the foreign IO device interface in poke."));

  if (pk_compile_buffer (poke_compiler, "open (\"<gdb>\");", nullptr,
			 &exit_exception) != PK_OK
      || exit_exception != PK_NULL)
    {
      if (exit_exception != PK_NULL)
	poke_handle_exception (exit_exception);
      error (_("Could not open <gdb>"));
    }

  /* Provide access to pickles installed by poke applications.  */
  pk_val pk_load_path = pk_decl_val (poke_compiler, "load_path");
  std::string load_path = pk_string_str (pk_load_path);
  load_path += ":%DATADIR%/pickles";
  pk_decl_set_val (poke_compiler, "load_path",
		   pk_make_string (load_path.c_str ()));
}

/* Function to finalize the poke subsystem.  This is registered with
   make_final_cleanup in _initialize_poke.  */

static void
poke_finalize (void *arg)
{
  if (poke_compiler_lives)
    {
      pk_val val, exit_exception;
      if (pk_compile_statement (poke_compiler,
				"try close (get_ios); catch if E_no_ios {}",
				nullptr, &val, &exit_exception) != PK_OK
	  || exit_exception != PK_NULL)
	error (_("Error while closing an IOS on exit."));

      pk_compiler_free (poke_compiler);
      poke_compiler_lives = false;
    }
}

/* Command to dump the Poke definition of known types.  */

static void
poke_dump_types (const char *args, int from_tty)
{
  if (!poke_compiler_lives)
    start_poke ();

  for (const std::string &s : type_poke_strings)
    printf ("%s;\n", s.c_str ());
}

/* Commands to add GDB types to the running poke compiler.  */

static void
poke_add_type_command (const char *args, int from_tty)
{
  if (!poke_compiler_lives)
    start_poke ();

  std::string type_name = skip_spaces (args);
  type_name = gdb_type_name_to_poke (type_name);

  expression_up expr = parse_expression (args);
  struct value *val = evaluate_type (expr.get ());
  struct type *type = value_type (val);

  poke_add_type (type);
}

static void
poke_add_types (const char *args, int from_tty)
{
  if (!poke_compiler_lives)
    start_poke ();

  std::string symbol_name_regexp = skip_spaces (args);
  global_symbol_searcher spec (TYPES_DOMAIN, symbol_name_regexp.c_str ());
  std::vector<symbol_search> symbols = spec.search ();
  for (const symbol_search &p : symbols)
    {
      QUIT;

      struct symbol *sym = p.symbol;
      struct type *type = sym->type ();

      if (type)
	poke_add_type (type);
    }
}

/* Command to execute a poke statement or declaration.  */

static void
poke_command (const char *args, int from_tty)
{
  if (!poke_compiler_lives)
    start_poke ();

  int what; /* 0 -> declaration, 1 -> statement */
  const char *end;
  std::string cmd;
  pk_val exit_exception = PK_NULL;

#define IS_COMMAND(input, cmd) \
  (strncmp ((input), (cmd), sizeof (cmd) - 1) == 0 \
   && ((input)[sizeof (cmd) - 1] == ' ' || (input)[sizeof (cmd) - 1] == '\t'))

  args = skip_spaces (args);
  if (args == nullptr)
    return;

  if (IS_COMMAND (args, "fun"))
    {
      what = 0;
      cmd = args;
    }
  else
    {
      if (IS_COMMAND (args, "var")
	  || IS_COMMAND (args, "type")
	  || IS_COMMAND (args, "unit"))
	what = 0;
      else
	what = 1;

      cmd = args;
      cmd += ';';
    }

  pk_set_lexical_cuckolding_p (poke_compiler, 1);

  if (what == 0)
    {
      /* Declaration.  */
      if (pk_compile_buffer (poke_compiler, cmd.c_str (),
			     &end, &exit_exception) != PK_OK
	  || exit_exception != PK_NULL)
	goto error;
    }
  else
    {
      /* Statement.  */
      pk_val val;

      if (pk_compile_statement (poke_compiler, cmd.c_str (), &end,
				&val, &exit_exception) != PK_OK
	  || exit_exception != PK_NULL)
	goto error;

      if (val != PK_NULL)
	{
	  pk_print_val (poke_compiler, val, &exit_exception);
	  poke_puts ("\n");
	}
    }

  pk_set_lexical_cuckolding_p (poke_compiler, 0);
#undef IS_COMMAND
 error:
  if (exit_exception != PK_NULL)
    poke_handle_exception (exit_exception);
}

static struct value *
poke_internal_fn (struct gdbarch *gdbarch,
		  const struct language_defn *language,
		  void *cookie, int argc, struct value **argv)
{
  if (argc != 1)
    error ("_poke_poc requires only one argument");

  struct type *type = value_type (argv[0]);
  if (type->code () != TYPE_CODE_ARRAY
      || TYPE_TARGET_TYPE (type) != builtin_type (gdbarch)->builtin_char)
    error ("_poke_poc's first argument must have type 'const char *'");

  gdb::array_view<const gdb_byte> content = value_contents (argv[0]);
  const char *poke_expr = reinterpret_cast<const char *> (content.begin ());
  const char *poke_end = reinterpret_cast<const char *> (content.end () - 1);
  gdb_assert (*poke_end) == '\0');
  pk_val val;
  pk_val exit_exception = PK_NULL;
  if (pk_compile_statement (poke_compiler, poke_cmd, &poke_end,
			    &val, &exit_exception) != PK_OK
      || exit_exception != PK_NULL)
    {
      poke_handle_exception (exit_exception);
      error ("Error compiling poke call");
    }

  /* Do the best we can to convert a poke value to a GDB value.  */
  switch (pk_val_kind (val))
    {
    case PK_VAL_INT:
    case PK_VAL_UINT:
    default:
      error ("Poke");
    }

  return value_from_longest (builtin_type (gdbarch)->builtin_int, 0);
}

/* Initialize the poke GDB subsystem.  */

void _initialize_poke (void);
void
_initialize_poke ()
{
  add_com ("poke-add-type", class_vars, poke_add_type_command, _("\
Make Poke aware of a GDB type given an expression.\n\
Usage: poke-add-type EXPRESSION\n"));

  add_com ("poke-add-types", class_vars, poke_add_types, _("\
Make Poke aware of GDB types based on a regexp.\n\
Usage: poke-add-type REGEXP\n"));

  add_com ("poke-dump-types", class_vars, poke_dump_types, _("\
Dump the definition of all the GDB types known to poke.\n\
Usage: poke-dump-types\n"));

  add_com ("poke", class_vars, poke_command, _("\
Execute a Poke statement or declaration.\n\
Usage: poke [STMT]\n"));

  add_internal_function ("_poke", _("\
Run the expression in poke", poke_internal_fn, nullptr);

  make_final_cleanup (poke_finalize, nullptr);
}