Home | History | Annotate | Line # | Download | only in guile
scm-utils.c revision 1.1.1.7
      1 /* General utility routines for GDB/Scheme code.
      2 
      3    Copyright (C) 2014-2023 Free Software Foundation, Inc.
      4 
      5    This file is part of GDB.
      6 
      7    This program is free software; you can redistribute it and/or modify
      8    it under the terms of the GNU General Public License as published by
      9    the Free Software Foundation; either version 3 of the License, or
     10    (at your option) any later version.
     11 
     12    This program is distributed in the hope that it will be useful,
     13    but WITHOUT ANY WARRANTY; without even the implied warranty of
     14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     15    GNU General Public License for more details.
     16 
     17    You should have received a copy of the GNU General Public License
     18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
     19 
     20 /* See README file in this directory for implementation notes, coding
     21    conventions, et.al.  */
     22 
     23 #include "defs.h"
     24 #include "guile-internal.h"
     25 
     26 /* Define VARIABLES in the gdb module.  */
     27 
     28 void
     29 gdbscm_define_variables (const scheme_variable *variables, int is_public)
     30 {
     31   const scheme_variable *sv;
     32 
     33   for (sv = variables; sv->name != NULL; ++sv)
     34     {
     35       scm_c_define (sv->name, sv->value);
     36       if (is_public)
     37 	scm_c_export (sv->name, NULL);
     38     }
     39 }
     40 
     41 /* Define FUNCTIONS in the gdb module.  */
     42 
     43 void
     44 gdbscm_define_functions (const scheme_function *functions, int is_public)
     45 {
     46   const scheme_function *sf;
     47 
     48   for (sf = functions; sf->name != NULL; ++sf)
     49     {
     50       SCM proc = scm_c_define_gsubr (sf->name, sf->required, sf->optional,
     51 				     sf->rest, sf->func);
     52 
     53       scm_set_procedure_property_x (proc, gdbscm_documentation_symbol,
     54 				    gdbscm_scm_from_c_string (sf->doc_string));
     55       if (is_public)
     56 	scm_c_export (sf->name, NULL);
     57     }
     58 }
     59 
     60 /* Define CONSTANTS in the gdb module.  */
     61 
     62 void
     63 gdbscm_define_integer_constants (const scheme_integer_constant *constants,
     64 				 int is_public)
     65 {
     66   const scheme_integer_constant *sc;
     67 
     68   for (sc = constants; sc->name != NULL; ++sc)
     69     {
     70       scm_c_define (sc->name, scm_from_int (sc->value));
     71       if (is_public)
     72 	scm_c_export (sc->name, NULL);
     73     }
     74 }
     75 
     76 /* scm_printf, alas it doesn't exist.  */
     78 
     79 void
     80 gdbscm_printf (SCM port, const char *format, ...)
     81 {
     82   va_list args;
     83 
     84   va_start (args, format);
     85   std::string string = string_vprintf (format, args);
     86   va_end (args);
     87   scm_puts (string.c_str (), port);
     88 }
     89 
     90 /* Utility for calling from gdb to "display" an SCM object.  */
     91 
     92 void
     93 gdbscm_debug_display (SCM obj)
     94 {
     95   SCM port = scm_current_output_port ();
     96 
     97   scm_display (obj, port);
     98   scm_newline (port);
     99   scm_force_output (port);
    100 }
    101 
    102 /* Utility for calling from gdb to "write" an SCM object.  */
    103 
    104 void
    105 gdbscm_debug_write (SCM obj)
    106 {
    107   SCM port = scm_current_output_port ();
    108 
    109   scm_write (obj, port);
    110   scm_newline (port);
    111   scm_force_output (port);
    112 }
    113 
    114 /* Subroutine of gdbscm_parse_function_args to simplify it.
    116    Return the number of keyword arguments.  */
    117 
    118 static int
    119 count_keywords (const SCM *keywords)
    120 {
    121   int i;
    122 
    123   if (keywords == NULL)
    124     return 0;
    125   for (i = 0; keywords[i] != SCM_BOOL_F; ++i)
    126     continue;
    127 
    128   return i;
    129 }
    130 
    131 /* Subroutine of gdbscm_parse_function_args to simplify it.
    132    Validate an argument format string.
    133    The result is a boolean indicating if "." was seen.  */
    134 
    135 static int
    136 validate_arg_format (const char *format)
    137 {
    138   const char *p;
    139   int length = strlen (format);
    140   int optional_position = -1;
    141   int keyword_position = -1;
    142   int dot_seen = 0;
    143 
    144   gdb_assert (length > 0);
    145 
    146   for (p = format; *p != '\0'; ++p)
    147     {
    148       switch (*p)
    149 	{
    150 	case 's':
    151 	case 't':
    152 	case 'i':
    153 	case 'u':
    154 	case 'l':
    155 	case 'n':
    156 	case 'L':
    157 	case 'U':
    158 	case 'O':
    159 	  break;
    160 	case '|':
    161 	  gdb_assert (keyword_position < 0);
    162 	  gdb_assert (optional_position < 0);
    163 	  optional_position = p - format;
    164 	  break;
    165 	case '#':
    166 	  gdb_assert (keyword_position < 0);
    167 	  keyword_position = p - format;
    168 	  break;
    169 	case '.':
    170 	  gdb_assert (p[1] == '\0');
    171 	  dot_seen = 1;
    172 	  break;
    173 	default:
    174 	  gdb_assert_not_reached ("invalid argument format character");
    175 	}
    176     }
    177 
    178   return dot_seen;
    179 }
    180 
    181 /* Our version of SCM_ASSERT_TYPE that calls gdbscm_make_type_error.  */
    182 #define CHECK_TYPE(ok, arg, position, func_name, expected_type)		\
    183   do {									\
    184     if (!(ok))								\
    185       {									\
    186 	return gdbscm_make_type_error ((func_name), (position), (arg),	\
    187 				       (expected_type));		\
    188       }									\
    189   } while (0)
    190 
    191 /* Subroutine of gdbscm_parse_function_args to simplify it.
    192    Check the type of ARG against FORMAT_CHAR and extract the value.
    193    POSITION is the position of ARG in the argument list.
    194    The result is #f upon success or a <gdb:exception> object.  */
    195 
    196 static SCM
    197 extract_arg (char format_char, SCM arg, void *argp,
    198 	     const char *func_name, int position)
    199 {
    200   switch (format_char)
    201     {
    202     case 's':
    203       {
    204 	char **arg_ptr = (char **) argp;
    205 
    206 	CHECK_TYPE (gdbscm_is_true (scm_string_p (arg)), arg, position,
    207 		    func_name, _("string"));
    208 	*arg_ptr = gdbscm_scm_to_c_string (arg).release ();
    209 	break;
    210       }
    211     case 't':
    212       {
    213 	int *arg_ptr = (int *) argp;
    214 
    215 	/* While in Scheme, anything non-#f is "true", we're strict.  */
    216 	CHECK_TYPE (gdbscm_is_bool (arg), arg, position, func_name,
    217 		    _("boolean"));
    218 	*arg_ptr = gdbscm_is_true (arg);
    219 	break;
    220       }
    221     case 'i':
    222       {
    223 	int *arg_ptr = (int *) argp;
    224 
    225 	CHECK_TYPE (scm_is_signed_integer (arg, INT_MIN, INT_MAX),
    226 		    arg, position, func_name, _("int"));
    227 	*arg_ptr = scm_to_int (arg);
    228 	break;
    229       }
    230     case 'u':
    231       {
    232 	int *arg_ptr = (int *) argp;
    233 
    234 	CHECK_TYPE (scm_is_unsigned_integer (arg, 0, UINT_MAX),
    235 		    arg, position, func_name, _("unsigned int"));
    236 	*arg_ptr = scm_to_uint (arg);
    237 	break;
    238       }
    239     case 'l':
    240       {
    241 	long *arg_ptr = (long *) argp;
    242 
    243 	CHECK_TYPE (scm_is_signed_integer (arg, LONG_MIN, LONG_MAX),
    244 		    arg, position, func_name, _("long"));
    245 	*arg_ptr = scm_to_long (arg);
    246 	break;
    247       }
    248     case 'n':
    249       {
    250 	unsigned long *arg_ptr = (unsigned long *) argp;
    251 
    252 	CHECK_TYPE (scm_is_unsigned_integer (arg, 0, ULONG_MAX),
    253 		    arg, position, func_name, _("unsigned long"));
    254 	*arg_ptr = scm_to_ulong (arg);
    255 	break;
    256       }
    257     case 'L':
    258       {
    259 	LONGEST *arg_ptr = (LONGEST *) argp;
    260 
    261 	CHECK_TYPE (scm_is_signed_integer (arg, INT64_MIN, INT64_MAX),
    262 		    arg, position, func_name, _("LONGEST"));
    263 	*arg_ptr = gdbscm_scm_to_longest (arg);
    264 	break;
    265       }
    266     case 'U':
    267       {
    268 	ULONGEST *arg_ptr = (ULONGEST *) argp;
    269 
    270 	CHECK_TYPE (scm_is_unsigned_integer (arg, 0, UINT64_MAX),
    271 		    arg, position, func_name, _("ULONGEST"));
    272 	*arg_ptr = gdbscm_scm_to_ulongest (arg);
    273 	break;
    274       }
    275     case 'O':
    276       {
    277 	SCM *arg_ptr = (SCM *) argp;
    278 
    279 	*arg_ptr = arg;
    280 	break;
    281       }
    282     default:
    283       gdb_assert_not_reached ("invalid argument format character");
    284     }
    285 
    286   return SCM_BOOL_F;
    287 }
    288 
    289 #undef CHECK_TYPE
    290 
    291 /* Look up KEYWORD in KEYWORD_LIST.
    292    The result is the index of the keyword in the list or -1 if not found.  */
    293 
    294 static int
    295 lookup_keyword (const SCM *keyword_list, SCM keyword)
    296 {
    297   int i = 0;
    298 
    299   while (keyword_list[i] != SCM_BOOL_F)
    300     {
    301       if (scm_is_eq (keyword_list[i], keyword))
    302 	return i;
    303       ++i;
    304     }
    305 
    306   return -1;
    307 }
    308 
    309 
    310 /* Helper for gdbscm_parse_function_args that does most of the work,
    311    in a separate function wrapped with gdbscm_wrap so that we can use
    312    non-trivial-dtor objects here.  The result is #f upon success or a
    313    <gdb:exception> object otherwise.  */
    314 
    315 static SCM
    316 gdbscm_parse_function_args_1 (const char *func_name,
    317 			      int beginning_arg_pos,
    318 			      const SCM *keywords,
    319 			      const char *format, va_list args)
    320 {
    321   const char *p;
    322   int i, have_rest, num_keywords, position;
    323   int have_optional = 0;
    324   SCM status;
    325   SCM rest = SCM_EOL;
    326   /* Keep track of malloc'd strings.  We need to free them upon error.  */
    327   std::vector<char *> allocated_strings;
    328 
    329   have_rest = validate_arg_format (format);
    330   num_keywords = count_keywords (keywords);
    331 
    332   p = format;
    333   position = beginning_arg_pos;
    334 
    335   /* Process required, optional arguments.  */
    336 
    337   while (*p && *p != '#' && *p != '.')
    338     {
    339       SCM arg;
    340       void *arg_ptr;
    341 
    342       if (*p == '|')
    343 	{
    344 	  have_optional = 1;
    345 	  ++p;
    346 	  continue;
    347 	}
    348 
    349       arg = va_arg (args, SCM);
    350       if (!have_optional || !SCM_UNBNDP (arg))
    351 	{
    352 	  arg_ptr = va_arg (args, void *);
    353 	  status = extract_arg (*p, arg, arg_ptr, func_name, position);
    354 	  if (!gdbscm_is_false (status))
    355 	    goto fail;
    356 	  if (*p == 's')
    357 	    allocated_strings.push_back (*(char **) arg_ptr);
    358 	}
    359       ++p;
    360       ++position;
    361     }
    362 
    363   /* Process keyword arguments.  */
    364 
    365   if (have_rest || num_keywords > 0)
    366     rest = va_arg (args, SCM);
    367 
    368   if (num_keywords > 0)
    369     {
    370       SCM *keyword_args = XALLOCAVEC (SCM, num_keywords);
    371       int *keyword_positions = XALLOCAVEC (int, num_keywords);
    372 
    373       gdb_assert (*p == '#');
    374       ++p;
    375 
    376       for (i = 0; i < num_keywords; ++i)
    377 	{
    378 	  keyword_args[i] = SCM_UNSPECIFIED;
    379 	  keyword_positions[i] = -1;
    380 	}
    381 
    382       while (scm_is_pair (rest)
    383 	     && scm_is_keyword (scm_car (rest)))
    384 	{
    385 	  SCM keyword = scm_car (rest);
    386 
    387 	  i = lookup_keyword (keywords, keyword);
    388 	  if (i < 0)
    389 	    {
    390 	      status = gdbscm_make_error (scm_arg_type_key, func_name,
    391 					  _("Unrecognized keyword: ~a"),
    392 					  scm_list_1 (keyword), keyword);
    393 	      goto fail;
    394 	    }
    395 	  if (!scm_is_pair (scm_cdr (rest)))
    396 	    {
    397 	      status = gdbscm_make_error
    398 		(scm_arg_type_key, func_name,
    399 		 _("Missing value for keyword argument"),
    400 		 scm_list_1 (keyword), keyword);
    401 	      goto fail;
    402 	    }
    403 	  keyword_args[i] = scm_cadr (rest);
    404 	  keyword_positions[i] = position + 1;
    405 	  rest = scm_cddr (rest);
    406 	  position += 2;
    407 	}
    408 
    409       for (i = 0; i < num_keywords; ++i)
    410 	{
    411 	  int *arg_pos_ptr = va_arg (args, int *);
    412 	  void *arg_ptr = va_arg (args, void *);
    413 	  SCM arg = keyword_args[i];
    414 
    415 	  if (! scm_is_eq (arg, SCM_UNSPECIFIED))
    416 	    {
    417 	      *arg_pos_ptr = keyword_positions[i];
    418 	      status = extract_arg (p[i], arg, arg_ptr, func_name,
    419 				    keyword_positions[i]);
    420 	      if (!gdbscm_is_false (status))
    421 		goto fail;
    422 	      if (p[i] == 's')
    423 		allocated_strings.push_back (*(char **) arg_ptr);
    424 	    }
    425 	}
    426     }
    427 
    428   /* Process "rest" arguments.  */
    429 
    430   if (have_rest)
    431     {
    432       if (num_keywords > 0)
    433 	{
    434 	  SCM *rest_ptr = va_arg (args, SCM *);
    435 
    436 	  *rest_ptr = rest;
    437 	}
    438     }
    439   else
    440     {
    441       if (! scm_is_null (rest))
    442 	{
    443 	  status = gdbscm_make_error (scm_args_number_key, func_name,
    444 				      _("Too many arguments"),
    445 				      SCM_EOL, SCM_BOOL_F);
    446 	  goto fail;
    447 	}
    448     }
    449 
    450   /* Return anything not-an-exception.  */
    451   return SCM_BOOL_F;
    452 
    453  fail:
    454   for (char *ptr : allocated_strings)
    455     xfree (ptr);
    456 
    457   /* Return the exception, which gdbscm_wrap takes care of
    458      throwing.  */
    459   return status;
    460 }
    461 
    462 /* Utility to parse required, optional, and keyword arguments to Scheme
    463    functions.  Modelled on PyArg_ParseTupleAndKeywords, but no attempt is made
    464    at similarity or functionality.
    465    There is no result, if there's an error a Scheme exception is thrown.
    466 
    467    Guile provides scm_c_bind_keyword_arguments, and feel free to use it.
    468    This is for times when we want a bit more parsing.
    469 
    470    BEGINNING_ARG_POS is the position of the first argument passed to this
    471    routine.  It should be one of the SCM_ARGn values.  It could be > SCM_ARG1
    472    if the caller chooses not to parse one or more required arguments.
    473 
    474    KEYWORDS may be NULL if there are no keywords.
    475 
    476    FORMAT:
    477    s - string -> char *, malloc'd
    478    t - boolean (gdb uses "t", for biT?) -> int
    479    i - int
    480    u - unsigned int
    481    l - long
    482    n - unsigned long
    483    L - longest
    484    U - unsigned longest
    485    O - random scheme object
    486    | - indicates the next set is for optional arguments
    487    # - indicates the next set is for keyword arguments (must follow |)
    488    . - indicates "rest" arguments are present, this character must appear last
    489 
    490    FORMAT must match the definition from scm_c_{make,define}_gsubr.
    491    Required and optional arguments appear in order in the format string.
    492    Afterwards, keyword-based arguments are processed.  There must be as many
    493    remaining characters in the format string as their are keywords.
    494    Except for "|#.", the number of characters in the format string must match
    495    #required + #optional + #keywords.
    496 
    497    The function is required to be defined in a compatible manner:
    498    #required-args and #optional-arguments must match, and rest-arguments
    499    must be specified if keyword args are desired, and/or regular "rest" args.
    500 
    501    Example:  For this function,
    502    scm_c_define_gsubr ("execute", 2, 3, 1, foo);
    503    the format string + keyword list could be any of:
    504    1) "ss|ttt#tt", { "key1", "key2", NULL }
    505    2) "ss|ttt.", { NULL }
    506    3) "ss|ttt#t.", { "key1", NULL }
    507 
    508    For required and optional args pass the SCM of the argument, and a
    509    pointer to the value to hold the parsed result (type depends on format
    510    char).  After that pass the SCM containing the "rest" arguments followed
    511    by pointers to values to hold parsed keyword arguments, and if specified
    512    a pointer to hold the remaining contents of "rest".
    513 
    514    For keyword arguments pass two pointers: the first is a pointer to an int
    515    that will contain the position of the argument in the arg list, and the
    516    second will contain result of processing the argument.  The int pointed
    517    to by the first value should be initialized to -1.  It can then be used
    518    to tell whether the keyword was present.
    519 
    520    If both keyword and rest arguments are present, the caller must pass a
    521    pointer to contain the new value of rest (after keyword args have been
    522    removed).
    523 
    524    There's currently no way, that I know of, to specify default values for
    525    optional arguments in C-provided functions.  At the moment they're a
    526    work-in-progress.  The caller should test SCM_UNBNDP for each optional
    527    argument.  Unbound optional arguments are ignored.  */
    528 
    529 void
    530 gdbscm_parse_function_args (const char *func_name,
    531 			    int beginning_arg_pos,
    532 			    const SCM *keywords,
    533 			    const char *format, ...)
    534 {
    535   va_list args;
    536   va_start (args, format);
    537 
    538   gdbscm_wrap (gdbscm_parse_function_args_1, func_name,
    539 	       beginning_arg_pos, keywords, format, args);
    540 
    541   va_end (args);
    542 }
    543 
    544 
    545 /* Return longest L as a scheme object.  */
    547 
    548 SCM
    549 gdbscm_scm_from_longest (LONGEST l)
    550 {
    551   return scm_from_int64 (l);
    552 }
    553 
    554 /* Convert scheme object L to LONGEST.
    555    It is an error to call this if L is not an integer in range of LONGEST.
    556    (because the underlying Scheme function will thrown an exception,
    557    which is not part of our contract with the caller).  */
    558 
    559 LONGEST
    560 gdbscm_scm_to_longest (SCM l)
    561 {
    562   return scm_to_int64 (l);
    563 }
    564 
    565 /* Return unsigned longest L as a scheme object.  */
    566 
    567 SCM
    568 gdbscm_scm_from_ulongest (ULONGEST l)
    569 {
    570   return scm_from_uint64 (l);
    571 }
    572 
    573 /* Convert scheme object U to ULONGEST.
    574    It is an error to call this if U is not an integer in range of ULONGEST
    575    (because the underlying Scheme function will thrown an exception,
    576    which is not part of our contract with the caller).  */
    577 
    578 ULONGEST
    579 gdbscm_scm_to_ulongest (SCM u)
    580 {
    581   return scm_to_uint64 (u);
    582 }
    583 
    584 /* Same as scm_dynwind_free, but uses xfree.  */
    585 
    586 void
    587 gdbscm_dynwind_xfree (void *ptr)
    588 {
    589   scm_dynwind_unwind_handler (xfree, ptr, SCM_F_WIND_EXPLICITLY);
    590 }
    591 
    592 /* Return non-zero if PROC is a procedure.  */
    593 
    594 int
    595 gdbscm_is_procedure (SCM proc)
    596 {
    597   return gdbscm_is_true (scm_procedure_p (proc));
    598 }
    599 
    600 /* Same as xstrdup, but the string is allocated on the GC heap.  */
    601 
    602 char *
    603 gdbscm_gc_xstrdup (const char *str)
    604 {
    605   size_t len = strlen (str);
    606   char *result
    607     = (char *) scm_gc_malloc_pointerless (len + 1, "gdbscm_gc_xstrdup");
    608 
    609   strcpy (result, str);
    610   return result;
    611 }
    612 
    613 /* Return a duplicate of ARGV living on the GC heap.  */
    614 
    615 const char * const *
    616 gdbscm_gc_dup_argv (char **argv)
    617 {
    618   int i, len;
    619   size_t string_space;
    620   char *p, **result;
    621 
    622   for (len = 0, string_space = 0; argv[len] != NULL; ++len)
    623     string_space += strlen (argv[len]) + 1;
    624 
    625   /* Allocating "pointerless" works because the pointers are all
    626      self-contained within the object.  */
    627   result = (char **) scm_gc_malloc_pointerless (((len + 1) * sizeof (char *))
    628 						+ string_space,
    629 						"parameter enum list");
    630   p = (char *) &result[len + 1];
    631 
    632   for (i = 0; i < len; ++i)
    633     {
    634       result[i] = p;
    635       strcpy (p, argv[i]);
    636       p += strlen (p) + 1;
    637     }
    638   result[i] = NULL;
    639 
    640   return (const char * const *) result;
    641 }
    642 
    643 /* Return non-zero if the version of Guile being used it at least
    644    MAJOR.MINOR.MICRO.  */
    645 
    646 int
    647 gdbscm_guile_version_is_at_least (int major, int minor, int micro)
    648 {
    649   if (major > gdbscm_guile_major_version)
    650     return 0;
    651   if (major < gdbscm_guile_major_version)
    652     return 1;
    653   if (minor > gdbscm_guile_minor_version)
    654     return 0;
    655   if (minor < gdbscm_guile_minor_version)
    656     return 1;
    657   if (micro > gdbscm_guile_micro_version)
    658     return 0;
    659   return 1;
    660 }
    661