Code coverage tests

This page documents the degree to which the PARI/GP source code is tested by our public test suite, distributed with the source distribution in directory src/test/. This is measured by the gcov utility; we then process gcov output using the lcov frond-end.

We test a few variants depending on Configure flags on the pari.math.u-bordeaux.fr machine (x86_64 architecture), and agregate them in the final report:

The target is 90% coverage for all mathematical modules (given that branches depending on DEBUGLEVEL or DEBUGMEM are not covered). This script is run to produce the results below.

LCOV - code coverage report
Current view: top level - language - init.c (source / functions) Hit Total Coverage
Test: PARI/GP v2.10.0 lcov report (development 20277-2bd9113) Lines: 841 1177 71.5 %
Date: 2017-02-21 05:49:51 Functions: 101 133 75.9 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /* Copyright (C) 2000-2003  The PARI group.
       2             : 
       3             : This file is part of the PARI/GP package.
       4             : 
       5             : PARI/GP is free software; you can redistribute it and/or modify it under the
       6             : terms of the GNU General Public License as published by the Free Software
       7             : Foundation. It is distributed in the hope that it will be useful, but WITHOUT
       8             : ANY WARRANTY WHATSOEVER.
       9             : 
      10             : Check the License for details. You should have received a copy of it, along
      11             : with the package; see the file 'COPYING'. If not, write to the Free Software
      12             : Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */
      13             : 
      14             : /*******************************************************************/
      15             : /*                                                                 */
      16             : /*        INITIALIZING THE SYSTEM, ERRORS, STACK MANAGEMENT        */
      17             : /*                                                                 */
      18             : /*******************************************************************/
      19             : /* _GNU_SOURCE is needed before first include to get RUSAGE_THREAD */
      20             : #undef _GNU_SOURCE /* avoid warning */
      21             : #define _GNU_SOURCE
      22             : #include <string.h>
      23             : #if defined(_WIN32) || defined(__CYGWIN32__)
      24             : #  include "../systems/mingw/mingw.h"
      25             : #  include <process.h>
      26             : #endif
      27             : #include "paricfg.h"
      28             : #if defined(STACK_CHECK) && !defined(__EMX__)
      29             : #  include <sys/types.h>
      30             : #  include <sys/time.h>
      31             : #  include <sys/resource.h>
      32             : #endif
      33             : #if defined(HAS_WAITPID) && defined(HAS_SETSID)
      34             : #  include <sys/wait.h>
      35             : #endif
      36             : #ifdef HAS_MMAP
      37             : #  include <sys/mman.h>
      38             : #endif
      39             : #if defined(USE_GETTIMEOFDAY) || defined(USE_GETRUSAGE) || defined(USE_TIMES)
      40             : #  include <sys/time.h>
      41             : #endif
      42             : #if defined(USE_GETRUSAGE)
      43             : #  include <sys/resource.h>
      44             : #endif
      45             : #if defined(USE_FTIME) || defined(USE_FTIMEFORWALLTIME)
      46             : #  include <sys/timeb.h>
      47             : #endif
      48             : #if defined(USE_CLOCK_GETTIME) || defined(USE_TIMES)
      49             : #  include <time.h>
      50             : #endif
      51             : #if defined(USE_TIMES)
      52             : #  include <sys/times.h>
      53             : #endif
      54             : #include "pari.h"
      55             : #include "paripriv.h"
      56             : #include "anal.h"
      57             : 
      58             : const double LOG2    = 0.6931471805599453; /* log(2) */
      59             : const double LOG10_2 = 0.3010299956639812; /* log_10(2) */
      60             : const double LOG2_10 = 3.321928094887362;  /* log_2(10) */
      61             : 
      62             : GEN gnil, gen_0, gen_1, gen_m1, gen_2, gen_m2, ghalf, err_e_STACK;
      63             : 
      64             : static const ulong readonly_constants[] = {
      65             :   evaltyp(t_INT) | _evallg(2),  /* gen_0 */
      66             :   evallgefint(2),
      67             :   evaltyp(t_INT) | _evallg(2),  /* gnil */
      68             :   evallgefint(2),
      69             :   evaltyp(t_INT) | _evallg(3),  /* gen_1 */
      70             :   evalsigne(1) | evallgefint(3),
      71             :   1,
      72             :   evaltyp(t_INT) | _evallg(3),  /* gen_2 */
      73             :   evalsigne(1) | evallgefint(3),
      74             :   2,
      75             :   evaltyp(t_INT) | _evallg(3),  /* gen_m1 */
      76             :   evalsigne(-1) | evallgefint(3),
      77             :   1,
      78             :   evaltyp(t_INT) | _evallg(3),  /* gen_m2 */
      79             :   evalsigne(-1) | evallgefint(3),
      80             :   2,
      81             :   evaltyp(t_FRAC) | _evallg(3), /* ghalf */
      82             :   (ulong)(readonly_constants+4),
      83             :   (ulong)(readonly_constants+7)
      84             : };
      85             : static const ulong readonly_err_STACK[] = {
      86             :   evaltyp(t_ERROR) | _evallg(2),
      87             :   e_STACK
      88             : };
      89             : THREAD GEN bernzone, primetab;
      90             : byteptr diffptr;
      91             : FILE    *pari_outfile, *pari_errfile, *pari_logfile, *pari_infile;
      92             : char    *current_logfile, *current_psfile, *pari_datadir;
      93             : long    gp_colors[c_LAST];
      94             : int     disable_color;
      95             : ulong   DEBUGFILES, DEBUGLEVEL, DEBUGMEM;
      96             : long    DEBUGVAR;
      97             : ulong   pari_mt_nbthreads;
      98             : long    precreal;
      99             : ulong   precdl, logstyle;
     100             : gp_data *GP_DATA;
     101             : 
     102             : GEN colormap, pari_graphcolors;
     103             : 
     104             : entree  **varentries;
     105             : THREAD long *varpriority;
     106             : 
     107             : THREAD pari_sp avma;
     108             : THREAD struct pari_mainstack *pari_mainstack;
     109             : 
     110             : static void ** MODULES;
     111             : static pari_stack s_MODULES;
     112             : const long functions_tblsz = 135; /* size of functions_hash */
     113             : entree **functions_hash, **defaults_hash;
     114             : 
     115             : char *(*cb_pari_fgets_interactive)(char *s, int n, FILE *f);
     116             : int (*cb_pari_get_line_interactive)(const char*, const char*, filtre_t *F);
     117             : void (*cb_pari_quit)(long);
     118             : void (*cb_pari_init_histfile)(void);
     119             : void (*cb_pari_ask_confirm)(const char *);
     120             : int  (*cb_pari_handle_exception)(long);
     121             : int  (*cb_pari_err_handle)(GEN);
     122             : int  (*cb_pari_whatnow)(PariOUT *out, const char *, int);
     123             : void (*cb_pari_sigint)(void);
     124             : void (*cb_pari_pre_recover)(long);
     125             : void (*cb_pari_err_recover)(long);
     126             : int (*cb_pari_break_loop)(int);
     127             : int (*cb_pari_is_interactive)(void);
     128             : void (*cb_pari_start_output)();
     129             : 
     130             : const char * pari_library_path = NULL;
     131             : 
     132             : static THREAD GEN global_err_data;
     133             : THREAD jmp_buf *iferr_env;
     134             : const long CATCH_ALL = -1;
     135             : 
     136             : static void pari_init_timer(void);
     137             : 
     138             : /*********************************************************************/
     139             : /*                                                                   */
     140             : /*                       BLOCKS & CLONES                             */
     141             : /*                                                                   */
     142             : /*********************************************************************/
     143             : /*#define DEBUG*/
     144             : static THREAD long next_block;
     145             : static THREAD GEN cur_block; /* current block in block list */
     146             : #ifdef DEBUG
     147             : static THREAD long NUM;
     148             : #endif
     149             : 
     150             : static void
     151       62825 : pari_init_blocks(void)
     152             : {
     153       62825 :   next_block = 0; cur_block = NULL;
     154             : #ifdef DEBUG
     155             :   NUM = 0;
     156             : #endif
     157       62825 : }
     158             : 
     159             : static void
     160       64435 : pari_close_blocks(void)
     161             : {
     162       64435 :   while (cur_block) killblock(cur_block);
     163       64700 : }
     164             : 
     165             : /* Return x, where:
     166             :  * x[-4]: reference count
     167             :  * x[-3]: adress of next block
     168             :  * x[-2]: adress of preceding block.
     169             :  * x[-1]: number of allocated blocs.
     170             :  * x[0..n-1]: malloc-ed memory. */
     171             : GEN
     172   137722386 : newblock(size_t n)
     173             : {
     174   137722386 :   long *x = (long *) pari_malloc((n + BL_HEAD)*sizeof(long)) + BL_HEAD;
     175             : 
     176   137724278 :   bl_refc(x) = 1;
     177   137724278 :   bl_next(x) = NULL;
     178   137724278 :   bl_prev(x) = cur_block;
     179   137724278 :   bl_num(x)  = next_block++;
     180   137724278 :   if (cur_block) bl_next(cur_block) = x;
     181             : #ifdef DEBUG
     182             :   err_printf("+ %ld\n", ++NUM);
     183             : #endif
     184   137724278 :   if (DEBUGMEM)
     185             :   {
     186           0 :     if (!n) pari_warn(warner,"mallocing NULL object in newblock");
     187         200 :     if (DEBUGMEM > 2)
     188           0 :       err_printf("new block, size %6lu (no %ld): %08lx\n", n, next_block-1, x);
     189             :   }
     190   137724478 :   return cur_block = x;
     191             : }
     192             : 
     193             : GEN
     194         297 : gcloneref(GEN x)
     195             : {
     196         297 :   if (isclone(x)) { ++bl_refc(x); return x; }
     197         297 :   else return gclone(x);
     198             : }
     199             : 
     200             : void
     201           0 : gclone_refc(GEN x) { ++bl_refc(x); }
     202             : 
     203             : void
     204   180068537 : gunclone(GEN x)
     205             : {
     206   360137344 :   if (--bl_refc(x) > 0) return;
     207   137732496 :   BLOCK_SIGINT_START;
     208   137733014 :   if (bl_next(x)) bl_prev(bl_next(x)) = bl_prev(x);
     209             :   else
     210             :   {
     211    24653514 :     cur_block = bl_prev(x);
     212    24653514 :     next_block = bl_num(x);
     213             :   }
     214   137733014 :   if (bl_prev(x)) bl_next(bl_prev(x)) = bl_next(x);
     215   137733014 :   if (DEBUGMEM > 2)
     216           0 :     err_printf("killing block (no %ld): %08lx\n", bl_num(x), x);
     217   137733203 :   free((void*)bl_base(x)); /* pari_free not needed: we already block */
     218   137733203 :   BLOCK_SIGINT_END;
     219             : #ifdef DEBUG
     220             :   err_printf("- %ld\n", NUM--);
     221             : #endif
     222             : }
     223             : 
     224             : /* Recursively look for clones in the container and kill them. Then kill
     225             :  * container if clone. SIGINT could be blocked until it returns */
     226             : void
     227  2540593644 : gunclone_deep(GEN x)
     228             : {
     229             :   long i, lx;
     230             :   GEN v;
     231  5081187288 :   if (isclone(x) && bl_refc(x) > 1) { --bl_refc(x); return; }
     232  2519015213 :   BLOCK_SIGINT_START;
     233  2519015213 :   switch(typ(x))
     234             :   {
     235             :     case t_VEC: case t_COL: case t_MAT:
     236    33402989 :       lx = lg(x);
     237    33402989 :       for (i=1;i<lx;i++) gunclone_deep(gel(x,i));
     238    33402989 :       break;
     239             :     case t_LIST:
     240         270 :       v = list_data(x); lx = v? lg(v): 1;
     241         270 :       for (i=1;i<lx;i++) gunclone_deep(gel(v,i));
     242         270 :       if (v) killblock(v);
     243         270 :       break;
     244             :   }
     245  2519015213 :   if (isclone(x)) gunclone(x);
     246  2519015213 :   BLOCK_SIGINT_END;
     247             : }
     248             : 
     249             : int
     250      138860 : pop_entree_block(entree *ep, long loc)
     251             : {
     252      138860 :   GEN x = (GEN)ep->value;
     253      138860 :   if (bl_num(x) < loc) return 0; /* older */
     254         112 :   if (DEBUGMEM>2)
     255           0 :     err_printf("popping %s (block no %ld)\n", ep->name, bl_num(x));
     256         112 :   gunclone_deep(x); return 1;
     257             : }
     258             : 
     259             : /*********************************************************************/
     260             : /*                                                                   */
     261             : /*                       C STACK SIZE CONTROL                        */
     262             : /*                                                                   */
     263             : /*********************************************************************/
     264             : /* Avoid core dump on deep recursion. Adapted Perl code by Dominic Dunlop */
     265             : THREAD void *PARI_stack_limit = NULL;
     266             : 
     267             : #ifdef STACK_CHECK
     268             : 
     269             : #  ifdef __EMX__                                /* Emulate */
     270             : void
     271             : pari_stackcheck_init(void *pari_stack_base)
     272             : {
     273             :   (void) pari_stack_base;
     274             :   if (!pari_stack_base) { PARI_stack_limit = NULL; return; }
     275             :   PARI_stack_limit = get_stack(1./16, 32*1024);
     276             : }
     277             : #  else /* !__EMX__ */
     278             : /* Set PARI_stack_limit to (a little above) the lowest safe address that can be
     279             :  * used on the stack. Leave PARI_stack_limit at its initial value (NULL) to
     280             :  * show no check should be made [init failed]. Assume stack grows downward. */
     281             : void
     282        1420 : pari_stackcheck_init(void *pari_stack_base)
     283             : {
     284             :   struct rlimit rip;
     285             :   ulong size;
     286        1420 :   if (!pari_stack_base) { PARI_stack_limit = NULL; return; }
     287        1420 :   if (getrlimit(RLIMIT_STACK, &rip)) return;
     288        1420 :   size = rip.rlim_cur;
     289        1420 :   if (size == (ulong)RLIM_INFINITY || size > (ulong)pari_stack_base)
     290           0 :     PARI_stack_limit = (void*)(((ulong)pari_stack_base) / 16);
     291             :   else
     292        1420 :     PARI_stack_limit = (void*)((ulong)pari_stack_base - (size/16)*15);
     293             : }
     294             : #  endif /* !__EMX__ */
     295             : 
     296             : #else
     297             : void
     298             : pari_stackcheck_init(void *pari_stack_base)
     299             : {
     300             :   (void) pari_stack_base; PARI_stack_limit = NULL;
     301             : }
     302             : #endif /* STACK_CHECK */
     303             : 
     304             : /*******************************************************************/
     305             : /*                         HEAP TRAVERSAL                          */
     306             : /*******************************************************************/
     307             : struct getheap_t { long n, l; };
     308             : static void
     309        6699 : f_getheap(GEN x, void *D)
     310             : {
     311        6699 :   struct getheap_t *T = (struct getheap_t*)D;
     312        6699 :   T->n++;
     313        6699 :   T->l += gsizeword(x);
     314        6699 : }
     315             : GEN
     316          84 : getheap(void)
     317             : {
     318          84 :   struct getheap_t T = { 0, 0 };
     319          84 :   traverseheap(&f_getheap, &T);
     320          84 :   return mkvec2s(T.n, T.l + BL_HEAD * T.n);
     321             : }
     322             : 
     323             : void
     324          84 : traverseheap( void(*f)(GEN, void *), void *data )
     325             : {
     326             :   GEN x;
     327          84 :   for (x = cur_block; x; x = bl_prev(x)) f(x, data);
     328          84 : }
     329             : 
     330             : /*********************************************************************/
     331             : /*                          DAEMON / FORK                            */
     332             : /*********************************************************************/
     333             : #if defined(HAS_WAITPID) && defined(HAS_SETSID)
     334             : /* Properly fork a process, detaching from main process group without creating
     335             :  * zombies on exit. Parent returns 1, son returns 0 */
     336             : int
     337         508 : pari_daemon(void)
     338             : {
     339         508 :   pid_t pid = fork();
     340        1016 :   switch(pid) {
     341           0 :       case -1: return 1; /* father, fork failed */
     342             :       case 0:
     343         508 :         (void)setsid(); /* son becomes process group leader */
     344         508 :         if (fork()) _exit(0); /* now son exits, also when fork fails */
     345         508 :         break; /* grandson: its father is the son, which exited,
     346             :                 * hence father becomes 'init', that'll take care of it */
     347             :       default: /* father, fork succeeded */
     348         508 :         (void)waitpid(pid,NULL,0); /* wait for son to exit, immediate */
     349         508 :         return 1;
     350             :   }
     351             :   /* grandson */
     352         508 :   return 0;
     353             : }
     354             : #else
     355             : int
     356             : pari_daemon(void)
     357             : {
     358             :   pari_err_IMPL("pari_daemon without waitpid & setsid");
     359             :   return 0;
     360             : }
     361             : #endif
     362             : 
     363             : /*********************************************************************/
     364             : /*                                                                   */
     365             : /*                       SYSTEM INITIALIZATION                       */
     366             : /*                                                                   */
     367             : /*********************************************************************/
     368             : static int try_to_recover = 0;
     369             : THREAD VOLATILE int PARI_SIGINT_block = 0, PARI_SIGINT_pending = 0;
     370             : 
     371             : /*********************************************************************/
     372             : /*                         SIGNAL HANDLERS                           */
     373             : /*********************************************************************/
     374             : static void
     375           0 : dflt_sigint_fun(void) { pari_err(e_MISC, "user interrupt"); }
     376             : 
     377             : #if defined(_WIN32) || defined(__CYGWIN32__)
     378             : int win32ctrlc = 0, win32alrm = 0;
     379             : void
     380             : dowin32ctrlc(void)
     381             : {
     382             :   win32ctrlc = 0;
     383             :   cb_pari_sigint();
     384             : }
     385             : #endif
     386             : 
     387             : static void
     388           0 : pari_handle_SIGINT(void)
     389             : {
     390             : #ifdef _WIN32
     391             :   if (++win32ctrlc >= 5) _exit(3);
     392             : #else
     393           0 :   cb_pari_sigint();
     394             : #endif
     395           0 : }
     396             : 
     397             : typedef void (*pari_sighandler_t)(int);
     398             : 
     399             : pari_sighandler_t
     400       18154 : os_signal(int sig, pari_sighandler_t f)
     401             : {
     402             : #ifdef HAS_SIGACTION
     403             :   struct sigaction sa, oldsa;
     404             : 
     405       18154 :   sa.sa_handler = f;
     406       18154 :   sigemptyset(&sa.sa_mask);
     407       18154 :   sa.sa_flags = SA_NODEFER;
     408             : 
     409       18154 :   if (sigaction(sig, &sa, &oldsa)) return NULL;
     410       18154 :   return oldsa.sa_handler;
     411             : #else
     412             :   return signal(sig,f);
     413             : #endif
     414             : }
     415             : 
     416             : void
     417           0 : pari_sighandler(int sig)
     418             : {
     419             :   const char *msg;
     420             : #ifndef HAS_SIGACTION
     421             :   /*SYSV reset the signal handler in the handler*/
     422             :   (void)os_signal(sig,pari_sighandler);
     423             : #endif
     424           0 :   switch(sig)
     425             :   {
     426             : #ifdef SIGBREAK
     427             :     case SIGBREAK:
     428             :       if (PARI_SIGINT_block==1)
     429             :       {
     430             :         PARI_SIGINT_pending=SIGBREAK;
     431             :         mt_sigint();
     432             :       }
     433             :       else pari_handle_SIGINT();
     434             :       return;
     435             : #endif
     436             : 
     437             : #ifdef SIGINT
     438             :     case SIGINT:
     439           0 :       if (PARI_SIGINT_block==1)
     440             :       {
     441           0 :         PARI_SIGINT_pending=SIGINT;
     442           0 :         mt_sigint();
     443             :       }
     444           0 :       else pari_handle_SIGINT();
     445           0 :       return;
     446             : #endif
     447             : 
     448             : #ifdef SIGSEGV
     449             :     case SIGSEGV:
     450           0 :       msg="PARI/GP (Segmentation Fault)"; break;
     451             : #endif
     452             : #ifdef SIGBUS
     453             :     case SIGBUS:
     454           0 :       msg="PARI/GP (Bus Error)"; break;
     455             : #endif
     456             : #ifdef SIGFPE
     457             :     case SIGFPE:
     458           0 :       msg="PARI/GP (Floating Point Exception)"; break;
     459             : #endif
     460             : 
     461             : #ifdef SIGPIPE
     462             :     case SIGPIPE:
     463             :     {
     464           0 :       pariFILE *f = GP_DATA->pp->file;
     465           0 :       if (f && pari_outfile == f->file)
     466             :       {
     467           0 :         GP_DATA->pp->file = NULL; /* to avoid oo recursion on error */
     468           0 :         pari_outfile = stdout; pari_fclose(f);
     469           0 :         pari_err(e_MISC, "Broken Pipe, resetting file stack...");
     470             :       }
     471             :       return; /* LCOV_EXCL_LINE */
     472             :     }
     473             : #endif
     474             : 
     475           0 :     default: msg="signal handling"; break;
     476             :   }
     477           0 :   pari_err_BUG(msg);
     478             : }
     479             : 
     480             : void
     481        3347 : pari_sig_init(void (*f)(int))
     482             : {
     483             : #ifdef SIGBUS
     484        3347 :   (void)os_signal(SIGBUS,f);
     485             : #endif
     486             : #ifdef SIGFPE
     487        3347 :   (void)os_signal(SIGFPE,f);
     488             : #endif
     489             : #ifdef SIGINT
     490        3347 :   (void)os_signal(SIGINT,f);
     491             : #endif
     492             : #ifdef SIGBREAK
     493             :   (void)os_signal(SIGBREAK,f);
     494             : #endif
     495             : #ifdef SIGPIPE
     496        3347 :   (void)os_signal(SIGPIPE,f);
     497             : #endif
     498             : #ifdef SIGSEGV
     499        3347 :   (void)os_signal(SIGSEGV,f);
     500             : #endif
     501        3347 : }
     502             : 
     503             : /*********************************************************************/
     504             : /*                      STACK AND UNIVERSAL CONSTANTS                */
     505             : /*********************************************************************/
     506             : static void
     507        1420 : init_universal_constants(void)
     508             : {
     509        1420 :   gen_0  = (GEN)readonly_constants;
     510        1420 :   gnil   = (GEN)readonly_constants+2;
     511        1420 :   gen_1  = (GEN)readonly_constants+4;
     512        1420 :   gen_2  = (GEN)readonly_constants+7;
     513        1420 :   gen_m1 = (GEN)readonly_constants+10;
     514        1420 :   gen_m2 = (GEN)readonly_constants+13;
     515        1420 :   ghalf  = (GEN)readonly_constants+16;
     516        1420 :   err_e_STACK = (GEN)readonly_err_STACK;
     517        1420 : }
     518             : 
     519             : static void
     520       63046 : pari_init_errcatch(void)
     521             : {
     522       63046 :   iferr_env = NULL;
     523       63046 :   global_err_data = NULL;
     524       63046 : }
     525             : 
     526             : /*********************************************************************/
     527             : /*                           INIT DEFAULTS                           */
     528             : /*********************************************************************/
     529             : void
     530        1420 : pari_init_defaults(void)
     531             : {
     532             :   long i;
     533        1420 :   initout(1);
     534             : 
     535             : #ifdef LONG_IS_64BIT
     536        1219 :   precreal = 128;
     537             : #else
     538         201 :   precreal = 96;
     539             : #endif
     540             : 
     541        1420 :   precdl = 16;
     542        1420 :   DEBUGFILES = DEBUGLEVEL = DEBUGMEM = 0;
     543        1420 :   disable_color = 1;
     544        1420 :   logstyle = logstyle_none;
     545             : 
     546        1420 :   current_psfile = pari_strdup("pari.ps");
     547        1420 :   current_logfile= pari_strdup("pari.log");
     548        1420 :   pari_logfile = NULL;
     549             : 
     550        1420 :   pari_datadir = os_getenv("GP_DATA_DIR");
     551        1420 :   if (!pari_datadir)
     552             :   {
     553             : #if defined(_WIN32) || defined(__CYGWIN32__)
     554             :     if (paricfg_datadir[0]=='@' && paricfg_datadir[1]==0)
     555             :       pari_datadir = win32_datadir();
     556             :     else
     557             : #endif
     558        1420 :       pari_datadir = pari_strdup(paricfg_datadir);
     559             :   }
     560           0 :   else pari_datadir= pari_strdup(pari_datadir);
     561        1420 :   for (i=0; i<c_LAST; i++) gp_colors[i] = c_NONE;
     562        1420 :   colormap = NULL; pari_graphcolors = NULL;
     563        1420 : }
     564             : 
     565             : /*********************************************************************/
     566             : /*                   FUNCTION HASHTABLES, MODULES                    */
     567             : /*********************************************************************/
     568             : extern entree functions_basic[], functions_default[];
     569             : static void
     570        1420 : pari_init_functions(void)
     571             : {
     572        1420 :   pari_stack_init(&s_MODULES, sizeof(*MODULES),(void**)&MODULES);
     573        1420 :   pari_stack_pushp(&s_MODULES,functions_basic);
     574        1420 :   functions_hash = (entree**) pari_calloc(sizeof(entree*)*functions_tblsz);
     575        1420 :   pari_fill_hashtable(functions_hash, functions_basic);
     576        1420 :   defaults_hash = (entree**) pari_calloc(sizeof(entree*)*functions_tblsz);
     577        1420 :   pari_add_defaults_module(functions_default);
     578        1420 : }
     579             : 
     580             : void
     581        2838 : pari_add_module(entree *ep)
     582             : {
     583        2838 :   pari_fill_hashtable(functions_hash, ep);
     584        2838 :   pari_stack_pushp(&s_MODULES, ep);
     585        2838 : }
     586             : 
     587             : void
     588        1420 : pari_add_defaults_module(entree *ep)
     589        1420 : { pari_fill_hashtable(defaults_hash, ep); }
     590             : 
     591             : /*********************************************************************/
     592             : /*                       PARI MAIN STACK                             */
     593             : /*********************************************************************/
     594             : 
     595             : #ifdef HAS_MMAP
     596             : #define PARI_STACK_ALIGN (sysconf(_SC_PAGE_SIZE))
     597             : #ifndef MAP_ANONYMOUS
     598             : #define MAP_ANONYMOUS MAP_ANON
     599             : #endif
     600             : static void *
     601       64568 : pari_mainstack_malloc(size_t size)
     602             : {
     603       64568 :   void *b = mmap(NULL, size, PROT_READ|PROT_WRITE,
     604             :                              MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
     605       64568 :   return (b == MAP_FAILED) ? NULL: b;
     606             : }
     607             : 
     608             : static void
     609       65075 : pari_mainstack_mfree(void *s, size_t size)
     610             : {
     611       65075 :   munmap(s, size);
     612       65075 : }
     613             : 
     614             : /* Completely discard the memory mapped between the addresses "from"
     615             :  * and "to" (which must be page-aligned).
     616             :  *
     617             :  * We use mmap() with PROT_NONE, which means that the underlying memory
     618             :  * is freed and that the kernel should not commit memory for it. We
     619             :  * still keep the mapping such that we can change the flags to
     620             :  * PROT_READ|PROT_WRITE later.
     621             :  *
     622             :  * NOTE: remapping with MAP_FIXED and PROT_NONE is not the same as
     623             :  * calling mprotect(..., PROT_NONE) because the latter will keep the
     624             :  * memory committed (this is in particular relevant on Linux with
     625             :  * vm.overcommit = 2). This remains true even when calling
     626             :  * madvise(..., MADV_DONTNEED). */
     627             : static void
     628      135736 : pari_mainstack_mreset(pari_sp from, pari_sp to)
     629             : {
     630      135736 :   size_t s = to - from;
     631      135736 :   mmap((void*)from, s, PROT_NONE, MAP_FIXED|MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
     632      135736 : }
     633             : 
     634             : /* Commit (make available) the virtual memory mapped between the
     635             :  * addresses "from" and "to" (which must be page-aligned).
     636             :  * Return 0 if successful, -1 if failed. */
     637             : static int
     638      135736 : pari_mainstack_mextend(pari_sp from, pari_sp to)
     639             : {
     640      135736 :   size_t s = to - from;
     641      135736 :   return mprotect((void*)from, s, PROT_READ|PROT_WRITE);
     642             : }
     643             : 
     644             : /* Set actual stack size to the given size. This sets st->size and
     645             :  * st->bot. If not enough system memory is available, this can fail.
     646             :  * Return 1 if successful, 0 if failed (in that case, st->size is not
     647             :  * changed) */
     648             : static int
     649      135736 : pari_mainstack_setsize(struct pari_mainstack *st, size_t size)
     650             : {
     651      135736 :   pari_sp newbot = st->top - size;
     652             :   /* Align newbot to pagesize */
     653      135736 :   pari_sp alignbot = newbot & ~(pari_sp)(PARI_STACK_ALIGN - 1);
     654      135736 :   if (pari_mainstack_mextend(alignbot, st->top))
     655             :   {
     656             :     /* Making the memory available did not work: limit vsize to the
     657             :      * current actual stack size. */
     658           0 :     st->vsize = st->size;
     659           0 :     pari_warn(warnstack, st->vsize);
     660           0 :     return 0;
     661             :   }
     662      135736 :   pari_mainstack_mreset(st->vbot, alignbot);
     663      135736 :   st->bot = newbot;
     664      135736 :   st->size = size;
     665      135736 :   return 1;
     666             : }
     667             : 
     668             : #else
     669             : #define PARI_STACK_ALIGN (0x40UL)
     670             : static void *
     671             : pari_mainstack_malloc(size_t s)
     672             : {
     673             :   return malloc(s); /* NOT pari_malloc, e_MEM would be deadly */
     674             : }
     675             : 
     676             : static void
     677             : pari_mainstack_mfree(void *s, size_t size) { (void) size; free(s); }
     678             : 
     679             : static int
     680             : pari_mainstack_setsize(struct pari_mainstack *st, size_t size)
     681             : {
     682             :   st->bot = st->top - size;
     683             :   st->size = size;
     684             :   return 1;
     685             : }
     686             : 
     687             : #endif
     688             : 
     689             : static const size_t MIN_STACK = 500032UL;
     690             : static size_t
     691      129643 : fix_size(size_t a)
     692             : {
     693      129643 :   size_t ps = PARI_STACK_ALIGN;
     694      129643 :   size_t b = a & ~(ps - 1); /* Align */
     695      129643 :   if (b < a && b < ~(ps - 1)) b += ps;
     696      129643 :   if (b < MIN_STACK) b = MIN_STACK;
     697      129643 :   return b;
     698             : }
     699             : 
     700             : static void
     701       64568 : pari_mainstack_alloc(struct pari_mainstack *st, size_t rsize, size_t vsize)
     702             : {
     703       64568 :   size_t sizemax = vsize ? vsize: rsize, s = fix_size(sizemax);
     704             :   for (;;)
     705             :   {
     706       64568 :     st->vbot = (pari_sp)pari_mainstack_malloc(s);
     707       64568 :     if (st->vbot) break;
     708           0 :     if (s == MIN_STACK) pari_err(e_MEM); /* no way out. Die */
     709           0 :     s = fix_size(s >> 1);
     710           0 :     pari_warn(warnstack, s);
     711           0 :   }
     712       64568 :   st->vsize = vsize ? s: 0;
     713       64568 :   st->rsize = minuu(rsize, s);
     714       64568 :   st->top = st->vbot+s;
     715       64568 :   if (!pari_mainstack_setsize(st, st->rsize))
     716             :   {
     717             :     /* This should never happen since we only decrease the allocated space */
     718           0 :     pari_err(e_MEM);
     719             :   }
     720       64568 :   st->memused = 0;
     721       64568 : }
     722             : 
     723             : static void
     724       65075 : pari_mainstack_free(struct pari_mainstack *st)
     725             : {
     726       65075 :   pari_mainstack_mfree((void*)st->vbot, st->vsize ? st->vsize : fix_size(st->rsize));
     727       65075 :   st->top = st->bot = st->vbot = 0;
     728       65075 :   st->size = st->vsize = 0;
     729       65075 : }
     730             : 
     731             : static void
     732         204 : pari_mainstack_resize(struct pari_mainstack *st, size_t rsize, size_t vsize)
     733             : {
     734         204 :   BLOCK_SIGINT_START;
     735         204 :   pari_mainstack_free(st);
     736         204 :   pari_mainstack_alloc(st, rsize, vsize);
     737         204 :   BLOCK_SIGINT_END;
     738         204 : }
     739             : 
     740             : static void
     741       62905 : pari_mainstack_use(struct pari_mainstack *st)
     742             : {
     743       62905 :   pari_mainstack = st;
     744       62905 :   avma = st->top;
     745       62905 : }
     746             : 
     747             : static void
     748        1420 : paristack_alloc(size_t rsize, size_t vsize)
     749             : {
     750        1420 :   pari_mainstack_alloc(pari_mainstack, rsize, vsize);
     751        1420 :   pari_mainstack_use(pari_mainstack);
     752        1420 : }
     753             : 
     754             : void
     755           0 : paristack_setsize(size_t rsize, size_t vsize)
     756             : {
     757           0 :   pari_mainstack_resize(pari_mainstack, rsize, vsize);
     758           0 :   pari_mainstack_use(pari_mainstack);
     759           0 : }
     760             : 
     761             : void
     762           0 : parivstack_resize(ulong newsize)
     763             : {
     764             :   size_t s;
     765           0 :   if (newsize && newsize < pari_mainstack->rsize)
     766           0 :     pari_err_DIM("stack sizes [parisizemax < parisize]");
     767           0 :   if (newsize == pari_mainstack->vsize) return;
     768           0 :   evalstate_reset();
     769           0 :   paristack_setsize(pari_mainstack->rsize, newsize);
     770           0 :   s = pari_mainstack->vsize ? pari_mainstack->vsize : pari_mainstack->rsize;
     771           0 :   pari_warn(warner,"new maximum stack size = %lu (%.3f Mbytes)", s, s/1048576.);
     772           0 :   pari_init_errcatch();
     773           0 :   cb_pari_err_recover(-1);
     774             : }
     775             : 
     776             : void
     777         210 : paristack_newrsize(ulong newsize)
     778             : {
     779         210 :   size_t s, vsize = pari_mainstack->vsize;
     780         210 :   if (!newsize) newsize = pari_mainstack->rsize << 1;
     781         210 :   if (newsize != pari_mainstack->rsize)
     782         204 :     pari_mainstack_resize(pari_mainstack, newsize, vsize);
     783         210 :   evalstate_reset();
     784         210 :   s = pari_mainstack->rsize;
     785         210 :   pari_warn(warner,"new stack size = %lu (%.3f Mbytes)", s, s/1048576.);
     786         210 :   pari_init_errcatch();
     787         210 :   cb_pari_err_recover(-1);
     788           0 : }
     789             : 
     790             : void
     791           8 : paristack_resize(ulong newsize)
     792             : {
     793           8 :   if (!newsize)
     794           0 :     newsize = 2 * pari_mainstack->size;
     795           8 :   newsize = minuu(newsize, pari_mainstack->vsize);
     796          16 :   if (newsize <= pari_mainstack->size) return;
     797           0 :   if (pari_mainstack_setsize(pari_mainstack, newsize))
     798             :   {
     799           0 :     pari_warn(warner, "increasing stack size to %lu", pari_mainstack->size);
     800             :   }
     801             : }
     802             : 
     803             : void
     804       71160 : parivstack_reset(void)
     805             : {
     806       71160 :   pari_mainstack_setsize(pari_mainstack, pari_mainstack->rsize);
     807       71160 :   if (avma < pari_mainstack->bot)
     808           0 :     pari_err_BUG("parivstack_reset [avma < bot]");
     809       71160 : }
     810             : 
     811             : /* Enlarge the stack if needed such that the unused portion of the stack
     812             :  * (between bot and avma) is large enough to contain x longs. */
     813             : void
     814           8 : new_chunk_resize(size_t x)
     815             : {
     816             :   ulong size, newsize, avail;
     817           8 :   avail = (avma - pari_mainstack->bot) / sizeof(long);
     818           8 :   if (avail >= x) return;
     819             : 
     820             :   /* We need to enlarge the stack. We try to at least double the
     821             :    * stack, to avoid increasing the stack a lot of times by a small
     822             :    * amount. */
     823           8 :   size = pari_mainstack->size;
     824           8 :   newsize = size + maxuu((x - avail) * sizeof(long), size);
     825           8 :   paristack_resize(newsize);
     826             : 
     827             :   /* Verify that we have enough space. Using a division here instead
     828             :    * of a multiplication is safe against overflow. */
     829           8 :   avail = (avma - pari_mainstack->bot) / sizeof(long);
     830           8 :   if (avail < x)
     831             :   {
     832             :     /* Restore old size and error out */
     833           8 :     pari_mainstack_setsize(pari_mainstack, size);
     834           8 :     pari_err(e_STACK);
     835             :   }
     836             : }
     837             : 
     838             : /*********************************************************************/
     839             : /*                       PARI THREAD                                 */
     840             : /*********************************************************************/
     841             : 
     842             : /* Initial PARI thread structure t with a stack of size s and virtual size v
     843             :  * and argument arg */
     844             : 
     845             : void
     846           0 : pari_thread_valloc(struct pari_thread *t, size_t s, size_t v, GEN arg)
     847             : {
     848           0 :   pari_mainstack_alloc(&t->st,s,v);
     849           0 :   t->data = arg;
     850           0 : }
     851             : 
     852             : /* Initial PARI thread structure t with a stack of size s and
     853             :  * argument arg */
     854             : 
     855             : void
     856       62944 : pari_thread_alloc(struct pari_thread *t, size_t s, GEN arg)
     857             : {
     858       62944 :   pari_mainstack_alloc(&t->st,s,0);
     859       62944 :   t->data = arg;
     860       62944 : }
     861             : 
     862             : void
     863       62944 : pari_thread_free(struct pari_thread *t)
     864             : {
     865       62944 :   pari_mainstack_free(&t->st);
     866       62944 : }
     867             : 
     868             : void
     869       62829 : pari_thread_init(void)
     870             : {
     871       62829 :   pari_init_blocks();
     872       63184 :   pari_init_errcatch();
     873       62891 :   pari_init_rand();
     874       64153 :   pari_init_floats();
     875       64143 :   pari_init_parser();
     876       64049 :   pari_init_compiler();
     877       64199 :   pari_init_evaluator();
     878       63973 :   pari_init_files();
     879       63787 :   pari_thread_init_primetab();
     880       63686 :   pari_thread_init_seadata();
     881       63419 : }
     882             : 
     883             : void
     884        3934 : pari_thread_sync(void)
     885             : {
     886        3934 :   pari_pthread_init_primetab();
     887        3934 :   pari_pthread_init_seadata();
     888        3934 :   pari_pthread_init_varstate();
     889        3934 : }
     890             : 
     891             : void
     892       64730 : pari_thread_close(void)
     893             : {
     894       64730 :   pari_thread_close_files();
     895       64720 :   pari_close_evaluator();
     896       64690 :   pari_close_compiler();
     897       64599 :   pari_close_parser();
     898       64580 :   pari_close_floats();
     899       64571 :   pari_close_blocks();
     900       64180 : }
     901             : 
     902             : GEN
     903       61479 : pari_thread_start(struct pari_thread *t)
     904             : {
     905       61479 :   pari_mainstack_use(&t->st);
     906       61395 :   pari_thread_init();
     907       61986 :   pari_thread_init_varstate();
     908       62897 :   return t->data;
     909             : }
     910             : 
     911             : /*********************************************************************/
     912             : /*                       LIBPARI INIT / CLOSE                        */
     913             : /*********************************************************************/
     914             : 
     915             : static void
     916           0 : pari_exit(void)
     917             : {
     918           0 :   err_printf("  ***   Error in the PARI system. End of program.\n");
     919           0 :   exit(1);
     920             : }
     921             : 
     922             : static void
     923           0 : dflt_err_recover(long errnum) { (void) errnum; pari_exit(); }
     924             : 
     925             : static void
     926           0 : dflt_pari_quit(long err) { (void)err; /*do nothing*/; }
     927             : 
     928             : static int pari_err_display(GEN err);
     929             : 
     930             : /* initialize PARI data. Initialize [new|old]fun to NULL for default set. */
     931             : void
     932        1420 : pari_init_opts(size_t parisize, ulong maxprime, ulong init_opts)
     933             : {
     934             :   ulong u;
     935             : 
     936        1420 :   pari_mt_nbthreads = 0;
     937        1420 :   cb_pari_quit = dflt_pari_quit;
     938        1420 :   cb_pari_init_histfile = NULL;
     939        1420 :   cb_pari_get_line_interactive = NULL;
     940        1420 :   cb_pari_fgets_interactive = NULL;
     941        1420 :   cb_pari_whatnow = NULL;
     942        1420 :   cb_pari_handle_exception = NULL;
     943        1420 :   cb_pari_err_handle = pari_err_display;
     944        1420 :   cb_pari_pre_recover = NULL;
     945        1420 :   cb_pari_break_loop = NULL;
     946        1420 :   cb_pari_is_interactive = NULL;
     947        1420 :   cb_pari_start_output = NULL;
     948        1420 :   cb_pari_sigint = dflt_sigint_fun;
     949        1420 :   if (init_opts&INIT_JMPm) cb_pari_err_recover = dflt_err_recover;
     950             : 
     951        1420 :   pari_stackcheck_init(&u);
     952        1420 :   pari_init_homedir();
     953        1420 :   if (init_opts&INIT_DFTm) {
     954           0 :     pari_init_defaults();
     955           0 :     GP_DATA = default_gp_data();
     956           0 :     gp_expand_path(GP_DATA->path);
     957             :   }
     958             : 
     959        1420 :   pari_mainstack = (struct pari_mainstack *) malloc(sizeof(*pari_mainstack));
     960        1420 :   paristack_alloc(parisize, 0);
     961        1420 :   init_universal_constants();
     962        1420 :   diffptr = NULL;
     963        1420 :   if (!(init_opts&INIT_noPRIMEm))  pari_init_primes(maxprime);
     964        1420 :   if (!(init_opts&INIT_noINTGMPm)) pari_kernel_init();
     965        1420 :   pari_init_primetab();
     966        1420 :   pari_init_seadata();
     967        1420 :   pari_thread_init();
     968        1420 :   pari_init_functions();
     969        1420 :   pari_var_init();
     970        1420 :   pari_init_timer();
     971        1420 :   pari_init_buffers();
     972        1420 :   (void)getabstime();
     973        1420 :   try_to_recover = 1;
     974        1420 :   if (!(init_opts&INIT_noIMTm)) pari_mt_init();
     975        1420 :   if ((init_opts&INIT_SIGm)) pari_sig_init(pari_sighandler);
     976        1420 : }
     977             : 
     978             : void
     979           0 : pari_init(size_t parisize, ulong maxprime)
     980           0 : { pari_init_opts(parisize, maxprime, INIT_JMPm | INIT_SIGm | INIT_DFTm); }
     981             : 
     982             : void
     983        1927 : pari_close_opts(ulong init_opts)
     984             : {
     985             :   long i;
     986             : 
     987        1927 :   BLOCK_SIGINT_START;
     988        1927 :   if ((init_opts&INIT_SIGm)) pari_sig_init(SIG_DFL);
     989        1927 :   if (!(init_opts&INIT_noIMTm)) pari_mt_close();
     990             : 
     991      262072 :   for (i = 0; i < functions_tblsz; i++)
     992             :   {
     993      260145 :     entree *ep = functions_hash[i];
     994     2494928 :     while (ep) {
     995     1974638 :       entree *EP = ep->next;
     996     1974638 :       if (!EpSTATIC(ep)) { freeep(ep); free(ep); }
     997     1974638 :       ep = EP;
     998             :     }
     999             :   }
    1000        1927 :   pari_var_close();
    1001        1927 :   pari_thread_close();
    1002        1927 :   pari_close_files();
    1003        1927 :   pari_close_homedir();
    1004        1927 :   pari_kernel_close();
    1005             : 
    1006        1927 :   free((void*)functions_hash);
    1007        1927 :   free((void*)defaults_hash);
    1008        1927 :   if (diffptr) pari_close_primes();
    1009        1927 :   free(current_logfile);
    1010        1927 :   free(current_psfile);
    1011        1927 :   pari_mainstack_free(pari_mainstack);
    1012        1927 :   free((void*)pari_mainstack);
    1013        1927 :   pari_stack_delete(&s_MODULES);
    1014        1927 :   if (pari_datadir) free(pari_datadir);
    1015        1927 :   if (init_opts&INIT_DFTm)
    1016             :   { /* delete GP_DATA */
    1017        1927 :     if (GP_DATA->hist->v) free((void*)GP_DATA->hist->v);
    1018        1927 :     if (GP_DATA->pp->cmd) free((void*)GP_DATA->pp->cmd);
    1019        1927 :     delete_dirs(GP_DATA->path);
    1020        1927 :     free((void*)GP_DATA->path->PATH);
    1021        1927 :     delete_dirs(GP_DATA->sopath);
    1022        1927 :     free((void*)GP_DATA->sopath->PATH);
    1023        1927 :     if (GP_DATA->help) free((void*)GP_DATA->help);
    1024        1927 :     free((void*)GP_DATA->prompt);
    1025        1927 :     free((void*)GP_DATA->prompt_cont);
    1026        1927 :     free((void*)GP_DATA->histfile);
    1027             :   }
    1028        1927 :   BLOCK_SIGINT_END;
    1029        1927 : }
    1030             : 
    1031             : void
    1032        1927 : pari_close(void)
    1033        1927 : { pari_close_opts(INIT_JMPm | INIT_SIGm | INIT_DFTm); }
    1034             : 
    1035             : /*******************************************************************/
    1036             : /*                                                                 */
    1037             : /*                         ERROR RECOVERY                          */
    1038             : /*                                                                 */
    1039             : /*******************************************************************/
    1040             : void
    1041       85888 : gp_context_save(struct gp_context* rec)
    1042             : {
    1043       85888 :   rec->file = pari_last_tmp_file();
    1044       85888 :   if (DEBUGFILES>1)
    1045           0 :     err_printf("gp_context_save: %s\n", rec->file ? rec->file->name: "NULL");
    1046       85888 :   rec->prettyp = GP_DATA->fmt->prettyp;
    1047       85888 :   rec->listloc = next_block;
    1048       85888 :   rec->iferr_env = iferr_env;
    1049       85888 :   rec->err_data  = global_err_data;
    1050       85888 :   varstate_save(&rec->var);
    1051       85888 :   evalstate_save(&rec->eval);
    1052       85888 :   parsestate_save(&rec->parse);
    1053       85888 : }
    1054             : 
    1055             : void
    1056       16457 : gp_context_restore(struct gp_context* rec)
    1057             : {
    1058             :   long i;
    1059             : 
    1060       32914 :   if (!try_to_recover) return;
    1061             :   /* disable gp_context_restore() and SIGINT */
    1062       16457 :   try_to_recover = 0;
    1063       16457 :   BLOCK_SIGINT_START
    1064       16457 :   if (DEBUGMEM>2) err_printf("entering recover(), loc = %ld\n", rec->listloc);
    1065       16457 :   evalstate_restore(&rec->eval);
    1066       16457 :   parsestate_restore(&rec->parse);
    1067       16457 :   filestate_restore(rec->file);
    1068       16457 :   global_err_data = rec->err_data;
    1069       16457 :   iferr_env = rec->iferr_env;
    1070       16457 :   GP_DATA->fmt->prettyp = rec->prettyp;
    1071             : 
    1072     2238152 :   for (i = 0; i < functions_tblsz; i++)
    1073             :   {
    1074     2221695 :     entree *ep = functions_hash[i];
    1075    21916379 :     while (ep)
    1076             :     {
    1077    17472989 :       entree *EP = ep->next;
    1078    17472989 :       switch(EpVALENCE(ep))
    1079             :       {
    1080             :         case EpVAR:
    1081      176818 :           while (pop_val_if_newer(ep,rec->listloc)) /* empty */;
    1082      176818 :           break;
    1083      641687 :         case EpNEW: break;
    1084             :       }
    1085    17472989 :       ep = EP;
    1086             :     }
    1087             :   }
    1088       16457 :   varstate_restore(&rec->var);
    1089       16457 :   if (DEBUGMEM>2) err_printf("leaving recover()\n");
    1090       16457 :   BLOCK_SIGINT_END
    1091       16457 :   try_to_recover = 1;
    1092             : }
    1093             : 
    1094             : static void
    1095       16387 : err_recover(long numerr)
    1096             : {
    1097       16387 :   if (cb_pari_pre_recover)
    1098       16387 :     cb_pari_pre_recover(numerr);
    1099           0 :   evalstate_reset();
    1100           0 :   killallfiles();
    1101           0 :   pari_init_errcatch();
    1102           0 :   cb_pari_err_recover(numerr);
    1103           0 : }
    1104             : 
    1105             : static void
    1106       16863 : err_init(void)
    1107             : {
    1108             :   /* make sure pari_err msg starts at the beginning of line */
    1109       16863 :   if (!pari_last_was_newline()) pari_putc('\n');
    1110       16863 :   pariOut->flush();
    1111       16863 :   pariErr->flush();
    1112       16863 :   out_term_color(pariErr, c_ERR);
    1113       16863 : }
    1114             : 
    1115             : static void
    1116       16828 : err_init_msg(int user)
    1117             : {
    1118             :   const char *gp_function_name;
    1119       16828 :   out_puts(pariErr, "  *** ");
    1120       16828 :   if (!user && (gp_function_name = closure_func_err()))
    1121       11935 :     out_printf(pariErr, "%s: ", gp_function_name);
    1122             :   else
    1123        4893 :     out_puts(pariErr, "  ");
    1124       16828 : }
    1125             : 
    1126             : void
    1127         455 : pari_warn(int numerr, ...)
    1128             : {
    1129             :   char *ch1;
    1130             :   va_list ap;
    1131             : 
    1132         455 :   va_start(ap,numerr);
    1133             : 
    1134         455 :   err_init();
    1135         455 :   err_init_msg(numerr==warnuser || numerr==warnstack);
    1136         455 :   switch (numerr)
    1137             :   {
    1138             :     case warnuser:
    1139           7 :       out_puts(pariErr, "user warning: ");
    1140           7 :       out_print0(pariErr, NULL, va_arg(ap, GEN), f_RAW);
    1141           7 :       break;
    1142             : 
    1143             :     case warnmem:
    1144           0 :       out_puts(pariErr, "collecting garbage in "); ch1=va_arg(ap, char*);
    1145           0 :       out_vprintf(pariErr, ch1,ap); out_putc(pariErr, '.');
    1146           0 :       break;
    1147             : 
    1148             :     case warner:
    1149         448 :       out_puts(pariErr, "Warning: "); ch1=va_arg(ap, char*);
    1150         448 :       out_vprintf(pariErr, ch1,ap); out_putc(pariErr, '.');
    1151         448 :       break;
    1152             : 
    1153             :     case warnprec:
    1154           0 :       out_vprintf(pariErr, "Warning: increasing prec in %s; new prec = %ld",
    1155             :                       ap);
    1156           0 :       break;
    1157             : 
    1158             :     case warnfile:
    1159           0 :       out_puts(pariErr, "Warning: failed to "),
    1160           0 :       ch1 = va_arg(ap, char*);
    1161           0 :       out_printf(pariErr, "%s: %s", ch1, va_arg(ap, char*));
    1162           0 :       break;
    1163             : 
    1164             :     case warnstack:
    1165             :     {
    1166           0 :       ulong  s = va_arg(ap, ulong);
    1167             :       char buf[128];
    1168           0 :       sprintf(buf,"Warning: not enough memory, new stack %lu", (ulong)s);
    1169           0 :       out_puts(pariErr,buf);
    1170           0 :       break;
    1171             :     }
    1172             : 
    1173             :   }
    1174         455 :   va_end(ap);
    1175         455 :   out_term_color(pariErr, c_NONE);
    1176         455 :   out_putc(pariErr, '\n');
    1177         455 :   pariErr->flush();
    1178         455 : }
    1179             : void
    1180           0 : pari_sigint(const char *time_s)
    1181             : {
    1182           0 :   int recover=0;
    1183           0 :   BLOCK_SIGALRM_START
    1184           0 :   err_init();
    1185           0 :   closure_err(0);
    1186           0 :   err_init_msg(0);
    1187           0 :   out_puts(pariErr, "user interrupt after ");
    1188           0 :   out_puts(pariErr, time_s);
    1189           0 :   out_term_color(pariErr, c_NONE);
    1190           0 :   pariErr->flush();
    1191           0 :   if (cb_pari_handle_exception)
    1192           0 :     recover = cb_pari_handle_exception(-1);
    1193           0 :   if (!recover && !block)
    1194           0 :     PARI_SIGINT_pending = 0;
    1195           0 :   BLOCK_SIGINT_END
    1196           0 :   if (!recover) err_recover(e_MISC);
    1197           0 : }
    1198             : 
    1199             : #define retmkerr2(x,y)\
    1200             :   do { GEN _v = cgetg(3, t_ERROR);\
    1201             :        _v[1] = (x);\
    1202             :        gel(_v,2) = (y); return _v; } while(0)
    1203             : #define retmkerr3(x,y,z)\
    1204             :   do { GEN _v = cgetg(4, t_ERROR);\
    1205             :        _v[1] = (x);\
    1206             :        gel(_v,2) = (y);\
    1207             :        gel(_v,3) = (z); return _v; } while(0)
    1208             : #define retmkerr4(x,y,z,t)\
    1209             :   do { GEN _v = cgetg(5, t_ERROR);\
    1210             :        _v[1] = (x);\
    1211             :        gel(_v,2) = (y);\
    1212             :        gel(_v,3) = (z);\
    1213             :        gel(_v,4) = (t); return _v; } while(0)
    1214             : #define retmkerr5(x,y,z,t,u)\
    1215             :   do { GEN _v = cgetg(6, t_ERROR);\
    1216             :        _v[1] = (x);\
    1217             :        gel(_v,2) = (y);\
    1218             :        gel(_v,3) = (z);\
    1219             :        gel(_v,4) = (t);\
    1220             :        gel(_v,5) = (u); return _v; } while(0)
    1221             : #define retmkerr6(x,y,z,t,u,v)\
    1222             :   do { GEN _v = cgetg(7, t_ERROR);\
    1223             :        _v[1] = (x);\
    1224             :        gel(_v,2) = (y);\
    1225             :        gel(_v,3) = (z);\
    1226             :        gel(_v,4) = (t);\
    1227             :        gel(_v,5) = (u);\
    1228             :        gel(_v,6) = (v); return _v; } while(0)
    1229             : 
    1230             : static GEN
    1231       31199 : pari_err2GEN(long numerr, va_list ap)
    1232             : {
    1233       31199 :   switch ((enum err_list) numerr)
    1234             :   {
    1235             :   case e_SYNTAX:
    1236             :     {
    1237          35 :       const char *msg = va_arg(ap, char*);
    1238          35 :       const char *s = va_arg(ap,char *);
    1239          35 :       const char *entry = va_arg(ap,char *);
    1240          35 :       retmkerr3(numerr,strtoGENstr(msg), mkvecsmall2((long)s,(long)entry));
    1241             :     }
    1242             :   case e_MISC: case e_ALARM:
    1243             :     {
    1244        2692 :       const char *ch1 = va_arg(ap, char*);
    1245        2692 :       retmkerr2(numerr, gvsprintf(ch1,ap));
    1246             :     }
    1247             :   case e_NOTFUNC:
    1248             :   case e_USER:
    1249        2737 :     retmkerr2(numerr,va_arg(ap, GEN));
    1250             :   case e_FILE:
    1251             :     {
    1252           0 :       const char *f = va_arg(ap, const char*);
    1253           0 :       retmkerr3(numerr, strtoGENstr(f), strtoGENstr(va_arg(ap, char*)));
    1254             :     }
    1255             :   case e_OVERFLOW:
    1256             :   case e_IMPL:
    1257             :   case e_DIM:
    1258             :   case e_CONSTPOL:
    1259             :   case e_ROOTS0:
    1260             :   case e_FLAG:
    1261             :   case e_PREC:
    1262             :   case e_BUG:
    1263             :   case e_ARCH:
    1264             :   case e_PACKAGE:
    1265        1661 :     retmkerr2(numerr, strtoGENstr(va_arg(ap, char*)));
    1266             :   case e_MODULUS:
    1267             :   case e_VAR:
    1268             :     {
    1269         938 :       const char *f = va_arg(ap, const char*);
    1270         938 :       GEN x = va_arg(ap, GEN);
    1271         938 :       GEN y = va_arg(ap, GEN);
    1272         938 :       retmkerr4(numerr, strtoGENstr(f), x,y);
    1273             :     }
    1274             :   case e_INV:
    1275             :   case e_IRREDPOL:
    1276             :   case e_PRIME:
    1277             :   case e_SQRTN:
    1278             :   case e_TYPE:
    1279             :     {
    1280       14161 :       const char *f = va_arg(ap, const char*);
    1281       14161 :       GEN x = va_arg(ap, GEN);
    1282       14161 :       retmkerr3(numerr, strtoGENstr(f), x);
    1283             :     }
    1284             :   case e_COPRIME: case e_OP: case e_TYPE2:
    1285             :     {
    1286        3423 :       const char *f = va_arg(ap, const char*);
    1287        3423 :       GEN x = va_arg(ap, GEN);
    1288        3423 :       GEN y = va_arg(ap, GEN);
    1289        3423 :       retmkerr4(numerr,strtoGENstr(f),x,y);
    1290             :     }
    1291             :   case e_COMPONENT:
    1292             :     {
    1293         224 :       const char *f= va_arg(ap, const char *);
    1294         224 :       const char *op = va_arg(ap, const char *);
    1295         224 :       GEN l = va_arg(ap, GEN);
    1296         224 :       GEN x = va_arg(ap, GEN);
    1297         224 :       retmkerr5(numerr,strtoGENstr(f),strtoGENstr(op),l,x);
    1298             :     }
    1299             :   case e_DOMAIN:
    1300             :     {
    1301        5201 :       const char *f = va_arg(ap, const char*);
    1302        5201 :       const char *v = va_arg(ap, const char *);
    1303        5201 :       const char *op = va_arg(ap, const char *);
    1304        5201 :       GEN l = va_arg(ap, GEN);
    1305        5201 :       GEN x = va_arg(ap, GEN);
    1306        5201 :       retmkerr6(numerr,strtoGENstr(f),strtoGENstr(v),strtoGENstr(op),l,x);
    1307             :     }
    1308             :   case e_PRIORITY:
    1309             :     {
    1310         119 :       const char *f = va_arg(ap, const char*);
    1311         119 :       GEN x = va_arg(ap, GEN);
    1312         119 :       const char *op = va_arg(ap, const char *);
    1313         119 :       long v = va_arg(ap, long);
    1314         119 :       retmkerr5(numerr,strtoGENstr(f),x,strtoGENstr(op),stoi(v));
    1315             :     }
    1316             :   case e_MAXPRIME:
    1317           0 :     retmkerr2(numerr, utoi(va_arg(ap, ulong)));
    1318             :   case e_STACK:
    1319           8 :     return err_e_STACK;
    1320             :   case e_STACKTHREAD:
    1321           0 :     retmkerr3(numerr, utoi(va_arg(ap, ulong)), utoi(va_arg(ap, ulong)));
    1322             :   default:
    1323           0 :     return mkerr(numerr);
    1324             :   }
    1325             : }
    1326             : 
    1327             : static char *
    1328        6258 : type_dim(GEN x)
    1329             : {
    1330        6258 :   char *v = stack_malloc(64);
    1331        6258 :   switch(typ(x))
    1332             :   {
    1333             :     case t_MAT:
    1334             :     {
    1335          63 :       long l = lg(x), r = (l == 1)? 1: lgcols(x);
    1336          63 :       sprintf(v, "t_MAT (%ldx%ld)", r-1,l-1);
    1337          63 :       break;
    1338             :     }
    1339             :     case t_COL:
    1340          91 :       sprintf(v, "t_COL (%ld elts)", lg(x)-1);
    1341          91 :       break;
    1342             :     case t_VEC:
    1343         133 :       sprintf(v, "t_VEC (%ld elts)", lg(x)-1);
    1344         133 :       break;
    1345             :     default:
    1346        5971 :       v = (char*)type_name(typ(x));
    1347             :   }
    1348        6258 :   return v;
    1349             : }
    1350             : 
    1351             : static char *
    1352        2240 : gdisplay(GEN x)
    1353             : {
    1354        2240 :   char *s = GENtostr_raw(x);
    1355        2240 :   if (strlen(s) < 1600) return s;
    1356          21 :   if (! GP_DATA->breakloop) return (char*)"(...)";
    1357           0 :   return stack_sprintf("\n  ***  (...) Huge %s omitted; you can access it via dbg_err()", type_name(typ(x)));
    1358             : }
    1359             : 
    1360             : char *
    1361       23436 : pari_err2str(GEN e)
    1362             : {
    1363       23436 :   long numerr = err_get_num(e);
    1364       23436 :   switch ((enum err_list) numerr)
    1365             :   {
    1366             :   case e_ALARM:
    1367           0 :     return pari_sprintf("alarm interrupt after %Ps.",gel(e,2));
    1368             :   case e_MISC:
    1369        2690 :     return pari_sprintf("%Ps.",gel(e,2));
    1370             : 
    1371             :   case e_ARCH:
    1372           0 :     return pari_sprintf("sorry, '%Ps' not available on this system.",gel(e,2));
    1373             :   case e_BUG:
    1374          14 :     return pari_sprintf("bug in %Ps, please report.",gel(e,2));
    1375             :   case e_CONSTPOL:
    1376           7 :     return pari_sprintf("constant polynomial in %Ps.", gel(e,2));
    1377             :   case e_COPRIME:
    1378         189 :     return pari_sprintf("elements not coprime in %Ps:\n    %s\n    %s",
    1379         189 :                         gel(e,2), gdisplay(gel(e,3)), gdisplay(gel(e,4)));
    1380             :   case e_DIM:
    1381         932 :     return pari_sprintf("inconsistent dimensions in %Ps.", gel(e,2));
    1382             :   case e_FILE:
    1383           0 :     return pari_sprintf("error opening %Ps: `%Ps'.", gel(e,2), gel(e,3));
    1384             :   case e_FLAG:
    1385          21 :     return pari_sprintf("invalid flag in %Ps.", gel(e,2));
    1386             :   case e_IMPL:
    1387         315 :     return pari_sprintf("sorry, %Ps is not yet implemented.", gel(e,2));
    1388             :   case e_PACKAGE:
    1389           0 :     return pari_sprintf("package %Ps is required, please install it.", gel(e,2));
    1390             :   case e_INV:
    1391         490 :     return pari_sprintf("impossible inverse in %Ps: %s.", gel(e,2),
    1392         490 :                         gdisplay(gel(e,3)));
    1393             :   case e_IRREDPOL:
    1394          42 :     return pari_sprintf("not an irreducible polynomial in %Ps: %s.",
    1395          42 :                         gel(e,2), gdisplay(gel(e,3)));
    1396             :   case e_MAXPRIME:
    1397             :     {
    1398           0 :       const char * msg = "not enough precomputed primes";
    1399           0 :       ulong c = itou(gel(e,2));
    1400           0 :       if (c) return pari_sprintf("%s, need primelimit ~ %lu.",msg, c);
    1401           0 :       else   return pari_strdup(msg);
    1402             :     }
    1403             :   case e_MEM:
    1404           0 :     return pari_strdup("not enough memory");
    1405             :   case e_MODULUS:
    1406             :     {
    1407         735 :       GEN x = gel(e,3), y = gel(e,4);
    1408        1470 :       return pari_sprintf("inconsistent moduli in %Ps: %s != %s",
    1409         735 :                           gel(e,2), gdisplay(x), gdisplay(y));
    1410             :     }
    1411           0 :   case e_NONE: return NULL;
    1412             :   case e_NOTFUNC:
    1413        2723 :     return pari_strdup("not a function in function call");
    1414             :   case e_OP: case e_TYPE2:
    1415             :     {
    1416        3129 :       pari_sp av = avma;
    1417             :       char *v;
    1418        3129 :       const char *f, *op = GSTR(gel(e,2));
    1419        3129 :       const char *what = numerr == e_OP? "inconsistent": "forbidden";
    1420        3129 :       GEN x = gel(e,3);
    1421        3129 :       GEN y = gel(e,4);
    1422        3129 :       switch(*op)
    1423             :       {
    1424          14 :       case '+': f = "addition"; break;
    1425         105 :       case '*': f = "multiplication"; break;
    1426        2387 :       case '/': case '%': case '\\': f = "division"; break;
    1427           0 :       case '=': op = "-->"; f = "assignment"; break;
    1428         623 :       default:  f = op; op = ","; break;
    1429             :       }
    1430        3129 :       v = pari_sprintf("%s %s %s %s %s.", what,f,type_dim(x),op,type_dim(y));
    1431        3129 :       avma = av; return v;
    1432             :     }
    1433             :   case e_COMPONENT:
    1434             :     {
    1435         224 :       const char *f= GSTR(gel(e,2));
    1436         224 :       const char *op= GSTR(gel(e,3));
    1437         224 :       GEN l = gel(e,4);
    1438         224 :       if (!*f)
    1439         126 :         return pari_sprintf("non-existent component: index %s %Ps",op,l);
    1440          98 :       return pari_sprintf("non-existent component in %s: index %s %Ps",f,op,l);
    1441             :     }
    1442             :   case e_DOMAIN:
    1443             :     {
    1444        5103 :       const char *f = GSTR(gel(e,2));
    1445        5103 :       const char *v = GSTR(gel(e,3));
    1446        5103 :       const char *op= GSTR(gel(e,4));
    1447        5103 :       GEN l = gel(e,5);
    1448        5103 :       if (!*op)
    1449          28 :         return pari_sprintf("domain error in %s: %s out of range",f,v);
    1450        5075 :       return pari_sprintf("domain error in %s: %s %s %Ps",f,v,op,l);
    1451             :     }
    1452             :   case e_PRIORITY:
    1453             :     {
    1454          70 :       const char *f = GSTR(gel(e,2));
    1455          70 :       long vx = gvar(gel(e,3));
    1456          70 :       const char *op= GSTR(gel(e,4));
    1457          70 :       long v = itos(gel(e,5));
    1458          70 :       return pari_sprintf("incorrect priority in %s: variable %Ps %s %Ps",f,
    1459             :              pol_x(vx), op, pol_x(v));
    1460             :     }
    1461             :   case e_OVERFLOW:
    1462          77 :     return pari_sprintf("overflow in %Ps.", gel(e,2));
    1463             :   case e_PREC:
    1464         210 :     return pari_sprintf("precision too low in %Ps.", gel(e,2));
    1465             :   case e_PRIME:
    1466         112 :     return pari_sprintf("not a prime number in %Ps: %s.",
    1467         112 :                         gel(e,2), gdisplay(gel(e,3)));
    1468             :   case e_ROOTS0:
    1469          42 :     return pari_sprintf("zero polynomial in %Ps.", gel(e,2));
    1470             :   case e_SQRTN:
    1471         154 :     return pari_sprintf("not an n-th power residue in %Ps: %s.",
    1472         154 :                         gel(e,2), gdisplay(gel(e,3)));
    1473             :   case e_STACK:
    1474             :   case e_STACKTHREAD:
    1475             :     {
    1476           8 :       const char *stack = numerr == e_STACK? "PARI": "thread";
    1477           8 :       const char *var = numerr == e_STACK? "parisizemax": "threadsizemax";
    1478          10 :       size_t rsize = numerr == e_STACKTHREAD && GP_DATA->threadsize ?
    1479           8 :                                 GP_DATA->threadsize: pari_mainstack->rsize;
    1480           8 :       size_t vsize = numerr == e_STACK? pari_mainstack->vsize:
    1481           0 :                                         GP_DATA->threadsizemax;
    1482           8 :       char *buf = (char *) pari_malloc(512*sizeof(char));
    1483           8 :       if (vsize)
    1484             :       {
    1485           0 :         sprintf(buf, "the %s stack overflows !\n"
    1486             :             "  current stack size: %lu (%.3f Mbytes)\n"
    1487             :             "  [hint] you can increase '%s' using default()\n",
    1488           0 :             stack, (ulong)vsize, (double)vsize/1048576., var);
    1489             :       }
    1490             :       else
    1491             :       {
    1492           8 :         sprintf(buf, "the %s stack overflows !\n"
    1493             :             "  current stack size: %lu (%.3f Mbytes)\n"
    1494             :             "  [hint] set '%s' to a non-zero value in your GPRC\n",
    1495           8 :             stack, (ulong)rsize, (double)rsize/1048576., var);
    1496             :       }
    1497           8 :       return buf;
    1498             :     }
    1499             :   case e_SYNTAX:
    1500           0 :     return pari_strdup(GSTR(gel(e,2)));
    1501             :   case e_TYPE:
    1502       12424 :     return pari_sprintf("incorrect type in %Ps (%s).",
    1503       12424 :                         gel(e,2), type_name(typ(gel(e,3))));
    1504             :   case e_USER:
    1505          14 :     return pari_sprint0("user error: ", gel(e,2), f_RAW);
    1506             :   case e_VAR:
    1507             :     {
    1508         203 :       GEN x = gel(e,3), y = gel(e,4);
    1509         609 :       return pari_sprintf("inconsistent variables in %Ps, %Ps != %Ps.",
    1510         609 :                           gel(e,2), pol_x(varn(x)), pol_x(varn(y)));
    1511             :     }
    1512             :   }
    1513             :   return NULL; /*LCOV_EXCL_LINE*/
    1514             : }
    1515             : 
    1516             : static int
    1517       16408 : pari_err_display(GEN err)
    1518             : {
    1519       16408 :   long numerr=err_get_num(err);
    1520       16408 :   err_init();
    1521       16408 :   if (numerr==e_SYNTAX)
    1522             :   {
    1523          35 :     const char *msg = GSTR(gel(err,2));
    1524          35 :     const char *s     = (const char *) gmael(err,3,1);
    1525          35 :     const char *entry = (const char *) gmael(err,3,2);
    1526          35 :     print_errcontext(pariErr, msg, s, entry);
    1527             :   }
    1528             :   else
    1529             :   {
    1530       16373 :     char *s = pari_err2str(err);
    1531       16373 :     closure_err(0);
    1532       16373 :     err_init_msg(numerr==e_USER);
    1533       16373 :     pariErr->puts(s);
    1534       16373 :     if (numerr==e_NOTFUNC)
    1535             :     {
    1536        2723 :       GEN fun = gel(err,2);
    1537        2723 :       if (gequalX(fun))
    1538             :       {
    1539        2723 :         entree *ep = varentries[varn(fun)];
    1540        2723 :         const char *s = ep->name;
    1541        2723 :         if (cb_pari_whatnow) cb_pari_whatnow(pariErr,s,1);
    1542             :       }
    1543             :     }
    1544       16359 :     pari_free(s);
    1545             :   }
    1546       16394 :   out_term_color(pariErr, c_NONE);
    1547       16394 :   pariErr->flush(); return 0;
    1548             : }
    1549             : 
    1550             : void
    1551       31215 : pari_err(int numerr, ...)
    1552             : {
    1553             :   va_list ap;
    1554             :   GEN E;
    1555             : 
    1556       31215 :   va_start(ap,numerr);
    1557             : 
    1558       31215 :   if (numerr)
    1559       31199 :     E = pari_err2GEN(numerr,ap);
    1560             :   else
    1561             :   {
    1562          16 :     E = va_arg(ap,GEN);
    1563          16 :     numerr = err_get_num(E);
    1564             :   }
    1565       31215 :   global_err_data = E;
    1566       31215 :   if (*iferr_env) longjmp(*iferr_env, numerr);
    1567       16410 :   mt_err_recover(numerr);
    1568       16408 :   va_end(ap);
    1569       32802 :   if (cb_pari_err_handle &&
    1570       16408 :       cb_pari_err_handle(E)) return;
    1571       32781 :   if (cb_pari_handle_exception &&
    1572       16394 :       cb_pari_handle_exception(numerr)) return;
    1573       16387 :   err_recover(numerr);
    1574             : }
    1575             : 
    1576             : GEN
    1577       29599 : pari_err_last(void) { return global_err_data; }
    1578             : 
    1579             : const char *
    1580        7340 : numerr_name(long numerr)
    1581             : {
    1582        7340 :   switch ((enum err_list) numerr)
    1583             :   {
    1584           0 :   case e_ALARM:    return "e_ALARM";
    1585           0 :   case e_ARCH:     return "e_ARCH";
    1586           0 :   case e_BUG:      return "e_BUG";
    1587           0 :   case e_COMPONENT: return "e_COMPONENT";
    1588           0 :   case e_CONSTPOL: return "e_CONSTPOL";
    1589           0 :   case e_COPRIME:  return "e_COPRIME";
    1590           0 :   case e_DIM:      return "e_DIM";
    1591          56 :   case e_DOMAIN:   return "e_DOMAIN";
    1592           0 :   case e_FILE:     return "e_FILE";
    1593           7 :   case e_FLAG:     return "e_FLAG";
    1594          28 :   case e_IMPL:     return "e_IMPL";
    1595          95 :   case e_INV:      return "e_INV";
    1596           0 :   case e_IRREDPOL: return "e_IRREDPOL";
    1597           0 :   case e_MAXPRIME: return "e_MAXPRIME";
    1598           0 :   case e_MEM:      return "e_MEM";
    1599           0 :   case e_MISC:     return "e_MISC";
    1600           0 :   case e_MODULUS:  return "e_MODULUS";
    1601           0 :   case e_NONE:     return "e_NONE";
    1602           0 :   case e_NOTFUNC:  return "e_NOTFUNC";
    1603           0 :   case e_OP:       return "e_OP";
    1604           0 :   case e_OVERFLOW: return "e_OVERFLOW";
    1605           0 :   case e_PACKAGE:  return "e_PACKAGE";
    1606           0 :   case e_PREC:     return "e_PREC";
    1607           0 :   case e_PRIME:    return "e_PRIME";
    1608          49 :   case e_PRIORITY: return "e_PRIORITY";
    1609           0 :   case e_ROOTS0:   return "e_ROOTS0";
    1610           0 :   case e_SQRTN:    return "e_SQRTN";
    1611           0 :   case e_STACK:    return "e_STACK";
    1612           0 :   case e_SYNTAX:   return "e_SYNTAX";
    1613           0 :   case e_STACKTHREAD:   return "e_STACKTHREAD";
    1614           0 :   case e_TYPE2:    return "e_TYPE2";
    1615        7105 :   case e_TYPE:     return "e_TYPE";
    1616           0 :   case e_USER:     return "e_USER";
    1617           0 :   case e_VAR:      return "e_VAR";
    1618             :   }
    1619           0 :   return "invalid error number";
    1620             : }
    1621             : 
    1622             : long
    1623          21 : name_numerr(const char *s)
    1624             : {
    1625          21 :   if (!strcmp(s,"e_ALARM"))    return e_ALARM;
    1626          21 :   if (!strcmp(s,"e_ARCH"))     return e_ARCH;
    1627          21 :   if (!strcmp(s,"e_BUG"))      return e_BUG;
    1628          21 :   if (!strcmp(s,"e_COMPONENT")) return e_COMPONENT;
    1629          21 :   if (!strcmp(s,"e_CONSTPOL")) return e_CONSTPOL;
    1630          21 :   if (!strcmp(s,"e_COPRIME"))  return e_COPRIME;
    1631          21 :   if (!strcmp(s,"e_DIM"))      return e_DIM;
    1632          21 :   if (!strcmp(s,"e_DOMAIN"))   return e_DOMAIN;
    1633          21 :   if (!strcmp(s,"e_FILE"))     return e_FILE;
    1634          21 :   if (!strcmp(s,"e_FLAG"))     return e_FLAG;
    1635          21 :   if (!strcmp(s,"e_IMPL"))     return e_IMPL;
    1636          21 :   if (!strcmp(s,"e_INV"))      return e_INV;
    1637           0 :   if (!strcmp(s,"e_IRREDPOL")) return e_IRREDPOL;
    1638           0 :   if (!strcmp(s,"e_MAXPRIME")) return e_MAXPRIME;
    1639           0 :   if (!strcmp(s,"e_MEM"))      return e_MEM;
    1640           0 :   if (!strcmp(s,"e_MISC"))     return e_MISC;
    1641           0 :   if (!strcmp(s,"e_MODULUS"))  return e_MODULUS;
    1642           0 :   if (!strcmp(s,"e_NONE"))     return e_NONE;
    1643           0 :   if (!strcmp(s,"e_NOTFUNC"))  return e_NOTFUNC;
    1644           0 :   if (!strcmp(s,"e_OP"))       return e_OP;
    1645           0 :   if (!strcmp(s,"e_OVERFLOW")) return e_OVERFLOW;
    1646           0 :   if (!strcmp(s,"e_PACKAGE"))  return e_PACKAGE;
    1647           0 :   if (!strcmp(s,"e_PREC"))     return e_PREC;
    1648           0 :   if (!strcmp(s,"e_PRIME"))    return e_PRIME;
    1649           0 :   if (!strcmp(s,"e_PRIORITY")) return e_PRIORITY;
    1650           0 :   if (!strcmp(s,"e_ROOTS0"))   return e_ROOTS0;
    1651           0 :   if (!strcmp(s,"e_SQRTN"))    return e_SQRTN;
    1652           0 :   if (!strcmp(s,"e_STACK"))    return e_STACK;
    1653           0 :   if (!strcmp(s,"e_SYNTAX"))   return e_SYNTAX;
    1654           0 :   if (!strcmp(s,"e_TYPE"))     return e_TYPE;
    1655           0 :   if (!strcmp(s,"e_TYPE2"))    return e_TYPE2;
    1656           0 :   if (!strcmp(s,"e_USER"))     return e_USER;
    1657           0 :   if (!strcmp(s,"e_VAR"))      return e_VAR;
    1658           0 :   pari_err(e_MISC,"unknown error name");
    1659             :   return -1; /* LCOV_EXCL_LINE */
    1660             : }
    1661             : 
    1662             : GEN
    1663        7340 : errname(GEN err)
    1664             : {
    1665        7340 :   if (typ(err)!=t_ERROR) pari_err_TYPE("errname",err);
    1666        7340 :   return strtoGENstr(numerr_name(err_get_num(err)));
    1667             : }
    1668             : 
    1669             : /* Try f (trapping error e), recover using r (break_loop, if NULL) */
    1670             : GEN
    1671          21 : trap0(const char *e, GEN r, GEN f)
    1672             : {
    1673          21 :   long numerr = CATCH_ALL;
    1674             :   GEN x;
    1675          21 :   if (!e || !*e) numerr = CATCH_ALL;
    1676          21 :   else numerr = name_numerr(e);
    1677          21 :   if (!f) {
    1678           0 :     pari_warn(warner,"default handlers are no longer supported --> ignored");
    1679           0 :     return gnil;
    1680             :   }
    1681          21 :   x = closure_trapgen(f, numerr);
    1682          14 :   if (x == (GEN)1L) x = r? closure_evalgen(r): gnil;
    1683          14 :   return x;
    1684             : }
    1685             : 
    1686             : /*******************************************************************/
    1687             : /*                                                                */
    1688             : /*                       CLONING & COPY                            */
    1689             : /*                  Replicate an existing GEN                      */
    1690             : /*                                                                 */
    1691             : /*******************************************************************/
    1692             : /* lontyp[tx] = 0 (non recursive type) or number of codewords for type tx */
    1693             : const  long lontyp[] = { 0,0,0,1,1,2,1,2,1,1, 2,2,0,1,1,1,1,1,1,1, 2,0,0,2,2,1 };
    1694             : 
    1695             : static GEN
    1696         690 : list_internal_copy(GEN z, long nmax)
    1697             : {
    1698             :   long i, l;
    1699             :   GEN a;
    1700         690 :   if (!z) return NULL;
    1701         560 :   l = lg(z);
    1702         560 :   a = newblock(nmax+1);
    1703         560 :   for (i = 1; i < l; i++) gel(a,i) = gel(z,i)? gclone(gel(z,i)): gen_0;
    1704         560 :   a[0] = z[0]; return a;
    1705             : }
    1706             : 
    1707             : static void
    1708         690 : listassign(GEN x, GEN y)
    1709             : {
    1710         690 :   long nmax = list_nmax(x);
    1711         690 :   GEN L = list_data(x);
    1712         690 :   if (!nmax && L) nmax = lg(L) + 32; /* not malloc'ed yet */
    1713         690 :   y[1] = evaltyp(list_typ(x))|evallg(nmax);
    1714         690 :   list_data(y) = list_internal_copy(L, nmax);
    1715         690 : }
    1716             : 
    1717             : /* copy list on the PARI stack */
    1718             : GEN
    1719         165 : listcopy(GEN x)
    1720             : {
    1721         165 :   GEN y = mklist(), L = list_data(x);
    1722         165 :   if (L) list_data(y) = gcopy(L);
    1723         165 :   y[1] = evaltyp(list_typ(x));
    1724         165 :   return y;
    1725             : }
    1726             : 
    1727             : GEN
    1728  3114967039 : gcopy(GEN x)
    1729             : {
    1730  3114967039 :   long tx = typ(x), lx, i;
    1731             :   GEN y;
    1732  3114967039 :   switch(tx)
    1733             :   { /* non recursive types */
    1734  2890830499 :     case t_INT: return signe(x)? icopy(x): gen_0;
    1735             :     case t_REAL:
    1736             :     case t_STR:
    1737   123192724 :     case t_VECSMALL: return leafcopy(x);
    1738             :     /* one more special case */
    1739         165 :     case t_LIST: return listcopy(x);
    1740             :   }
    1741   100943651 :   y = cgetg_copy(x, &lx);
    1742   100943650 :   if (lontyp[tx] == 1) i = 1; else { y[1] = x[1]; i = 2; }
    1743   100943650 :   for (; i<lx; i++) gel(y,i) = gcopy(gel(x,i));
    1744   100943651 :   return y;
    1745             : }
    1746             : 
    1747             : /* as gcopy, but truncate to the first lx components if recursive type
    1748             :  * [ leaves use their own lg ]. No checks. */
    1749             : GEN
    1750         588 : gcopy_lg(GEN x, long lx)
    1751             : {
    1752         588 :   long tx = typ(x), i;
    1753             :   GEN y;
    1754         588 :   switch(tx)
    1755             :   { /* non recursive types */
    1756           0 :     case t_INT: return signe(x)? icopy(x): gen_0;
    1757             :     case t_REAL:
    1758             :     case t_STR:
    1759           0 :     case t_VECSMALL: return leafcopy(x);
    1760             :     /* one more special case */
    1761           0 :     case t_LIST: return listcopy(x);
    1762             :   }
    1763         588 :   y = cgetg(lx, tx);
    1764         588 :   if (lontyp[tx] == 1) i = 1; else { y[1] = x[1]; i = 2; }
    1765         588 :   for (; i<lx; i++) gel(y,i) = gcopy(gel(x,i));
    1766         588 :   return y;
    1767             : }
    1768             : 
    1769             : /* cf cgetg_copy: "allocate" (by updating first codeword only) for subsequent
    1770             :  * copy of x, as if avma = *AVMA */
    1771             : INLINE GEN
    1772   186765574 : cgetg_copy_avma(GEN x, long *plx, pari_sp *AVMA) {
    1773             :   GEN z;
    1774   186765574 :   *plx = lg(x);
    1775   186765574 :   z = ((GEN)*AVMA) - *plx;
    1776   186765574 :   z[0] = x[0] & (TYPBITS|LGBITS);
    1777   186765574 :   *AVMA = (pari_sp)z; return z;
    1778             : }
    1779             : INLINE GEN
    1780         133 : cgetlist_avma(pari_sp *AVMA)
    1781             : {
    1782         133 :   GEN y = ((GEN)*AVMA) - 3;
    1783         133 :   y[0] = _evallg(3) | evaltyp(t_LIST);
    1784         133 :   *AVMA = (pari_sp)y; return y;
    1785             : }
    1786             : 
    1787             : /* copy x as if avma = *AVMA, update *AVMA */
    1788             : GEN
    1789  2538106390 : gcopy_avma(GEN x, pari_sp *AVMA)
    1790             : {
    1791  2538106390 :   long i, lx, tx = typ(x);
    1792             :   GEN y;
    1793             : 
    1794  2538106390 :   switch(typ(x))
    1795             :   { /* non recursive types */
    1796             :     case t_INT:
    1797  2480481855 :       *AVMA = (pari_sp)icopy_avma(x, *AVMA);
    1798  2480481767 :       return (GEN)*AVMA;
    1799             :     case t_REAL: case t_STR: case t_VECSMALL:
    1800    14002483 :       *AVMA = (pari_sp)leafcopy_avma(x, *AVMA);
    1801    14002491 :       return (GEN)*AVMA;
    1802             : 
    1803             :     /* one more special case */
    1804             :     case t_LIST:
    1805         133 :       y = cgetlist_avma(AVMA);
    1806         133 :       listassign(x, y); return y;
    1807             : 
    1808             :   }
    1809    43621919 :   y = cgetg_copy_avma(x, &lx, AVMA);
    1810    43621935 :   if (lontyp[tx] == 1) i = 1; else { y[1] = x[1]; i = 2; }
    1811    43621935 :   for (; i<lx; i++) gel(y,i) = gcopy_avma(gel(x,i), AVMA);
    1812    43621916 :   return y;
    1813             : }
    1814             : 
    1815             : /* [copy_bin/bin_copy:] same as gcopy_avma but use NULL to code an exact 0, and
    1816             :  * make shallow copies of finalized t_LISTs */
    1817             : static GEN
    1818   766579527 : gcopy_av0(GEN x, pari_sp *AVMA)
    1819             : {
    1820   766579527 :   long i, lx, tx = typ(x);
    1821             :   GEN y;
    1822             : 
    1823   766579527 :   switch(tx)
    1824             :   { /* non recursive types */
    1825             :     case t_INT:
    1826   548650278 :       if (!signe(x)) return NULL; /* special marker */
    1827   284855263 :       *AVMA = (pari_sp)icopy_avma(x, *AVMA);
    1828   284855252 :       return (GEN)*AVMA;
    1829             :     case t_LIST:
    1830          49 :       if (list_data(x) && !list_nmax(x)) break; /* not finalized, need copy */
    1831             :       /* else finalized: shallow copy */
    1832             :     case t_REAL: case t_STR: case t_VECSMALL:
    1833    74785748 :       *AVMA = (pari_sp)leafcopy_avma(x, *AVMA);
    1834    74785766 :       return (GEN)*AVMA;
    1835             :   }
    1836   143143501 :   y = cgetg_copy_avma(x, &lx, AVMA);
    1837   143143540 :   if (lontyp[tx] == 1) i = 1; else { y[1] = x[1]; i = 2; }
    1838   143143540 :   for (; i<lx; i++) gel(y,i) = gcopy_av0(gel(x,i), AVMA);
    1839   143143670 :   return y;
    1840             : }
    1841             : 
    1842             : INLINE GEN
    1843           0 : icopy_avma_canon(GEN x, pari_sp AVMA)
    1844             : {
    1845           0 :   long i, lx = lgefint(x);
    1846           0 :   GEN y = ((GEN)AVMA) - lx;
    1847           0 :   y[0] = evaltyp(t_INT)|evallg(lx); /* kills isclone */
    1848           0 :   y[1] = x[1]; x = int_MSW(x);
    1849           0 :   for (i=2; i<lx; i++, x = int_precW(x)) y[i] = *x;
    1850           0 :   return y;
    1851             : }
    1852             : 
    1853             : /* [copy_bin_canon:] same as gcopy_av0, but copy integers in
    1854             :  * canonical (native kernel) form and make a full copy of t_LISTs */
    1855             : static GEN
    1856           0 : gcopy_av0_canon(GEN x, pari_sp *AVMA)
    1857             : {
    1858           0 :   long i, lx, tx = typ(x);
    1859             :   GEN y;
    1860             : 
    1861           0 :   switch(tx)
    1862             :   { /* non recursive types */
    1863             :     case t_INT:
    1864           0 :       if (!signe(x)) return NULL; /* special marker */
    1865           0 :       *AVMA = (pari_sp)icopy_avma_canon(x, *AVMA);
    1866           0 :       return (GEN)*AVMA;
    1867             :     case t_REAL: case t_STR: case t_VECSMALL:
    1868           0 :       *AVMA = (pari_sp)leafcopy_avma(x, *AVMA);
    1869           0 :       return (GEN)*AVMA;
    1870             : 
    1871             :     /* one more special case */
    1872             :     case t_LIST:
    1873             :     {
    1874           0 :       long t = list_typ(x);
    1875           0 :       GEN y = cgetlist_avma(AVMA), z = list_data(x);
    1876           0 :       if (z) {
    1877           0 :         list_data(y) = gcopy_av0_canon(z, AVMA);
    1878           0 :         y[1] = evaltyp(t)|evallg(lg(z)-1);
    1879             :       } else {
    1880           0 :         list_data(y) = NULL;
    1881           0 :         y[1] = evaltyp(t);
    1882             :       }
    1883           0 :       return y;
    1884             :     }
    1885             :   }
    1886           0 :   y = cgetg_copy_avma(x, &lx, AVMA);
    1887           0 :   if (lontyp[tx] == 1) i = 1; else { y[1] = x[1]; i = 2; }
    1888           0 :   for (; i<lx; i++) gel(y,i) = gcopy_av0_canon(gel(x,i), AVMA);
    1889           0 :   return y;
    1890             : }
    1891             : 
    1892             : /* [copy_bin/bin_copy:] size (number of words) required for
    1893             :  * gcopy_av0_canon(x) */
    1894             : static long
    1895           0 : taille0_canon(GEN x)
    1896             : {
    1897           0 :   long i,n,lx, tx = typ(x);
    1898           0 :   switch(tx)
    1899             :   { /* non recursive types */
    1900           0 :     case t_INT: return signe(x)? lgefint(x): 0;
    1901             :     case t_REAL:
    1902             :     case t_STR:
    1903           0 :     case t_VECSMALL: return lg(x);
    1904             : 
    1905             :     /* one more special case */
    1906             :     case t_LIST:
    1907             :     {
    1908           0 :       GEN L = list_data(x);
    1909           0 :       return L? 3 + taille0_canon(L): 3;
    1910             :     }
    1911             :   }
    1912           0 :   n = lx = lg(x);
    1913           0 :   for (i=lontyp[tx]; i<lx; i++) n += taille0_canon(gel(x,i));
    1914           0 :   return n;
    1915             : }
    1916             : 
    1917             : /* [copy_bin/bin_copy:] size (number of words) required for gcopy_av0(x) */
    1918             : static long
    1919   766580218 : taille0(GEN x)
    1920             : {
    1921   766580218 :   long i,n,lx, tx = typ(x);
    1922   766580218 :   switch(tx)
    1923             :   { /* non recursive types */
    1924             :     case t_INT:
    1925   548650736 :       lx = lgefint(x);
    1926   548650736 :       return lx == 2? 0: lx;
    1927             :     case t_LIST:
    1928             :     {
    1929          49 :       GEN L = list_data(x);
    1930          49 :       if (L && !list_nmax(x)) break; /* not finalized, deep copy */
    1931             :     }
    1932             :     /* else finalized: shallow */
    1933             :     case t_REAL:
    1934             :     case t_STR:
    1935             :     case t_VECSMALL:
    1936    74785777 :       return lg(x);
    1937             :   }
    1938   143143705 :   n = lx = lg(x);
    1939   143143705 :   for (i=lontyp[tx]; i<lx; i++) n += taille0(gel(x,i));
    1940   143143722 :   return n;
    1941             : }
    1942             : 
    1943             : /* How many words do we need to allocate to copy x ? t_LIST is a special case
    1944             :  * since list_data() is malloc'ed later, in list_internal_copy() */
    1945             : static long
    1946  2675749229 : words_to_allocate(GEN x)
    1947             : {
    1948  2675749229 :   long i,n,lx, tx = typ(x);
    1949  2675749229 :   switch(tx)
    1950             :   { /* non recursive types */
    1951  2575827910 :     case t_INT: return lgefint(x);
    1952             :     case t_REAL:
    1953             :     case t_STR:
    1954    19787300 :     case t_VECSMALL: return lg(x);
    1955             : 
    1956         697 :     case t_LIST: return 3;
    1957             :     default:
    1958    80133322 :       n = lx = lg(x);
    1959    80133322 :       for (i=lontyp[tx]; i<lx; i++) n += words_to_allocate(gel(x,i));
    1960    80133317 :       return n;
    1961             :   }
    1962             : }
    1963             : 
    1964             : long
    1965        6720 : gsizeword(GEN x)
    1966             : {
    1967             :   GEN L;
    1968        6720 :   if (typ(x) != t_LIST) return words_to_allocate(x);
    1969             :   /* For t_LIST, return the actual list size, words_to_allocate() is always 3 */
    1970         147 :   L = list_data(x);
    1971         147 :   return L? 3 + words_to_allocate(L): 3;
    1972             : }
    1973             : long
    1974          21 : gsizebyte(GEN x) { return gsizeword(x) * sizeof(long); }
    1975             : 
    1976             : /* return a clone of x structured as a gcopy */
    1977             : GENbin*
    1978    37819623 : copy_bin(GEN x)
    1979             : {
    1980    37819623 :   long t = taille0(x);
    1981    37819610 :   GENbin *p = (GENbin*)pari_malloc(sizeof(GENbin) + t*sizeof(long));
    1982    37819667 :   pari_sp AVMA = (pari_sp)(GENbinbase(p) + t);
    1983    37819651 :   p->rebase = &shiftaddress;
    1984    37819651 :   p->len = t;
    1985    37819651 :   p->x   = gcopy_av0(x, &AVMA);
    1986    37819631 :   p->base= (GEN)AVMA; return p;
    1987             : }
    1988             : 
    1989             : /* same, writing t_INT in canonical native form */
    1990             : GENbin*
    1991           0 : copy_bin_canon(GEN x)
    1992             : {
    1993           0 :   long t = taille0_canon(x);
    1994           0 :   GENbin *p = (GENbin*)pari_malloc(sizeof(GENbin) + t*sizeof(long));
    1995           0 :   pari_sp AVMA = (pari_sp)(GENbinbase(p) + t);
    1996           0 :   p->rebase = &shiftaddress_canon;
    1997           0 :   p->len = t;
    1998           0 :   p->x   = gcopy_av0_canon(x, &AVMA);
    1999           0 :   p->base= (GEN)AVMA; return p;
    2000             : }
    2001             : 
    2002             : GEN
    2003   137555845 : gclone(GEN x)
    2004             : {
    2005   137555845 :   long i,lx,tx = typ(x), t = words_to_allocate(x);
    2006   137555846 :   GEN y = newblock(t);
    2007   137555846 :   switch(tx)
    2008             :   { /* non recursive types */
    2009             :     case t_INT:
    2010    95209283 :       lx = lgefint(x);
    2011    95209283 :       y[0] = evaltyp(t_INT)|evallg(lx);
    2012    95209283 :       for (i=1; i<lx; i++) y[i] = x[i];
    2013    95209283 :       break;
    2014             :     case t_REAL:
    2015             :     case t_STR:
    2016             :     case t_VECSMALL:
    2017     5872565 :       lx = lg(x);
    2018     5872565 :       for (i=0; i<lx; i++) y[i] = x[i];
    2019     5872565 :       break;
    2020             : 
    2021             :     /* one more special case */
    2022             :     case t_LIST:
    2023         557 :       y[0] = evaltyp(t_LIST)|_evallg(3);
    2024         557 :       listassign(x, y);
    2025         557 :       break;
    2026             :     default: {
    2027    36473441 :       pari_sp AVMA = (pari_sp)(y + t);
    2028    36473441 :       lx = lg(x);
    2029    36473441 :       y[0] = x[0];
    2030    36473441 :       if (lontyp[tx] == 1) i = 1; else { y[1] = x[1]; i = 2; }
    2031    36473441 :       for (; i<lx; i++) gel(y,i) = gcopy_avma(gel(x,i), &AVMA);
    2032             :     }
    2033             :   }
    2034   137555846 :   setisclone(y); return y;
    2035             : }
    2036             : 
    2037             : void
    2038   502784615 : shiftaddress(GEN x, long dec)
    2039             : {
    2040   502784615 :   long i, lx, tx = typ(x);
    2041   502784615 :   if (is_recursive_t(tx))
    2042             :   {
    2043   143143746 :     if (tx == t_LIST)
    2044             :     {
    2045   502784717 :       if (!list_data(x) || list_nmax(x)) return; /* empty or finalized */
    2046             :       /* not finalized, update pointers  */
    2047             :     }
    2048   143143704 :     lx = lg(x);
    2049   871904007 :     for (i=lontyp[tx]; i<lx; i++) {
    2050   728760255 :       if (!x[i]) gel(x,i) = gen_0;
    2051             :       else
    2052             :       {
    2053   464967605 :         x[i] += dec;
    2054   464967605 :         shiftaddress(gel(x,i), dec);
    2055             :       }
    2056             :     }
    2057             :   }
    2058             : }
    2059             : 
    2060             : void
    2061           0 : shiftaddress_canon(GEN x, long dec)
    2062             : {
    2063           0 :   long i, lx, tx = typ(x);
    2064           0 :   switch(tx)
    2065             :   { /* non recursive types */
    2066             :     case t_INT: {
    2067             :       GEN y;
    2068           0 :       lx = lgefint(x); if (lx <= 3) return;
    2069           0 :       y = x + 2;
    2070           0 :       x = int_MSW(x);  if (x == y) return;
    2071           0 :       while (x > y) { lswap(*x, *y); x = int_precW(x); y++; }
    2072           0 :       break;
    2073             :     }
    2074             :     case t_REAL:
    2075             :     case t_STR:
    2076             :     case t_VECSMALL:
    2077           0 :       break;
    2078             : 
    2079             :     /* one more special case */
    2080             :     case t_LIST: {
    2081           0 :       GEN Lx = list_data(x);
    2082           0 :       if (Lx) {
    2083           0 :         pari_sp av = avma;
    2084           0 :         GEN L = (GEN)((long)Lx+dec);
    2085           0 :         shiftaddress_canon(L, dec);
    2086           0 :         list_data(x) = list_internal_copy(L, lg(L)); avma = av;
    2087             :       }
    2088             :     }
    2089             :     default:
    2090           0 :       lx = lg(x);
    2091           0 :       for (i=lontyp[tx]; i<lx; i++) {
    2092           0 :         if (!x[i]) gel(x,i) = gen_0;
    2093             :         else
    2094             :         {
    2095           0 :           x[i] += dec;
    2096           0 :           shiftaddress_canon(gel(x,i), dec);
    2097             :         }
    2098             :       }
    2099             :   }
    2100             : }
    2101             : 
    2102             : /********************************************************************/
    2103             : /**                                                                **/
    2104             : /**                INSERT DYNAMIC OBJECT IN STRUCTURE              **/
    2105             : /**                                                                **/
    2106             : /********************************************************************/
    2107             : GEN
    2108          21 : obj_reinit(GEN S)
    2109             : {
    2110          21 :   GEN s, T = leafcopy(S);
    2111          21 :   long a = lg(T)-1;
    2112          21 :   s = gel(T,a);
    2113          21 :   gel(T,a) = zerovec(lg(s)-1);
    2114          21 :   return T;
    2115             : }
    2116             : 
    2117             : GEN
    2118     1834406 : obj_init(long d, long n)
    2119             : {
    2120     1834406 :   GEN S = cgetg(d+2, t_VEC);
    2121     1834405 :   gel(S, d+1) = zerovec(n);
    2122     1834406 :   return S;
    2123             : }
    2124             : /* insert O in S [last position] at position K, return it */
    2125             : GEN
    2126     1086709 : obj_insert(GEN S, long K, GEN O)
    2127     1086709 : { return obj_insert_shallow(S, K, gclone(O)); }
    2128             : /* as obj_insert. WITHOUT cloning (for libpari, when creating a *new* obj
    2129             :  * from an existing one) */
    2130             : GEN
    2131     1090538 : obj_insert_shallow(GEN S, long K, GEN O)
    2132             : {
    2133     1090538 :   GEN o, v = gel(S, lg(S)-1);
    2134     1090538 :   if (typ(v) != t_VEC) pari_err_TYPE("obj_insert", S);
    2135     1090538 :   o = gel(v,K);
    2136     1090538 :   gel(v,K) = O; /*SIGINT: before unclone(o)*/
    2137     1090538 :   if (isclone(o)) gunclone(o);
    2138     1090538 :   return gel(v,K);
    2139             : }
    2140             : 
    2141             : /* Does S [last position] contain data at position K ? Return it, or NULL */
    2142             : GEN
    2143     2395095 : obj_check(GEN S, long K)
    2144             : {
    2145     2395095 :   GEN O, v = gel(S, lg(S)-1);
    2146     2395095 :   if (typ(v) != t_VEC || K >= lg(v)) pari_err_TYPE("obj_check", S);
    2147     2395095 :   O = gel(v,K); return isintzero(O)? NULL: O;
    2148             : }
    2149             : 
    2150             : GEN
    2151      723227 : obj_checkbuild(GEN S, long tag, GEN (*build)(GEN))
    2152             : {
    2153      723227 :   GEN O = obj_check(S, tag);
    2154      723227 :   if (!O)
    2155      628934 :   { pari_sp av = avma; O = obj_insert(S, tag, build(S)); avma = av; }
    2156      723227 :   return O;
    2157             : }
    2158             : 
    2159             : GEN
    2160       27210 : obj_checkbuild_prec(GEN S, long tag, GEN (*build)(GEN,long),
    2161             :   long (*pr)(GEN), long prec)
    2162             : {
    2163       27210 :   pari_sp av = avma;
    2164       27210 :   GEN w = obj_check(S, tag);
    2165       27210 :   if (!w || pr(w) < prec) w = obj_insert(S, tag, build(S, prec));
    2166       27210 :   avma = av; return gcopy(w);
    2167             : }
    2168             : GEN
    2169        4439 : obj_checkbuild_realprec(GEN S, long tag, GEN (*build)(GEN,long), long prec)
    2170        4439 : { return obj_checkbuild_prec(S,tag,build,gprecision,prec); }
    2171             : GEN
    2172         455 : obj_checkbuild_padicprec(GEN S, long tag, GEN (*build)(GEN,long), long prec)
    2173         455 : { return obj_checkbuild_prec(S,tag,build,padicprec_relative,prec); }
    2174             : 
    2175             : /* Reset S [last position], freeing all clones */
    2176             : void
    2177        5250 : obj_free(GEN S)
    2178             : {
    2179        5250 :   GEN v = gel(S, lg(S)-1);
    2180             :   long i;
    2181        5250 :   if (typ(v) != t_VEC) pari_err_TYPE("obj_free", S);
    2182       29750 :   for (i = 1; i < lg(v); i++)
    2183             :   {
    2184       24500 :     GEN o = gel(v,i);
    2185       24500 :     if (isclone(o)) gunclone(o);
    2186       24500 :     gel(v,i) = gen_0;
    2187             :   }
    2188        5250 : }
    2189             : 
    2190             : /*******************************************************************/
    2191             : /*                                                                 */
    2192             : /*                         STACK MANAGEMENT                        */
    2193             : /*                                                                 */
    2194             : /*******************************************************************/
    2195             : INLINE void
    2196  2052020441 : dec_gerepile(pari_sp *x, pari_sp av0, pari_sp av, pari_sp tetpil, size_t dec)
    2197             : {
    2198  2052020441 :   if (*x < av && *x >= av0)
    2199             :   { /* update address if in stack */
    2200  1679529421 :     if (*x < tetpil) *x += dec;
    2201           0 :     else pari_err_BUG("gerepile, significant pointers lost");
    2202             :   }
    2203  2052020441 : }
    2204             : 
    2205             : void
    2206      187894 : gerepileallsp(pari_sp av, pari_sp tetpil, int n, ...)
    2207             : {
    2208      187894 :   const pari_sp av0 = avma;
    2209      187894 :   const size_t dec = av-tetpil;
    2210             :   int i;
    2211      187894 :   va_list a; va_start(a, n);
    2212      187894 :   (void)gerepile(av,tetpil,NULL);
    2213      187894 :   for (i=0; i<n; i++) dec_gerepile((pari_sp*)va_arg(a,GEN*), av0,av,tetpil,dec);
    2214      187894 :   va_end(a);
    2215      187894 : }
    2216             : 
    2217             : /* Takes an array of pointers to GENs, of length n.
    2218             :  * Cleans up the stack between av and tetpil, updating those GENs. */
    2219             : void
    2220     5345357 : gerepilemanysp(pari_sp av, pari_sp tetpil, GEN* gptr[], int n)
    2221             : {
    2222     5345357 :   const pari_sp av0 = avma;
    2223     5345357 :   const size_t dec = av-tetpil;
    2224             :   int i;
    2225     5345357 :   (void)gerepile(av,tetpil,NULL);
    2226     5345357 :   for (i=0; i<n; i++) dec_gerepile((pari_sp*)gptr[i], av0, av, tetpil, dec);
    2227     5345357 : }
    2228             : 
    2229             : /* Takes an array of GENs (cast to longs), of length n.
    2230             :  * Cleans up the stack between av and tetpil, updating those GENs. */
    2231             : void
    2232   129722608 : gerepilecoeffssp(pari_sp av, pari_sp tetpil, long *g, int n)
    2233             : {
    2234   129722608 :   const pari_sp av0 = avma;
    2235   129722608 :   const size_t dec = av-tetpil;
    2236             :   int i;
    2237   129722608 :   (void)gerepile(av,tetpil,NULL);
    2238   129722608 :   for (i=0; i<n; i++,g++) dec_gerepile((pari_sp*)g, av0, av, tetpil, dec);
    2239   129722608 : }
    2240             : 
    2241             : static int
    2242           0 : dochk_gerepileupto(GEN av, GEN x)
    2243             : {
    2244             :   long i,lx,tx;
    2245           0 :   if (!isonstack(x)) return 1;
    2246           0 :   if (x > av)
    2247             :   {
    2248           0 :     pari_warn(warner,"bad object %Ps",x);
    2249           0 :     return 0;
    2250             :   }
    2251           0 :   tx = typ(x);
    2252           0 :   if (! is_recursive_t(tx)) return 1;
    2253             : 
    2254           0 :   lx = lg(x);
    2255           0 :   for (i=lontyp[tx]; i<lx; i++)
    2256           0 :     if (!dochk_gerepileupto(av, gel(x,i)))
    2257             :     {
    2258           0 :       pari_warn(warner,"bad component %ld in object %Ps",i,x);
    2259           0 :       return 0;
    2260             :     }
    2261           0 :   return 1;
    2262             : }
    2263             : /* check that x and all its components are out of stack, or have been
    2264             :  * created after av */
    2265             : int
    2266           0 : chk_gerepileupto(GEN x) { return dochk_gerepileupto(x, x); }
    2267             : 
    2268             : /* print stack between avma & av */
    2269             : void
    2270           0 : dbg_gerepile(pari_sp av)
    2271             : {
    2272           0 :   GEN x = (GEN)avma;
    2273           0 :   while (x < (GEN)av)
    2274             :   {
    2275           0 :     const long tx = typ(x), lx = lg(x);
    2276             :     GEN *a;
    2277             : 
    2278           0 :     pari_printf(" [%ld] %Ps:", x - (GEN)avma, x);
    2279           0 :     if (! is_recursive_t(tx)) { pari_putc('\n'); x += lx; continue; }
    2280           0 :     a = (GEN*)x + lontyp[tx]; x += lx;
    2281           0 :     for (  ; a < (GEN*)x; a++)
    2282             :     {
    2283           0 :       if (*a == gen_0)
    2284           0 :         pari_puts("  gen_0");
    2285           0 :       else if (*a == gen_1)
    2286           0 :         pari_puts("  gen_1");
    2287           0 :       else if (*a == gen_m1)
    2288           0 :         pari_puts("  gen_m1");
    2289           0 :       else if (*a == gen_2)
    2290           0 :         pari_puts("  gen_2");
    2291           0 :       else if (*a == gen_m2)
    2292           0 :         pari_puts("  gen_m2");
    2293           0 :       else if (*a == ghalf)
    2294           0 :         pari_puts("  ghalf");
    2295           0 :       else if (isclone(*a))
    2296           0 :         pari_printf("  %Ps (clone)", *a);
    2297             :       else
    2298           0 :         pari_printf("  %Ps [%ld]", *a, *a - (GEN)avma);
    2299           0 :       if (a+1 < (GEN*)x) pari_putc(',');
    2300             :     }
    2301           0 :     pari_printf("\n");
    2302             :   }
    2303           0 : }
    2304             : void
    2305           0 : dbg_gerepileupto(GEN q)
    2306             : {
    2307           0 :   err_printf("%Ps:\n", q);
    2308           0 :   dbg_gerepile((pari_sp) (q+lg(q)));
    2309           0 : }
    2310             : 
    2311             : GEN
    2312   437438472 : gerepile(pari_sp av, pari_sp tetpil, GEN q)
    2313             : {
    2314   437438472 :   const size_t dec = av - tetpil;
    2315   437438472 :   const pari_sp av0 = avma;
    2316             :   GEN x, a;
    2317             : 
    2318   437438472 :   if (dec == 0) return q;
    2319   373455090 :   if ((long)dec < 0) pari_err(e_MISC,"lbot>ltop in gerepile");
    2320             : 
    2321             :   /* dec_gerepile(&q, av0, av, tetpil, dec), saving 1 comparison */
    2322   373426573 :   if (q >= (GEN)av0 && q < (GEN)tetpil)
    2323   241905606 :     q = (GEN) (((pari_sp)q) + dec);
    2324             : 
    2325   373426573 :   for (x = (GEN)av, a = (GEN)tetpil; a > (GEN)av0; ) *--x = *--a;
    2326   373426573 :   avma = (pari_sp)x;
    2327  2751252754 :   while (x < (GEN)av)
    2328             :   {
    2329  2004354280 :     const long tx = typ(x), lx = lg(x);
    2330             : 
    2331  2004354280 :     if (! is_recursive_t(tx)) { x += lx; continue; }
    2332   420822891 :     a = x + lontyp[tx]; x += lx;
    2333   420822891 :     for (  ; a < x; a++) dec_gerepile((pari_sp*)a, av0, av, tetpil, dec);
    2334             :   }
    2335   373471901 :   return q;
    2336             : }
    2337             : 
    2338             : void
    2339           0 : fill_stack(void)
    2340             : {
    2341           0 :   GEN x = ((GEN)pari_mainstack->bot);
    2342           0 :   while (x < (GEN)avma) *x++ = 0xfefefefeUL;
    2343           0 : }
    2344             : 
    2345             : void
    2346           0 : debug_stack(void)
    2347             : {
    2348           0 :   pari_sp top = pari_mainstack->top, bot = pari_mainstack->bot;
    2349             :   GEN z;
    2350           0 :   err_printf("bot=0x%lx\ttop=0x%lx\tavma=0x%lx\n", bot, top, avma);
    2351           0 :   for (z = ((GEN)top)-1; z >= (GEN)avma; z--)
    2352           0 :     err_printf("%p:\t0x%lx\t%lu\n",z,*z,*z);
    2353           0 : }
    2354             : 
    2355             : void
    2356           0 : setdebugvar(long n) { DEBUGVAR=n; }
    2357             : 
    2358             : long
    2359           0 : getdebugvar(void) { return DEBUGVAR; }
    2360             : 
    2361             : long
    2362           7 : getstack(void) { return pari_mainstack->top-avma; }
    2363             : 
    2364             : /*******************************************************************/
    2365             : /*                                                                 */
    2366             : /*                               timer_delay                             */
    2367             : /*                                                                 */
    2368             : /*******************************************************************/
    2369             : 
    2370             : #if defined(USE_CLOCK_GETTIME)
    2371             : #if defined(_POSIX_THREAD_CPUTIME)
    2372             : static THREAD clockid_t time_type = CLOCK_THREAD_CPUTIME_ID;
    2373             : #else
    2374             : static const THREAD clockid_t time_type = CLOCK_PROCESS_CPUTIME_ID;
    2375             : #endif
    2376             : static void
    2377             : pari_init_timer(void)
    2378             : {
    2379             : #if defined(_POSIX_THREAD_CPUTIME)
    2380             :   time_type = CLOCK_PROCESS_CPUTIME_ID;
    2381             : #endif
    2382             : }
    2383             : 
    2384             : void
    2385             : timer_start(pari_timer *T)
    2386             : {
    2387             :   struct timespec t;
    2388             :   clock_gettime(time_type,&t);
    2389             :   T->us = t.tv_nsec / 1000;
    2390             :   T->s  = t.tv_sec;
    2391             : }
    2392             : #elif defined(USE_GETRUSAGE)
    2393             : #ifdef RUSAGE_THREAD
    2394             : static THREAD int rusage_type = RUSAGE_THREAD;
    2395             : #else
    2396             : static const THREAD int rusage_type = RUSAGE_SELF;
    2397             : #endif /*RUSAGE_THREAD*/
    2398             : static void
    2399        1420 : pari_init_timer(void)
    2400             : {
    2401             : #ifdef RUSAGE_THREAD
    2402        1420 :   rusage_type = RUSAGE_SELF;
    2403             : #endif
    2404        1420 : }
    2405             : 
    2406             : void
    2407      460535 : timer_start(pari_timer *T)
    2408             : {
    2409             :   struct rusage r;
    2410      460535 :   getrusage(rusage_type,&r);
    2411      460536 :   T->us = r.ru_utime.tv_usec;
    2412      460536 :   T->s  = r.ru_utime.tv_sec;
    2413      460536 : }
    2414             : #elif defined(USE_FTIME)
    2415             : 
    2416             : static void
    2417             : pari_init_timer(void) { }
    2418             : 
    2419             : void
    2420             : timer_start(pari_timer *T)
    2421             : {
    2422             :   struct timeb t;
    2423             :   ftime(&t);
    2424             :   T->us = ((long)t.millitm) * 1000;
    2425             :   T->s  = t.time;
    2426             : }
    2427             : 
    2428             : #else
    2429             : 
    2430             : static void
    2431             : _get_time(pari_timer *T, long Ticks, long TickPerSecond)
    2432             : {
    2433             :   T->us = (long) ((Ticks % TickPerSecond) * (1000000. / TickPerSecond));
    2434             :   T->s  = Ticks / TickPerSecond;
    2435             : }
    2436             : 
    2437             : # ifdef USE_TIMES
    2438             : static void
    2439             : pari_init_timer(void) { }
    2440             : 
    2441             : void
    2442             : timer_start(pari_timer *T)
    2443             : {
    2444             : # ifdef _SC_CLK_TCK
    2445             :   long tck = sysconf(_SC_CLK_TCK);
    2446             : # else
    2447             :   long tck = CLK_TCK;
    2448             : # endif
    2449             :   struct tms t; times(&t);
    2450             :   _get_time(T, t.tms_utime, tck);
    2451             : }
    2452             : # elif defined(_WIN32)
    2453             : static void
    2454             : pari_init_timer(void) { }
    2455             : 
    2456             : void
    2457             : timer_start(pari_timer *T)
    2458             : { _get_time(T, win32_timer(), 1000); }
    2459             : # else
    2460             : #  include <time.h>
    2461             : #  ifndef CLOCKS_PER_SEC
    2462             : #   define CLOCKS_PER_SEC 1000000 /* may be false on YOUR system */
    2463             : #  endif
    2464             : static void
    2465             : pari_init_timer(void) { }
    2466             : 
    2467             : void
    2468             : timer_start(pari_timer *T)
    2469             : { _get_time(T, clock(), CLOCKS_PER_SEC); }
    2470             : # endif
    2471             : #endif
    2472             : 
    2473             : static long
    2474       59312 : timer_aux(pari_timer *T, pari_timer *U)
    2475             : {
    2476       59312 :   long s = T->s, us = T->us; timer_start(U);
    2477       59312 :   return 1000 * (U->s - s) + (U->us - us + 500) / 1000;
    2478             : }
    2479             : /* return delay, reset timer */
    2480             : long
    2481       57890 : timer_delay(pari_timer *T) { return timer_aux(T, T); }
    2482             : /* return delay, don't reset timer */
    2483             : long
    2484        1422 : timer_get(pari_timer *T) { pari_timer t; return timer_aux(T, &t); }
    2485             : 
    2486             : static void
    2487           0 : timer_vprintf(pari_timer *T, const char *format, va_list args)
    2488             : {
    2489           0 :   out_puts(pariErr, "Time ");
    2490           0 :   out_vprintf(pariErr, format,args);
    2491           0 :   out_printf(pariErr, ": %ld\n", timer_delay(T));
    2492           0 :   pariErr->flush();
    2493           0 : }
    2494             : void
    2495           0 : timer_printf(pari_timer *T, const char *format, ...)
    2496             : {
    2497           0 :   va_list args; va_start(args, format);
    2498           0 :   timer_vprintf(T, format, args);
    2499           0 :   va_end(args);
    2500           0 : }
    2501             : 
    2502             : long
    2503           0 : timer(void)  { static THREAD pari_timer T; return timer_delay(&T);}
    2504             : long
    2505        3320 : gettime(void)  { static THREAD pari_timer T; return timer_delay(&T);}
    2506             : 
    2507             : static THREAD pari_timer timer2_T, abstimer_T;
    2508             : long
    2509           0 : timer2(void) {  return timer_delay(&timer2_T);}
    2510             : void
    2511           0 : msgtimer(const char *format, ...)
    2512             : {
    2513           0 :   va_list args; va_start(args, format);
    2514           0 :   timer_vprintf(&timer2_T, format, args);
    2515           0 :   va_end(args);
    2516           0 : }
    2517             : long
    2518        1420 : getabstime(void)  { return timer_get(&abstimer_T);}
    2519             : #if defined(USE_CLOCK_GETTIME) || defined(USE_GETTIMEOFDAY) \
    2520             :  || defined(USE_FTIMEFORWALLTIME)
    2521             : static GEN
    2522           0 : timetoi(ulong s, ulong m)
    2523             : {
    2524           0 :   pari_sp av = avma;
    2525           0 :   GEN r = addiu(muliu(utoi(s), 1000), m);
    2526           0 :   return gerepileuptoint(av, r);
    2527             : }
    2528             : #endif
    2529             : GEN
    2530           0 : getwalltime(void)
    2531             : {
    2532             : #if defined(USE_CLOCK_GETTIME)
    2533             :   struct timespec t;
    2534             :   if (!clock_gettime(CLOCK_REALTIME,&t))
    2535             :     return timetoi(t.tv_sec, (t.tv_nsec + 500000)/1000000);
    2536             : #elif defined(USE_GETTIMEOFDAY)
    2537             :   struct timeval tv;
    2538           0 :   if (!gettimeofday(&tv, NULL))
    2539           0 :     return timetoi(tv.tv_sec, (tv.tv_usec + 500)/1000);
    2540             : #elif defined(USE_FTIMEFORWALLTIME)
    2541             :   struct timeb tp;
    2542             :   ftime(&tp); return timetoi(tp.time, tp.millitm);
    2543             : #endif
    2544           0 :   return utoi(getabstime());
    2545             : }
    2546             : 
    2547             : /*******************************************************************/
    2548             : /*                                                                 */
    2549             : /*                   FUNCTIONS KNOWN TO THE ANALYZER               */
    2550             : /*                                                                 */
    2551             : /*******************************************************************/
    2552             : GEN
    2553           7 : pari_version(void)
    2554             : {
    2555           7 :   const ulong mask = (1UL<<PARI_VERSION_SHIFT) - 1;
    2556           7 :   ulong major, minor, patch, n = paricfg_version_code;
    2557           7 :   patch = n & mask; n >>= PARI_VERSION_SHIFT;
    2558           7 :   minor = n & mask; n >>= PARI_VERSION_SHIFT;
    2559           7 :   major = n;
    2560           7 :   if (*paricfg_vcsversion) {
    2561           7 :     const char *ver = paricfg_vcsversion;
    2562           7 :     const char *s = strchr(ver, '-');
    2563             :     char t[8];
    2564           7 :     const long len = s-ver;
    2565             :     GEN v;
    2566           7 :     if (!s || len > 6) pari_err_BUG("pari_version()"); /* paranoia */
    2567           7 :     memcpy(t, ver, len); t[len] = 0;
    2568           7 :     v = cgetg(6, t_VEC);
    2569           7 :     gel(v,1) = utoi(major);
    2570           7 :     gel(v,2) = utoi(minor);
    2571           7 :     gel(v,3) = utoi(patch);
    2572           7 :     gel(v,4) = stoi( atoi(t) );
    2573           7 :     gel(v,5) = strtoGENstr(s+1);
    2574           7 :     return v;
    2575             :   } else {
    2576           0 :     GEN v = cgetg(4, t_VEC);
    2577           0 :     gel(v,1) = utoi(major);
    2578           0 :     gel(v,2) = utoi(minor);
    2579           0 :     gel(v,3) = utoi(patch);
    2580           0 :     return v;
    2581             :   }
    2582             : }
    2583             : 
    2584             : /* List of GP functions: generated from the description system.
    2585             :  * Format (struct entree) :
    2586             :  *   char *name   : name (under GP).
    2587             :  *   ulong valence: (EpNEW, EpALIAS,EpVAR, EpINSTALL)|EpSTATIC
    2588             :  *   void *value  : For PREDEFINED FUNCTIONS: C function to call.
    2589             :  *                  For USER FUNCTIONS: pointer to defining data (block) =
    2590             :  *                   entree*: NULL, list of entree (arguments), NULL
    2591             :  *                   char*  : function text
    2592             :  *   long menu    : which help section do we belong to
    2593             :  *                   1: Standard monadic or dyadic OPERATORS
    2594             :  *                   2: CONVERSIONS and similar elementary functions
    2595             :  *                   3: TRANSCENDENTAL functions, etc.
    2596             :  *   char *code   : GP prototype, aka Parser Code (see libpari's manual)
    2597             :  *                  if NULL, use valence instead.
    2598             :  *   char *help   : short help text (init to NULL).
    2599             :  *   void *pvalue : push_val history.
    2600             :  *   long arity   : maximum number of arguments.
    2601             :  *   entree *next : next entree (init to NULL, used in hashing code). */
    2602             : #include "init.h"
    2603             : #include "default.h"

Generated by: LCOV version 1.11