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 to exceed 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.14.0 lcov report (development 26712-590d837a1c) Lines: 1088 1488 73.1 %
Date: 2021-06-22 07:13:04 Functions: 127 162 78.4 %
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; either version 2 of the License, or (at your option) any later
       8             : version. It is distributed in the hope that it will be useful, but WITHOUT
       9             : ANY WARRANTY WHATSOEVER.
      10             : 
      11             : Check the License for details. You should have received a copy of it, along
      12             : with the package; see the file 'COPYING'. If not, write to the Free Software
      13             : Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */
      14             : 
      15             : /*******************************************************************/
      16             : /*                                                                 */
      17             : /*        INITIALIZING THE SYSTEM, ERRORS, STACK MANAGEMENT        */
      18             : /*                                                                 */
      19             : /*******************************************************************/
      20             : /* _GNU_SOURCE is needed before first include to get RUSAGE_THREAD */
      21             : #undef _GNU_SOURCE /* avoid warning */
      22             : #define _GNU_SOURCE
      23             : #include <string.h>
      24             : #if defined(_WIN32) || defined(__CYGWIN32__)
      25             : #  include "../systems/mingw/mingw.h"
      26             : #  include <process.h>
      27             : #endif
      28             : #include "paricfg.h"
      29             : #if defined(STACK_CHECK) && !defined(__EMX__) && !defined(_WIN32)
      30             : #  include <sys/types.h>
      31             : #  include <sys/time.h>
      32             : #  include <sys/resource.h>
      33             : #endif
      34             : #if defined(HAS_WAITPID) && defined(HAS_SETSID)
      35             : #  include <sys/wait.h>
      36             : #endif
      37             : #ifdef HAS_MMAP
      38             : #  include <sys/mman.h>
      39             : #endif
      40             : #if defined(USE_GETTIMEOFDAY) || defined(USE_GETRUSAGE) || defined(USE_TIMES)
      41             : #  include <sys/time.h>
      42             : #endif
      43             : #if defined(USE_GETRUSAGE)
      44             : #  include <sys/resource.h>
      45             : #endif
      46             : #if defined(USE_FTIME) || defined(USE_FTIMEFORWALLTIME)
      47             : #  include <sys/timeb.h>
      48             : #endif
      49             : #if defined(USE_CLOCK_GETTIME) || defined(USE_TIMES)
      50             : #  include <time.h>
      51             : #endif
      52             : #if defined(USE_TIMES)
      53             : #  include <sys/times.h>
      54             : #endif
      55             : #define PARI_INIT
      56             : #include "pari.h"
      57             : #include "paripriv.h"
      58             : #include "anal.h"
      59             : 
      60             : const double LOG10_2 = 0.3010299956639812; /* log_10(2) */
      61             : const double LOG2_10 = 3.321928094887362;  /* log_2(10) */
      62             : 
      63             : GEN gnil, gen_0, gen_1, gen_m1, gen_2, gen_m2, ghalf, err_e_STACK;
      64             : 
      65             : static const ulong readonly_constants[] = {
      66             :   evaltyp(t_INT) | _evallg(2),  /* gen_0 */
      67             :   evallgefint(2),
      68             :   evaltyp(t_INT) | _evallg(2),  /* gnil */
      69             :   evallgefint(2),
      70             :   evaltyp(t_INT) | _evallg(3),  /* gen_1 */
      71             :   evalsigne(1) | evallgefint(3),
      72             :   1,
      73             :   evaltyp(t_INT) | _evallg(3),  /* gen_2 */
      74             :   evalsigne(1) | evallgefint(3),
      75             :   2,
      76             :   evaltyp(t_INT) | _evallg(3),  /* gen_m1 */
      77             :   evalsigne(-1) | evallgefint(3),
      78             :   1,
      79             :   evaltyp(t_INT) | _evallg(3),  /* gen_m2 */
      80             :   evalsigne(-1) | evallgefint(3),
      81             :   2,
      82             :   evaltyp(t_ERROR) | _evallg(2), /* err_e_STACK */
      83             :   e_STACK,
      84             :   evaltyp(t_FRAC) | _evallg(3), /* ghalf */
      85             :   (ulong)(readonly_constants+4),
      86             :   (ulong)(readonly_constants+7)
      87             : };
      88             : THREAD GEN zetazone, bernzone, eulerzone, primetab;
      89             : byteptr diffptr;
      90             : FILE    *pari_outfile, *pari_errfile, *pari_logfile, *pari_infile;
      91             : char    *current_logfile, *current_psfile, *pari_datadir;
      92             : long    gp_colors[c_LAST];
      93             : int     disable_color;
      94             : ulong   DEBUGLEVEL, DEBUGMEM;
      95             : long    DEBUGVAR;
      96             : ulong   pari_mt_nbthreads;
      97             : long    precreal;
      98             : ulong   precdl, pari_logstyle;
      99             : gp_data *GP_DATA;
     100             : 
     101             : entree  **varentries;
     102             : THREAD long *varpriority;
     103             : 
     104             : THREAD pari_sp avma;
     105             : THREAD struct pari_mainstack *pari_mainstack;
     106             : 
     107             : static void ** MODULES;
     108             : static pari_stack s_MODULES;
     109             : const long functions_tblsz = 135; /* size of functions_hash */
     110             : entree **functions_hash, **defaults_hash;
     111             : 
     112             : char *(*cb_pari_fgets_interactive)(char *s, int n, FILE *f);
     113             : int (*cb_pari_get_line_interactive)(const char*, const char*, filtre_t *F);
     114             : void (*cb_pari_quit)(long);
     115             : void (*cb_pari_init_histfile)(void);
     116             : void (*cb_pari_ask_confirm)(const char *);
     117             : int  (*cb_pari_handle_exception)(long);
     118             : int  (*cb_pari_err_handle)(GEN);
     119             : int  (*cb_pari_whatnow)(PariOUT *out, const char *, int);
     120             : void (*cb_pari_sigint)(void);
     121             : void (*cb_pari_pre_recover)(long);
     122             : void (*cb_pari_err_recover)(long);
     123             : int (*cb_pari_break_loop)(int);
     124             : int (*cb_pari_is_interactive)(void);
     125             : void (*cb_pari_start_output)();
     126             : 
     127             : const char * pari_library_path = NULL;
     128             : 
     129             : static THREAD GEN global_err_data;
     130             : THREAD jmp_buf *iferr_env;
     131             : const long CATCH_ALL = -1;
     132             : 
     133             : static void pari_init_timer(void);
     134             : 
     135             : /*********************************************************************/
     136             : /*                                                                   */
     137             : /*                       BLOCKS & CLONES                             */
     138             : /*                                                                   */
     139             : /*********************************************************************/
     140             : /*#define DEBUG*/
     141             : static THREAD long next_block;
     142             : static THREAD GEN cur_block; /* current block in block list */
     143             : static THREAD GEN root_block; /* current block in block list */
     144             : #ifdef DEBUG
     145             : static THREAD long NUM;
     146             : #endif
     147             : 
     148             : static void
     149      209696 : pari_init_blocks(void)
     150             : {
     151      209696 :   next_block = 0; cur_block = NULL; root_block = NULL;
     152             : #ifdef DEBUG
     153             :   NUM = 0;
     154             : #endif
     155      209696 : }
     156             : 
     157             : static void
     158      206423 : pari_close_blocks(void)
     159             : {
     160     6893623 :   while (cur_block) killblock(cur_block);
     161      208664 : }
     162             : 
     163             : static long
     164 11033014975 : blockheight(GEN bl) { return bl? bl_height(bl): 0; }
     165             : 
     166             : static long
     167  2650523541 : blockbalance(GEN bl)
     168  2650523541 : { return bl ? blockheight(bl_left(bl)) - blockheight(bl_right(bl)): 0; }
     169             : 
     170             : static void
     171  2866263140 : fix_height(GEN bl)
     172  2866263140 : { bl_height(bl) = maxss(blockheight(bl_left(bl)), blockheight(bl_right(bl)))+1; }
     173             : 
     174             : static GEN
     175    59340091 : bl_rotright(GEN y)
     176             : {
     177    59340091 :   GEN x = bl_left(y), t = bl_right(x);
     178    59340091 :   bl_right(x) = y;
     179    59340091 :   bl_left(y)  = t;
     180    59340091 :   fix_height(y);
     181    59339764 :   fix_height(x);
     182    59338726 :   return x;
     183             : }
     184             : 
     185             : static GEN
     186    58255085 : bl_rotleft(GEN x)
     187             : {
     188    58255085 :   GEN y = bl_right(x), t = bl_left(y);
     189    58255085 :   bl_left(y)  = x;
     190    58255085 :   bl_right(x) = t;
     191    58255085 :   fix_height(x);
     192    58253099 :   fix_height(y);
     193    58247092 :   return y;
     194             : }
     195             : 
     196             : static GEN
     197  1609639018 : blockinsert(GEN x, GEN bl, long *d)
     198             : {
     199             :   long b, c;
     200  1609639018 :   if (!bl)
     201             :   {
     202   223087151 :     bl_left(x)=NULL; bl_right(x)=NULL;
     203   223087151 :     bl_height(x)=1; return x;
     204             :   }
     205  1386551867 :   c = cmpuu((ulong)x, (ulong)bl);
     206  1386578171 :   if (c < 0)
     207   574168064 :     bl_left(bl) = blockinsert(x, bl_left(bl), d);
     208   812410107 :   else if (c > 0)
     209   812410107 :     bl_right(bl) = blockinsert(x, bl_right(bl), d);
     210           0 :   else return bl; /* ??? Already exist in the tree ? */
     211  1386501200 :   fix_height(bl);
     212  1386405256 :   b = blockbalance(bl);
     213  1386487271 :   if (b > 1)
     214             :   {
     215    33092356 :     if (*d > 0) bl_left(bl) = bl_rotleft(bl_left(bl));
     216    33092074 :     return bl_rotright(bl);
     217             :   }
     218  1353394915 :   if (b < -1)
     219             :   {
     220    29730171 :     if (*d < 0) bl_right(bl) = bl_rotright(bl_right(bl));
     221    29730159 :     return bl_rotleft(bl);
     222             :   }
     223  1323664744 :   *d = c; return bl;
     224             : }
     225             : 
     226             : static GEN
     227  1468027861 : blockdelete(GEN x, GEN bl)
     228             : {
     229             :   long b;
     230  1468027861 :   if (!bl) return NULL; /* ??? Do not exist in the tree */
     231  1468027861 :   if (x < bl)
     232   522990097 :     bl_left(bl) = blockdelete(x, bl_left(bl));
     233   945037764 :   else if (x > bl)
     234   676265522 :     bl_right(bl) = blockdelete(x, bl_right(bl));
     235             :   else
     236             :   {
     237   268772242 :     if (!bl_left(bl) && !bl_right(bl)) return NULL;
     238    92479495 :     else if (!bl_left(bl)) return bl_right(bl);
     239    68655565 :     else if (!bl_right(bl)) return bl_left(bl);
     240             :     else
     241             :     {
     242    45677216 :       GEN r = bl_right(bl);
     243    63343729 :       while (bl_left(r)) r = bl_left(r);
     244    45677216 :       bl_right(r) = blockdelete(r, bl_right(bl));
     245    45687955 :       bl_left(r) = bl_left(bl);
     246    45687955 :       bl = r;
     247             :     }
     248             :   }
     249  1244911778 :   fix_height(bl);
     250  1244862405 :   b = blockbalance(bl);
     251  1244878988 :   if (b > 1)
     252             :   {
     253    13856337 :     if (blockbalance(bl_left(bl)) >= 0) return bl_rotright(bl);
     254             :     else
     255     2367542 :     { bl_left(bl) = bl_rotleft(bl_left(bl)); return bl_rotright(bl); }
     256             :   }
     257  1231022651 :   if (b < -1)
     258             :   {
     259     5510849 :     if (blockbalance(bl_right(bl)) <= 0) return bl_rotleft(bl);
     260             :     else
     261     1324623 :     { bl_right(bl) = bl_rotright(bl_right(bl)); return bl_rotleft(bl); }
     262             :   }
     263  1225511802 :   return bl;
     264             : }
     265             : 
     266             : static GEN
     267   528818630 : blocksearch(GEN x, GEN bl)
     268             : {
     269   528818630 :   if (isclone(x)) return x;
     270   356465647 :   if (isonstack(x) || is_universal_constant(x)) return NULL;
     271   726359800 :   while (bl)
     272             :   {
     273   723991329 :     if (x >= bl  && x < bl + bl_size(bl))
     274   193944444 :       return bl;
     275   530046885 :     bl = x < bl ? bl_left(bl): bl_right(bl);
     276             :   }
     277     2368471 :   return NULL; /* Unknown address */
     278             : }
     279             : 
     280             : static int
     281     1157866 : check_clone(GEN x)
     282             : {
     283     1157866 :   GEN bl = root_block;
     284     1157866 :   if (isonstack(x) || is_universal_constant(x)) return 1;
     285     1269497 :   while (bl)
     286             :   {
     287     1269497 :     if (x >= bl  && x < bl + bl_size(bl))
     288      188034 :       return 1;
     289     1081463 :     bl = x < bl ? bl_left(bl): bl_right(bl);
     290             :   }
     291           0 :   return 0; /* Unknown address */
     292             : }
     293             : 
     294             : void
     295   267371035 : clone_lock(GEN x)
     296             : {
     297   267371035 :   GEN y = blocksearch(x, root_block);
     298   266947849 :   if (y && isclone(y))
     299             :   {
     300   185525259 :     if (DEBUGMEM > 2)
     301           0 :       err_printf("locking block no %ld: %08lx from %08lx\n", bl_num(y), y, x);
     302   185525259 :     ++bl_refc(y);
     303             :   }
     304   266947849 : }
     305             : 
     306             : void
     307   202820570 : clone_unlock(GEN x)
     308             : {
     309   202820570 :   GEN y = blocksearch(x, root_block);
     310   202726030 :   if (y && isclone(y))
     311             :   {
     312   128923480 :     if (DEBUGMEM > 2)
     313           0 :       err_printf("unlocking block no %ld: %08lx from %08lx\n", bl_num(y), y, x);
     314   128923480 :     gunclone(y);
     315             :   }
     316   202726030 : }
     317             : 
     318             : void
     319    58976045 : clone_unlock_deep(GEN x)
     320             : {
     321    58976045 :   GEN y = blocksearch(x, root_block);
     322    58976045 :   if (y && isclone(y))
     323             :   {
     324    51848536 :     if (DEBUGMEM > 2)
     325           0 :       err_printf("unlocking deep block no %ld: %08lx from %08lx\n", bl_num(y), y, x);
     326    51848536 :     gunclone_deep(y);
     327             :   }
     328    58976045 : }
     329             : 
     330             : /* Return x, where:
     331             :  * x[-8]: AVL height
     332             :  * x[-7]: adress of left child or NULL
     333             :  * x[-6]: adress of right child or NULL
     334             :  * x[-5]: size
     335             :  * x[-4]: reference count
     336             :  * x[-3]: adress of next block
     337             :  * x[-2]: adress of preceding block.
     338             :  * x[-1]: number of allocated blocs.
     339             :  * x[0..n-1]: malloc-ed memory. */
     340             : GEN
     341   223080132 : newblock(size_t n)
     342             : {
     343   223080132 :   long d = 0;
     344   223080132 :   long *x = (long *) pari_malloc((n + BL_HEAD)*sizeof(long)) + BL_HEAD;
     345             : 
     346   223093724 :   bl_size(x) = n;
     347   223093724 :   bl_refc(x) = 1;
     348   223093724 :   bl_next(x) = NULL;
     349   223093724 :   bl_prev(x) = cur_block;
     350   223093724 :   bl_num(x)  = next_block++;
     351   223093724 :   if (cur_block) bl_next(cur_block) = x;
     352   223093724 :   root_block = blockinsert(x, root_block, &d);
     353             : #ifdef DEBUG
     354             :   err_printf("+ %ld\n", ++NUM);
     355             : #endif
     356   223084235 :   if (DEBUGMEM > 2)
     357           0 :     err_printf("new block, size %6lu (no %ld): %08lx\n", n, next_block-1, x);
     358   223083904 :   return cur_block = x;
     359             : }
     360             : 
     361             : GEN
     362       31267 : gcloneref(GEN x)
     363             : {
     364       31267 :   if (isclone(x)) { ++bl_refc(x); return x; }
     365       30735 :   else return gclone(x);
     366             : }
     367             : 
     368             : void
     369           0 : gclone_refc(GEN x) { ++bl_refc(x); }
     370             : 
     371             : void
     372   357211182 : gunclone(GEN x)
     373             : {
     374   357211182 :   if (--bl_refc(x) > 0) return;
     375   223091241 :   BLOCK_SIGINT_START;
     376   223097394 :   root_block = blockdelete(x, root_block);
     377   223082682 :   if (bl_next(x)) bl_prev(bl_next(x)) = bl_prev(x);
     378             :   else
     379             :   {
     380    32381032 :     cur_block = bl_prev(x);
     381    32381032 :     next_block = bl_num(x);
     382             :   }
     383   223082682 :   if (bl_prev(x)) bl_next(bl_prev(x)) = bl_next(x);
     384   223082682 :   if (DEBUGMEM > 2)
     385           0 :     err_printf("killing block (no %ld): %08lx\n", bl_num(x), x);
     386   223082682 :   free((void*)bl_base(x)); /* pari_free not needed: we already block */
     387   223082682 :   BLOCK_SIGINT_END;
     388             : #ifdef DEBUG
     389             :   err_printf("- %ld\n", NUM--);
     390             : #endif
     391             : }
     392             : 
     393             : /* Recursively look for clones in the container and kill them. Then kill
     394             :  * container if clone. SIGINT could be blocked until it returns */
     395             : void
     396  2933447998 : gunclone_deep(GEN x)
     397             : {
     398             :   long i, lx;
     399             :   GEN v;
     400  2933447998 :   if (isclone(x) && bl_refc(x) > 1) { --bl_refc(x); return; }
     401  2881597438 :   BLOCK_SIGINT_START;
     402  2881597438 :   switch(typ(x))
     403             :   {
     404   117763078 :     case t_VEC: case t_COL: case t_MAT:
     405   117763078 :       lx = lg(x);
     406  2800990489 :       for (i=1;i<lx;i++) gunclone_deep(gel(x,i));
     407   117763094 :       break;
     408        3093 :     case t_LIST:
     409        3093 :       v = list_data(x); lx = v? lg(v): 1;
     410      833229 :       for (i=1;i<lx;i++) gunclone_deep(gel(v,i));
     411        3093 :       if (v) killblock(v);
     412        3093 :       break;
     413             :   }
     414  2881597454 :   if (isclone(x)) gunclone(x);
     415  2881597262 :   BLOCK_SIGINT_END;
     416             : }
     417             : 
     418             : int
     419      197452 : pop_entree_block(entree *ep, long loc)
     420             : {
     421      197452 :   GEN x = (GEN)ep->value;
     422      197452 :   if (bl_num(x) < loc) return 0; /* older */
     423         371 :   if (DEBUGMEM>2)
     424           0 :     err_printf("popping %s (block no %ld)\n", ep->name, bl_num(x));
     425         371 :   gunclone_deep(x); return 1;
     426             : }
     427             : 
     428             : /***************************************************************************
     429             :  **                                                                       **
     430             :  **                           Export                                      **
     431             :  **                                                                       **
     432             :  ***************************************************************************/
     433             : 
     434             : static hashtable *export_hash;
     435             : static void
     436        1699 : pari_init_export(void)
     437             : {
     438        1699 :   export_hash = hash_create_str(1,0);
     439        1699 : }
     440             : static void
     441        1689 : pari_close_export(void)
     442             : {
     443        1689 :   hash_destroy(export_hash);
     444        1689 : }
     445             : 
     446             : /* Exported values are blocks, but do not have the clone bit set so that they
     447             :  * are not affected by clone_lock and ensure_nb, etc. */
     448             : 
     449             : void
     450          36 : export_add(const char *str, GEN val)
     451             : {
     452             :   hashentry *h;
     453          36 :   val = gclone(val); unsetisclone(val);
     454          36 :   h = hash_search(export_hash, (void*) str);
     455          36 :   if (h)
     456             :   {
     457          21 :     GEN v = (GEN)h->val;
     458          21 :     h->val = val;
     459          21 :     setisclone(v); gunclone(v);
     460             :   }
     461             :   else
     462          15 :     hash_insert(export_hash,(void*)str, (void*) val);
     463          36 : }
     464             : 
     465             : void
     466           8 : export_del(const char *str)
     467             : {
     468           8 :   hashentry *h = hash_remove(export_hash,(void*)str);
     469           8 :   if (h)
     470             :   {
     471           8 :     GEN v = (GEN)h->val;
     472           8 :     setisclone(v); gunclone(v);
     473           8 :     pari_free(h);
     474             :   }
     475           8 : }
     476             : 
     477             : GEN
     478         501 : export_get(const char *str)
     479             : {
     480         501 :   return hash_haskey_GEN(export_hash,(void*)str);
     481             : }
     482             : 
     483             : void
     484           2 : unexportall(void)
     485             : {
     486           2 :   pari_sp av = avma;
     487           2 :   GEN keys = hash_keys(export_hash);
     488           2 :   long i, l = lg(keys);
     489           8 :   for (i = 1; i < l; i++) mt_export_del((const char *)keys[i]);
     490           2 :   set_avma(av);
     491           2 : }
     492             : 
     493             : void
     494           2 : exportall(void)
     495             : {
     496             :   long i;
     497         272 :   for (i = 0; i < functions_tblsz; i++)
     498             :   {
     499             :     entree *ep;
     500        2842 :     for (ep = functions_hash[i]; ep; ep = ep->next)
     501        2572 :       if (EpVALENCE(ep)==EpVAR) mt_export_add(ep->name, (GEN)ep->value);
     502             :   }
     503           2 : }
     504             : 
     505             : /*********************************************************************/
     506             : /*                                                                   */
     507             : /*                       C STACK SIZE CONTROL                        */
     508             : /*                                                                   */
     509             : /*********************************************************************/
     510             : /* Avoid core dump on deep recursion. Adapted Perl code by Dominic Dunlop */
     511             : THREAD void *PARI_stack_limit = NULL;
     512             : 
     513             : #ifdef STACK_CHECK
     514             : 
     515             : #  ifdef __EMX__                                /* Emulate */
     516             : void
     517             : pari_stackcheck_init(void *pari_stack_base)
     518             : {
     519             :   if (!pari_stack_base) { PARI_stack_limit = NULL; return; }
     520             :   PARI_stack_limit = get_stack(1./16, 32*1024);
     521             : }
     522             : #  elif _WIN32
     523             : void
     524             : pari_stackcheck_init(void *pari_stack_base)
     525             : {
     526             :   ulong size = 1UL << 21;
     527             :   if (!pari_stack_base) { PARI_stack_limit = NULL; return; }
     528             :   if (size > (ulong)pari_stack_base)
     529             :     PARI_stack_limit = (void*)(((ulong)pari_stack_base) / 16);
     530             :   else
     531             :     PARI_stack_limit = (void*)((ulong)pari_stack_base - (size/16)*15);
     532             : }
     533             : #  else /* !__EMX__ && !_WIN32 */
     534             : /* Set PARI_stack_limit to (a little above) the lowest safe address that can be
     535             :  * used on the stack. Leave PARI_stack_limit at its initial value (NULL) to
     536             :  * show no check should be made [init failed]. Assume stack grows downward. */
     537             : void
     538      211382 : pari_stackcheck_init(void *pari_stack_base)
     539             : {
     540             :   struct rlimit rip;
     541             :   ulong size;
     542      211382 :   if (!pari_stack_base) { PARI_stack_limit = NULL; return; }
     543      211382 :   if (getrlimit(RLIMIT_STACK, &rip)) return;
     544      211483 :   size = rip.rlim_cur;
     545      211483 :   if (size == (ulong)RLIM_INFINITY || size > (ulong)pari_stack_base)
     546          42 :     PARI_stack_limit = (void*)(((ulong)pari_stack_base) / 16);
     547             :   else
     548      211441 :     PARI_stack_limit = (void*)((ulong)pari_stack_base - (size/16)*15);
     549             : }
     550             : #  endif /* !__EMX__ */
     551             : 
     552             : #else
     553             : void
     554             : pari_stackcheck_init(void *pari_stack_base)
     555             : {
     556             :   (void) pari_stack_base; PARI_stack_limit = NULL;
     557             : }
     558             : #endif /* STACK_CHECK */
     559             : 
     560             : /*******************************************************************/
     561             : /*                         HEAP TRAVERSAL                          */
     562             : /*******************************************************************/
     563             : struct getheap_t { long n, l; };
     564             : /* x is a block, not necessarily a clone [x[0] may not be set] */
     565             : static void
     566        6776 : f_getheap(GEN x, void *D)
     567             : {
     568        6776 :   struct getheap_t *T = (struct getheap_t*)D;
     569        6776 :   T->n++;
     570        6776 :   T->l += bl_size(x) + BL_HEAD;
     571        6776 : }
     572             : GEN
     573          84 : getheap(void)
     574             : {
     575          84 :   struct getheap_t T = { 0, 0 };
     576          84 :   traverseheap(&f_getheap, &T); return mkvec2s(T.n, T.l);
     577             : }
     578             : 
     579             : static void
     580       13636 : traverseheap_r(GEN bl, void(*f)(GEN, void *), void *data)
     581             : {
     582       13636 :   if (!bl) return;
     583        6776 :   traverseheap_r(bl_left(bl), f, data);
     584        6776 :   traverseheap_r(bl_right(bl), f, data);
     585        6776 :   f(bl, data);
     586             : }
     587             : 
     588             : void
     589          84 : traverseheap( void(*f)(GEN, void *), void *data)
     590             : {
     591          84 :   traverseheap_r(root_block,f, data);
     592          84 : }
     593             : 
     594             : /*********************************************************************/
     595             : /*                          DAEMON / FORK                            */
     596             : /*********************************************************************/
     597             : #if defined(HAS_WAITPID) && defined(HAS_SETSID)
     598             : /* Properly fork a process, detaching from main process group without creating
     599             :  * zombies on exit. Parent returns 1, son returns 0 */
     600             : int
     601          60 : pari_daemon(void)
     602             : {
     603          60 :   pid_t pid = fork();
     604         120 :   switch(pid) {
     605           0 :       case -1: return 1; /* father, fork failed */
     606          60 :       case 0:
     607          60 :         (void)setsid(); /* son becomes process group leader */
     608          60 :         if (fork()) _exit(0); /* now son exits, also when fork fails */
     609           0 :         break; /* grandson: its father is the son, which exited,
     610             :                 * hence father becomes 'init', that'll take care of it */
     611          60 :       default: /* father, fork succeeded */
     612          60 :         (void)waitpid(pid,NULL,0); /* wait for son to exit, immediate */
     613          60 :         return 1;
     614             :   }
     615             :   /* grandson. The silly '!' avoids a gcc-8 warning (unused value) */
     616           0 :   (void)!freopen("/dev/null","r",stdin);
     617           0 :   return 0;
     618             : }
     619             : #else
     620             : int
     621             : pari_daemon(void)
     622             : {
     623             :   pari_err_IMPL("pari_daemon without waitpid & setsid");
     624             :   return 0;
     625             : }
     626             : #endif
     627             : 
     628             : /*********************************************************************/
     629             : /*                                                                   */
     630             : /*                       SYSTEM INITIALIZATION                       */
     631             : /*                                                                   */
     632             : /*********************************************************************/
     633             : static int try_to_recover = 0;
     634             : THREAD VOLATILE int PARI_SIGINT_block = 0, PARI_SIGINT_pending = 0;
     635             : 
     636             : /*********************************************************************/
     637             : /*                         SIGNAL HANDLERS                           */
     638             : /*********************************************************************/
     639             : static void
     640           0 : dflt_sigint_fun(void) { pari_err(e_MISC, "user interrupt"); }
     641             : 
     642             : #if defined(_WIN32) || defined(__CYGWIN32__)
     643             : int win32ctrlc = 0, win32alrm = 0;
     644             : void
     645             : dowin32ctrlc(void)
     646             : {
     647             :   win32ctrlc = 0;
     648             :   cb_pari_sigint();
     649             : }
     650             : #endif
     651             : 
     652             : static void
     653           0 : pari_handle_SIGINT(void)
     654             : {
     655             : #ifdef _WIN32
     656             :   if (++win32ctrlc >= 5) _exit(3);
     657             : #else
     658           0 :   cb_pari_sigint();
     659             : #endif
     660           0 : }
     661             : 
     662             : typedef void (*pari_sighandler_t)(int);
     663             : 
     664             : pari_sighandler_t
     665       18629 : os_signal(int sig, pari_sighandler_t f)
     666             : {
     667             : #ifdef HAS_SIGACTION
     668             :   struct sigaction sa, oldsa;
     669             : 
     670       18629 :   sa.sa_handler = f;
     671       18629 :   sigemptyset(&sa.sa_mask);
     672       18629 :   sa.sa_flags = SA_NODEFER;
     673             : 
     674       18629 :   if (sigaction(sig, &sa, &oldsa)) return NULL;
     675       18629 :   return oldsa.sa_handler;
     676             : #else
     677             :   return signal(sig,f);
     678             : #endif
     679             : }
     680             : 
     681             : void
     682           0 : pari_sighandler(int sig)
     683             : {
     684             :   const char *msg;
     685             : #ifndef HAS_SIGACTION
     686             :   /*SYSV reset the signal handler in the handler*/
     687             :   (void)os_signal(sig,pari_sighandler);
     688             : #endif
     689           0 :   switch(sig)
     690             :   {
     691             : #ifdef SIGBREAK
     692             :     case SIGBREAK:
     693             :       if (PARI_SIGINT_block==1)
     694             :       {
     695             :         PARI_SIGINT_pending=SIGBREAK;
     696             :         mt_sigint();
     697             :       }
     698             :       else pari_handle_SIGINT();
     699             :       return;
     700             : #endif
     701             : 
     702             : #ifdef SIGINT
     703           0 :     case SIGINT:
     704           0 :       if (PARI_SIGINT_block==1)
     705             :       {
     706           0 :         PARI_SIGINT_pending=SIGINT;
     707           0 :         mt_sigint();
     708             :       }
     709           0 :       else pari_handle_SIGINT();
     710           0 :       return;
     711             : #endif
     712             : 
     713             : #ifdef SIGSEGV
     714           0 :     case SIGSEGV:
     715           0 :       msg="PARI/GP (Segmentation Fault)"; break;
     716             : #endif
     717             : #ifdef SIGBUS
     718           0 :     case SIGBUS:
     719           0 :       msg="PARI/GP (Bus Error)"; break;
     720             : #endif
     721             : #ifdef SIGFPE
     722           0 :     case SIGFPE:
     723           0 :       msg="PARI/GP (Floating Point Exception)"; break;
     724             : #endif
     725             : 
     726             : #ifdef SIGPIPE
     727           0 :     case SIGPIPE:
     728             :     {
     729           0 :       pariFILE *f = GP_DATA->pp->file;
     730           0 :       if (f && pari_outfile == f->file)
     731             :       {
     732           0 :         GP_DATA->pp->file = NULL; /* to avoid oo recursion on error */
     733           0 :         pari_outfile = stdout; pari_fclose(f);
     734           0 :         pari_err(e_MISC, "Broken Pipe, resetting file stack...");
     735             :       }
     736             :       return; /* LCOV_EXCL_LINE */
     737             :     }
     738             : #endif
     739             : 
     740           0 :     default: msg="signal handling"; break;
     741             :   }
     742           0 :   pari_err_BUG(msg);
     743             : }
     744             : 
     745             : void
     746        3388 : pari_sig_init(void (*f)(int))
     747             : {
     748             : #ifdef SIGBUS
     749        3388 :   (void)os_signal(SIGBUS,f);
     750             : #endif
     751             : #ifdef SIGFPE
     752        3388 :   (void)os_signal(SIGFPE,f);
     753             : #endif
     754             : #ifdef SIGINT
     755        3388 :   (void)os_signal(SIGINT,f);
     756             : #endif
     757             : #ifdef SIGBREAK
     758             :   (void)os_signal(SIGBREAK,f);
     759             : #endif
     760             : #ifdef SIGPIPE
     761        3388 :   (void)os_signal(SIGPIPE,f);
     762             : #endif
     763             : #ifdef SIGSEGV
     764        3388 :   (void)os_signal(SIGSEGV,f);
     765             : #endif
     766        3388 : }
     767             : 
     768             : /*********************************************************************/
     769             : /*                      STACK AND UNIVERSAL CONSTANTS                */
     770             : /*********************************************************************/
     771             : static void
     772        1699 : init_universal_constants(void)
     773             : {
     774        1699 :   gen_0  = (GEN)readonly_constants;
     775        1699 :   gnil   = (GEN)readonly_constants+2;
     776        1699 :   gen_1  = (GEN)readonly_constants+4;
     777        1699 :   gen_2  = (GEN)readonly_constants+7;
     778        1699 :   gen_m1 = (GEN)readonly_constants+10;
     779        1699 :   gen_m2 = (GEN)readonly_constants+13;
     780        1699 :   err_e_STACK = (GEN)readonly_constants+16;
     781        1699 :   ghalf  = (GEN)readonly_constants+18;
     782        1699 : }
     783             : 
     784             : static void
     785      210032 : pari_init_errcatch(void)
     786             : {
     787      210032 :   iferr_env = NULL;
     788      210032 :   global_err_data = NULL;
     789      210032 : }
     790             : 
     791             : void
     792        1727 : setalldebug(long n)
     793             : {
     794        1727 :   long i, l = numberof(pari_DEBUGLEVEL_ptr);
     795      100166 :   for (i = 0; i < l; i++) *pari_DEBUGLEVEL_ptr[i] = n;
     796        1727 : }
     797             : 
     798             : /*********************************************************************/
     799             : /*                           INIT DEFAULTS                           */
     800             : /*********************************************************************/
     801             : void
     802        1699 : pari_init_defaults(void)
     803             : {
     804             :   long i;
     805        1699 :   initout(1);
     806             : 
     807             : #ifdef LONG_IS_64BIT
     808        1460 :   precreal = 128;
     809             : #else
     810         239 :   precreal = 96;
     811             : #endif
     812             : 
     813        1699 :   precdl = 16;
     814        1699 :   DEBUGLEVEL = 0;
     815        1699 :   setalldebug(0);
     816        1699 :   DEBUGMEM = 1;
     817        1699 :   disable_color = 1;
     818        1699 :   pari_logstyle = logstyle_none;
     819             : 
     820        1699 :   current_psfile = pari_strdup("pari.ps");
     821        1699 :   current_logfile= pari_strdup("pari.log");
     822        1699 :   pari_logfile = NULL;
     823             : 
     824        1699 :   pari_datadir = os_getenv("GP_DATA_DIR");
     825        1699 :   if (!pari_datadir)
     826             :   {
     827             : #if defined(_WIN32) || defined(__CYGWIN32__)
     828             :     if (paricfg_datadir[0]=='@' && paricfg_datadir[1]==0)
     829             :       pari_datadir = win32_datadir();
     830             :     else
     831             : #endif
     832        1699 :       pari_datadir = pari_strdup(paricfg_datadir);
     833             :   }
     834           0 :   else pari_datadir= pari_strdup(pari_datadir);
     835       13592 :   for (i=0; i<c_LAST; i++) gp_colors[i] = c_NONE;
     836        1699 : }
     837             : 
     838             : /*********************************************************************/
     839             : /*                   FUNCTION HASHTABLES, MODULES                    */
     840             : /*********************************************************************/
     841             : extern entree functions_basic[], functions_default[];
     842             : static void
     843        1699 : pari_init_functions(void)
     844             : {
     845        1699 :   pari_stack_init(&s_MODULES, sizeof(*MODULES),(void**)&MODULES);
     846        1699 :   pari_stack_pushp(&s_MODULES,functions_basic);
     847        1699 :   functions_hash = (entree**) pari_calloc(sizeof(entree*)*functions_tblsz);
     848        1699 :   pari_fill_hashtable(functions_hash, functions_basic);
     849        1699 :   defaults_hash = (entree**) pari_calloc(sizeof(entree*)*functions_tblsz);
     850        1699 :   pari_add_defaults_module(functions_default);
     851        1699 : }
     852             : 
     853             : void
     854        1689 : pari_add_module(entree *ep)
     855             : {
     856        1689 :   pari_fill_hashtable(functions_hash, ep);
     857        1689 :   pari_stack_pushp(&s_MODULES, ep);
     858        1689 : }
     859             : 
     860             : void
     861        1699 : pari_add_defaults_module(entree *ep)
     862        1699 : { pari_fill_hashtable(defaults_hash, ep); }
     863             : 
     864             : /*********************************************************************/
     865             : /*                       PARI MAIN STACK                             */
     866             : /*********************************************************************/
     867             : 
     868             : #ifdef HAS_MMAP
     869             : #define PARI_STACK_ALIGN (sysconf(_SC_PAGE_SIZE))
     870             : #ifndef MAP_ANONYMOUS
     871             : #define MAP_ANONYMOUS MAP_ANON
     872             : #endif
     873             : #ifndef MAP_NORESERVE
     874             : #define MAP_NORESERVE 0
     875             : #endif
     876             : static void *
     877      210233 : pari_mainstack_malloc(size_t size)
     878             : {
     879             :   void *b;
     880             :   /* Check that the system allows reserving "size" bytes. This is just
     881             :    * a check, we immediately free the memory. */
     882      210233 :   BLOCK_SIGINT_START;
     883      210233 :   b = mmap(NULL, size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
     884      210233 :   BLOCK_SIGINT_END;
     885      210233 :   if (b == MAP_FAILED) return NULL;
     886      210233 :   BLOCK_SIGINT_START;
     887      210233 :   munmap(b, size);
     888             : 
     889             :   /* Map again, this time with MAP_NORESERVE. On some operating systems
     890             :    * like Cygwin, this is needed because remapping with PROT_NONE and
     891             :    * MAP_NORESERVE does not work as expected. */
     892      210233 :   b = mmap(NULL, size, PROT_READ|PROT_WRITE,
     893             :                        MAP_PRIVATE|MAP_ANONYMOUS|MAP_NORESERVE, -1, 0);
     894      210233 :   BLOCK_SIGINT_END;
     895      210233 :   if (b == MAP_FAILED) return NULL;
     896      210233 :   return b;
     897             : }
     898             : 
     899             : static void
     900      210223 : pari_mainstack_mfree(void *s, size_t size)
     901             : {
     902      210223 :   BLOCK_SIGINT_START;
     903      210223 :   munmap(s, size);
     904      210223 :   BLOCK_SIGINT_END;
     905      210223 : }
     906             : 
     907             : /* Completely discard the memory mapped between the addresses "from"
     908             :  * and "to" (which must be page-aligned).
     909             :  *
     910             :  * We use mmap() with PROT_NONE, which means that the underlying memory
     911             :  * is freed and that the kernel should not commit memory for it. We
     912             :  * still keep the mapping such that we can change the flags to
     913             :  * PROT_READ|PROT_WRITE later.
     914             :  *
     915             :  * NOTE: remapping with MAP_FIXED and PROT_NONE is not the same as
     916             :  * calling mprotect(..., PROT_NONE) because the latter will keep the
     917             :  * memory committed (this is in particular relevant on Linux with
     918             :  * vm.overcommit = 2). This remains true even when calling
     919             :  * madvise(..., MADV_DONTNEED). */
     920             : static void
     921      303389 : pari_mainstack_mreset(pari_sp from, pari_sp to)
     922             : {
     923      303389 :   size_t s = to - from;
     924             :   void *addr, *res;
     925      303389 :   if (!s) return;
     926             : 
     927           0 :   addr = (void*)from;
     928           0 :   BLOCK_SIGINT_START;
     929           0 :   res = mmap(addr, s, PROT_NONE,
     930             :              MAP_FIXED|MAP_PRIVATE|MAP_ANONYMOUS|MAP_NORESERVE, -1, 0);
     931           0 :   BLOCK_SIGINT_END;
     932           0 :   if (res != addr) pari_err(e_MEM);
     933             : }
     934             : 
     935             : /* Commit (make available) the virtual memory mapped between the
     936             :  * addresses "from" and "to" (which must be page-aligned).
     937             :  * Return 0 if successful, -1 if failed. */
     938             : static int
     939      303389 : pari_mainstack_mextend(pari_sp from, pari_sp to)
     940             : {
     941      303389 :   size_t s = to - from;
     942             :   int ret;
     943      303389 :   BLOCK_SIGINT_START;
     944      303389 :   ret = mprotect((void*)from, s, PROT_READ|PROT_WRITE);
     945      303389 :   BLOCK_SIGINT_END;
     946      303389 :   return ret;
     947             : }
     948             : 
     949             : /* Set actual stack size to the given size. This sets st->size and
     950             :  * st->bot. If not enough system memory is available, this can fail.
     951             :  * Return 1 if successful, 0 if failed (in that case, st->size is not
     952             :  * changed) */
     953             : static int
     954      303389 : pari_mainstack_setsize(struct pari_mainstack *st, size_t size)
     955             : {
     956      303389 :   pari_sp newbot = st->top - size;
     957             :   /* Align newbot to pagesize */
     958      303389 :   pari_sp alignbot = newbot & ~(pari_sp)(PARI_STACK_ALIGN - 1);
     959      303389 :   if (pari_mainstack_mextend(alignbot, st->top))
     960             :   {
     961             :     /* Making the memory available did not work: limit vsize to the
     962             :      * current actual stack size. */
     963           0 :     st->vsize = st->size;
     964           0 :     pari_warn(warnstack, st->vsize);
     965           0 :     return 0;
     966             :   }
     967      303389 :   pari_mainstack_mreset(st->vbot, alignbot);
     968      303389 :   st->bot = newbot;
     969      303389 :   st->size = size;
     970      303389 :   return 1;
     971             : }
     972             : 
     973             : #else
     974             : #define PARI_STACK_ALIGN (0x40UL)
     975             : static void *
     976             : pari_mainstack_malloc(size_t s)
     977             : {
     978             :   char * tmp;
     979             :   BLOCK_SIGINT_START;
     980             :   tmp = malloc(s); /* NOT pari_malloc, e_MEM would be deadly */
     981             :   BLOCK_SIGINT_END;
     982             :   return tmp;
     983             : }
     984             : 
     985             : static void
     986             : pari_mainstack_mfree(void *s, size_t size) { (void) size; pari_free(s); }
     987             : 
     988             : static int
     989             : pari_mainstack_setsize(struct pari_mainstack *st, size_t size)
     990             : {
     991             :   st->bot = st->top - size;
     992             :   st->size = size;
     993             :   return 1;
     994             : }
     995             : 
     996             : #endif
     997             : 
     998             : static const size_t MIN_STACK = 500032UL;
     999             : static size_t
    1000      420456 : fix_size(size_t a)
    1001             : {
    1002      420456 :   size_t ps = PARI_STACK_ALIGN;
    1003      420456 :   size_t b = a & ~(ps - 1); /* Align */
    1004      420456 :   if (b < a && b < ~(ps - 1)) b += ps;
    1005      420456 :   if (b < MIN_STACK) b = MIN_STACK;
    1006      420456 :   return b;
    1007             : }
    1008             : 
    1009             : static void
    1010      210233 : pari_mainstack_alloc(int numerr, struct pari_mainstack *st, size_t rsize, size_t vsize)
    1011             : {
    1012      210233 :   size_t sizemax = vsize ? vsize: rsize, s = fix_size(sizemax);
    1013             :   for (;;)
    1014             :   {
    1015      210233 :     st->vbot = (pari_sp)pari_mainstack_malloc(s);
    1016      210233 :     if (st->vbot) break;
    1017           0 :     if (s == MIN_STACK) pari_err(e_MEM); /* no way out. Die */
    1018           0 :     s = fix_size(s >> 1);
    1019           0 :     pari_warn(numerr, s);
    1020             :   }
    1021      210233 :   st->vsize = vsize ? s: 0;
    1022      210233 :   st->rsize = minuu(rsize, s);
    1023      210233 :   st->top = st->vbot+s;
    1024      210233 :   if (!pari_mainstack_setsize(st, st->rsize))
    1025             :   {
    1026             :     /* This should never happen since we only decrease the allocated space */
    1027           0 :     pari_err(e_MEM);
    1028             :   }
    1029      210233 :   st->memused = 0;
    1030      210233 : }
    1031             : 
    1032             : static void
    1033      210223 : pari_mainstack_free(struct pari_mainstack *st)
    1034             : {
    1035      210223 :   pari_mainstack_mfree((void*)st->vbot, st->vsize ? st->vsize : fix_size(st->rsize));
    1036      210223 :   st->top = st->bot = st->vbot = 0;
    1037      210223 :   st->size = st->vsize = 0;
    1038      210223 : }
    1039             : 
    1040             : static void
    1041         369 : pari_mainstack_resize(struct pari_mainstack *st, size_t rsize, size_t vsize)
    1042             : {
    1043         369 :   BLOCK_SIGINT_START;
    1044         369 :   pari_mainstack_free(st);
    1045         369 :   pari_mainstack_alloc(warnstack, st, rsize, vsize);
    1046         369 :   BLOCK_SIGINT_END;
    1047         369 : }
    1048             : 
    1049             : static void
    1050      209727 : pari_mainstack_use(struct pari_mainstack *st)
    1051             : {
    1052      209727 :   pari_mainstack = st;
    1053      209727 :   avma = st->top; /* don't use set_avma */
    1054      209727 : }
    1055             : 
    1056             : static void
    1057        1699 : paristack_alloc(size_t rsize, size_t vsize)
    1058             : {
    1059        1699 :   pari_mainstack_alloc(warnstack, pari_mainstack, rsize, vsize);
    1060        1699 :   pari_mainstack_use(pari_mainstack);
    1061        1699 : }
    1062             : 
    1063             : void
    1064           0 : paristack_setsize(size_t rsize, size_t vsize)
    1065             : {
    1066           0 :   pari_mainstack_resize(pari_mainstack, rsize, vsize);
    1067           0 :   pari_mainstack_use(pari_mainstack);
    1068           0 : }
    1069             : 
    1070             : void
    1071           0 : parivstack_resize(ulong newsize)
    1072             : {
    1073             :   size_t s;
    1074           0 :   if (newsize && newsize < pari_mainstack->rsize)
    1075           0 :     pari_err_DIM("stack sizes [parisizemax < parisize]");
    1076           0 :   if (newsize == pari_mainstack->vsize) return;
    1077           0 :   evalstate_reset();
    1078           0 :   paristack_setsize(pari_mainstack->rsize, newsize);
    1079           0 :   s = pari_mainstack->vsize ? pari_mainstack->vsize : pari_mainstack->rsize;
    1080           0 :   if (DEBUGMEM)
    1081           0 :     pari_warn(warner,"new maximum stack size = %lu (%.3f Mbytes)",
    1082             :               s, s/1048576.);
    1083           0 :   pari_init_errcatch();
    1084           0 :   cb_pari_err_recover(-1);
    1085             : }
    1086             : 
    1087             : void
    1088         375 : paristack_newrsize(ulong newsize)
    1089             : {
    1090         375 :   size_t s, vsize = pari_mainstack->vsize;
    1091         375 :   if (!newsize) newsize = pari_mainstack->rsize << 1;
    1092         375 :   if (newsize != pari_mainstack->rsize)
    1093         369 :     pari_mainstack_resize(pari_mainstack, newsize, vsize);
    1094         375 :   evalstate_reset();
    1095         375 :   s = pari_mainstack->rsize;
    1096         375 :   if (DEBUGMEM)
    1097         375 :     pari_warn(warner,"new stack size = %lu (%.3f Mbytes)", s, s/1048576.);
    1098         375 :   pari_init_errcatch();
    1099         375 :   cb_pari_err_recover(-1);
    1100           0 : }
    1101             : 
    1102             : void
    1103           0 : paristack_resize(ulong newsize)
    1104             : {
    1105           0 :   long size = pari_mainstack->size;
    1106           0 :   if (!newsize)
    1107           0 :     newsize = 2 * size;
    1108           0 :   newsize = minuu(newsize, pari_mainstack->vsize);
    1109           0 :   if (newsize <= pari_mainstack->size) return;
    1110           0 :   if (pari_mainstack_setsize(pari_mainstack, newsize))
    1111             :   {
    1112           0 :     if (DEBUGMEM)
    1113           0 :       pari_warn(warner, "increasing stack size to %lu", pari_mainstack->size);
    1114             :   }
    1115             :   else
    1116             :   {
    1117           0 :     pari_mainstack_setsize(pari_mainstack, size);
    1118           0 :     pari_err(e_STACK);
    1119             :   }
    1120             : }
    1121             : 
    1122             : void
    1123       93156 : parivstack_reset(void)
    1124             : {
    1125       93156 :   pari_mainstack_setsize(pari_mainstack, pari_mainstack->rsize);
    1126       93156 :   if (avma < pari_mainstack->bot)
    1127           0 :     pari_err_BUG("parivstack_reset [avma < bot]");
    1128       93156 : }
    1129             : 
    1130             : /* Enlarge the stack if needed such that the unused portion of the stack
    1131             :  * (between bot and avma) is large enough to contain x longs. */
    1132             : void
    1133           7 : new_chunk_resize(size_t x)
    1134             : {
    1135           7 :   if (pari_mainstack->vsize==0
    1136           7 :     || x > (avma-pari_mainstack->vbot) / sizeof(long)) pari_err(e_STACK);
    1137           0 :   while (x > (avma-pari_mainstack->bot) / sizeof(long))
    1138           0 :     paristack_resize(0);
    1139           0 : }
    1140             : 
    1141             : /*********************************************************************/
    1142             : /*                       PARI THREAD                                 */
    1143             : /*********************************************************************/
    1144             : 
    1145             : /* Initial PARI thread structure t with a stack of size s and
    1146             :  * argument arg */
    1147             : 
    1148             : static void
    1149      206259 : pari_thread_set_global(struct pari_global_state *gs)
    1150             : {
    1151      206259 :   push_localbitprec(gs->bitprec);
    1152      206557 :   pari_set_primetab(gs->primetab);
    1153      206486 :   pari_set_seadata(gs->seadata);
    1154      206440 :   pari_set_varstate(gs->varpriority, &gs->varstate);
    1155      206959 : }
    1156             : 
    1157             : static void
    1158      208165 : pari_thread_get_global(struct pari_global_state *gs)
    1159             : {
    1160      208165 :   gs->bitprec = get_localbitprec();
    1161      208165 :   gs->primetab = primetab;
    1162      208165 :   gs->seadata = pari_get_seadata();
    1163      208165 :   varstate_save(&gs->varstate);
    1164      208165 :   gs->varpriority = varpriority;
    1165      208165 : }
    1166             : 
    1167             : void
    1168      208165 : pari_thread_alloc(struct pari_thread *t, size_t s, GEN arg)
    1169             : {
    1170      208165 :   pari_mainstack_alloc(warnstackthread, &t->st,s,0);
    1171      208165 :   pari_thread_get_global(&t->gs);
    1172      208165 :   t->data = arg;
    1173      208165 : }
    1174             : 
    1175             : /* Initial PARI thread structure t with a stack of size s and virtual size v
    1176             :  * and argument arg */
    1177             : 
    1178             : void
    1179           0 : pari_thread_valloc(struct pari_thread *t, size_t s, size_t v, GEN arg)
    1180             : {
    1181           0 :   pari_mainstack_alloc(warnstackthread, &t->st,s,v);
    1182           0 :   pari_thread_get_global(&t->gs);
    1183           0 :   t->data = arg;
    1184           0 : }
    1185             : 
    1186             : void
    1187      208165 : pari_thread_free(struct pari_thread *t)
    1188             : {
    1189      208165 :   pari_mainstack_free(&t->st);
    1190      208165 : }
    1191             : 
    1192             : void
    1193      209704 : pari_thread_init(void)
    1194             : {
    1195             :   long var;
    1196      209704 :   pari_stackcheck_init((void*)&var);
    1197      209715 :   pari_init_blocks();
    1198      209673 :   pari_init_errcatch();
    1199      209644 :   pari_init_rand();
    1200      206677 :   pari_init_floats();
    1201      207136 :   pari_init_parser();
    1202      207374 :   pari_init_compiler();
    1203      207620 :   pari_init_evaluator();
    1204      207004 :   pari_init_files();
    1205      207326 :   pari_init_ellcondfile();
    1206      208150 : }
    1207             : 
    1208             : void
    1209      208808 : pari_thread_close(void)
    1210             : {
    1211      208808 :   pari_thread_close_files();
    1212      207316 :   pari_close_evaluator();
    1213      208807 :   pari_close_compiler();
    1214      205992 :   pari_close_parser();
    1215      208874 :   pari_close_floats();
    1216      206587 :   pari_close_blocks();
    1217      208549 : }
    1218             : 
    1219             : GEN
    1220      208064 : pari_thread_start(struct pari_thread *t)
    1221             : {
    1222      208064 :   pari_mainstack_use(&t->st);
    1223      208022 :   pari_thread_init();
    1224      206362 :   pari_thread_set_global(&t->gs);
    1225      207141 :   return t->data;
    1226             : }
    1227             : 
    1228             : /*********************************************************************/
    1229             : /*                       LIBPARI INIT / CLOSE                        */
    1230             : /*********************************************************************/
    1231             : 
    1232             : static void
    1233           0 : pari_exit(void)
    1234             : {
    1235           0 :   err_printf("  ***   Error in the PARI system. End of program.\n");
    1236           0 :   exit(1);
    1237             : }
    1238             : 
    1239             : static void
    1240           0 : dflt_err_recover(long errnum) { (void) errnum; pari_exit(); }
    1241             : 
    1242             : static void
    1243           0 : dflt_pari_quit(long err) { (void)err; /*do nothing*/; }
    1244             : 
    1245             : static int pari_err_display(GEN err);
    1246             : 
    1247             : /* initialize PARI data. Initialize [new|old]fun to NULL for default set. */
    1248             : void
    1249        1699 : pari_init_opts(size_t parisize, ulong maxprime, ulong init_opts)
    1250             : {
    1251             :   ulong u;
    1252             : 
    1253        1699 :   pari_mt_nbthreads = 0;
    1254        1699 :   cb_pari_quit = dflt_pari_quit;
    1255        1699 :   cb_pari_init_histfile = NULL;
    1256        1699 :   cb_pari_get_line_interactive = NULL;
    1257        1699 :   cb_pari_fgets_interactive = NULL;
    1258        1699 :   cb_pari_whatnow = NULL;
    1259        1699 :   cb_pari_handle_exception = NULL;
    1260        1699 :   cb_pari_err_handle = pari_err_display;
    1261        1699 :   cb_pari_pre_recover = NULL;
    1262        1699 :   cb_pari_break_loop = NULL;
    1263        1699 :   cb_pari_is_interactive = NULL;
    1264        1699 :   cb_pari_start_output = NULL;
    1265        1699 :   cb_pari_sigint = dflt_sigint_fun;
    1266        1699 :   if (init_opts&INIT_JMPm) cb_pari_err_recover = dflt_err_recover;
    1267             : 
    1268        1699 :   pari_stackcheck_init(&u);
    1269        1699 :   pari_init_homedir();
    1270        1699 :   if (init_opts&INIT_DFTm) {
    1271           0 :     pari_init_defaults();
    1272           0 :     GP_DATA = default_gp_data();
    1273           0 :     pari_init_paths();
    1274             :   }
    1275             : 
    1276        1699 :   pari_mainstack = (struct pari_mainstack *) malloc(sizeof(*pari_mainstack));
    1277        1699 :   paristack_alloc(parisize, 0);
    1278        1699 :   init_universal_constants();
    1279        1699 :   diffptr = NULL;
    1280        1699 :   if (!(init_opts&INIT_noPRIMEm))
    1281             :   {
    1282           0 :     GP_DATA->primelimit = maxprime;
    1283           0 :     pari_init_primes(GP_DATA->primelimit);
    1284             :   }
    1285        1699 :   if (!(init_opts&INIT_noINTGMPm)) pari_kernel_init();
    1286        1699 :   pari_init_graphics();
    1287        1699 :   pari_thread_init();
    1288        1699 :   pari_set_primetab(NULL);
    1289        1699 :   pari_set_seadata(NULL);
    1290        1699 :   pari_init_functions();
    1291        1699 :   pari_init_export();
    1292        1699 :   pari_var_init();
    1293        1699 :   pari_init_timer();
    1294        1699 :   pari_init_buffers();
    1295        1699 :   (void)getabstime();
    1296        1699 :   try_to_recover = 1;
    1297        1699 :   if (!(init_opts&INIT_noIMTm)) pari_mt_init();
    1298        1699 :   if ((init_opts&INIT_SIGm)) pari_sig_init(pari_sighandler);
    1299        1699 : }
    1300             : 
    1301             : void
    1302           0 : pari_init(size_t parisize, ulong maxprime)
    1303           0 : { pari_init_opts(parisize, maxprime, INIT_JMPm | INIT_SIGm | INIT_DFTm); }
    1304             : 
    1305             : void
    1306        1689 : pari_close_opts(ulong init_opts)
    1307             : {
    1308             :   long i;
    1309             : 
    1310        1689 :   BLOCK_SIGINT_START;
    1311        1689 :   if ((init_opts&INIT_SIGm)) pari_sig_init(SIG_DFL);
    1312        1689 :   if (!(init_opts&INIT_noIMTm)) pari_mt_close();
    1313             : 
    1314        1689 :   pari_var_close(); /* must come before destruction of functions_hash */
    1315      229704 :   for (i = 0; i < functions_tblsz; i++)
    1316             :   {
    1317      228015 :     entree *ep = functions_hash[i];
    1318     2423555 :     while (ep) {
    1319     2195540 :       entree *EP = ep->next;
    1320     2195540 :       if (!EpSTATIC(ep)) { freeep(ep); free(ep); }
    1321     2195540 :       ep = EP;
    1322             :     }
    1323             :   }
    1324        1689 :   pari_close_mf();
    1325        1689 :   pari_thread_close();
    1326        1689 :   pari_close_export();
    1327        1689 :   pari_close_files();
    1328        1689 :   pari_close_homedir();
    1329        1689 :   if (!(init_opts&INIT_noINTGMPm)) pari_kernel_close();
    1330             : 
    1331        1689 :   free((void*)functions_hash);
    1332        1689 :   free((void*)defaults_hash);
    1333        1689 :   if (diffptr) pari_close_primes();
    1334        1689 :   free(current_logfile);
    1335        1689 :   free(current_psfile);
    1336        1689 :   pari_mainstack_free(pari_mainstack);
    1337        1689 :   free((void*)pari_mainstack);
    1338        1689 :   pari_stack_delete(&s_MODULES);
    1339        1689 :   if (pari_datadir) free(pari_datadir);
    1340        1689 :   if (init_opts&INIT_DFTm)
    1341             :   { /* delete GP_DATA */
    1342        1689 :     pari_close_paths();
    1343        1689 :     if (GP_DATA->hist->v) free((void*)GP_DATA->hist->v);
    1344        1689 :     if (GP_DATA->pp->cmd) free((void*)GP_DATA->pp->cmd);
    1345        1689 :     if (GP_DATA->help) free((void*)GP_DATA->help);
    1346        1689 :     if (GP_DATA->plothsizes) free((void*)GP_DATA->plothsizes);
    1347        1689 :     if (GP_DATA->colormap) pari_free(GP_DATA->colormap);
    1348        1689 :     if (GP_DATA->graphcolors) pari_free(GP_DATA->graphcolors);
    1349        1689 :     free((void*)GP_DATA->prompt);
    1350        1689 :     free((void*)GP_DATA->prompt_cont);
    1351        1689 :     free((void*)GP_DATA->histfile);
    1352             :   }
    1353        1689 :   BLOCK_SIGINT_END;
    1354        1689 : }
    1355             : 
    1356             : void
    1357        1689 : pari_close(void)
    1358        1689 : { pari_close_opts(INIT_JMPm | INIT_SIGm | INIT_DFTm); }
    1359             : 
    1360             : /*******************************************************************/
    1361             : /*                                                                 */
    1362             : /*                         ERROR RECOVERY                          */
    1363             : /*                                                                 */
    1364             : /*******************************************************************/
    1365             : void
    1366      113153 : gp_context_save(struct gp_context* rec)
    1367             : {
    1368      113153 :   rec->prettyp = GP_DATA->fmt->prettyp;
    1369      113153 :   rec->listloc = next_block;
    1370      113153 :   rec->iferr_env = iferr_env;
    1371      113153 :   rec->err_data  = global_err_data;
    1372      113153 :   varstate_save(&rec->var);
    1373      113153 :   evalstate_save(&rec->eval);
    1374      113153 :   parsestate_save(&rec->parse);
    1375      113153 :   filestate_save(&rec->file);
    1376      113153 : }
    1377             : 
    1378             : void
    1379       10237 : gp_context_restore(struct gp_context* rec)
    1380             : {
    1381             :   long i;
    1382             : 
    1383       10237 :   if (!try_to_recover) return;
    1384             :   /* disable gp_context_restore() and SIGINT */
    1385       10237 :   try_to_recover = 0;
    1386       10237 :   BLOCK_SIGINT_START
    1387       10237 :   if (DEBUGMEM>2) err_printf("entering recover(), loc = %ld\n", rec->listloc);
    1388       10237 :   evalstate_restore(&rec->eval);
    1389       10237 :   parsestate_restore(&rec->parse);
    1390       10237 :   filestate_restore(&rec->file);
    1391       10237 :   global_err_data = rec->err_data;
    1392       10237 :   iferr_env = rec->iferr_env;
    1393       10237 :   GP_DATA->fmt->prettyp = rec->prettyp;
    1394             : 
    1395     1392232 :   for (i = 0; i < functions_tblsz; i++)
    1396             :   {
    1397     1381995 :     entree *ep = functions_hash[i];
    1398    15361028 :     while (ep)
    1399             :     {
    1400    13979033 :       entree *EP = ep->next;
    1401    13979033 :       switch(EpVALENCE(ep))
    1402             :       {
    1403      224786 :         case EpVAR:
    1404      225157 :           while (pop_val_if_newer(ep,rec->listloc)) /* empty */;
    1405      224786 :           break;
    1406      630413 :         case EpNEW: break;
    1407             :       }
    1408    13979033 :       ep = EP;
    1409             :     }
    1410             :   }
    1411       10237 :   varstate_restore(&rec->var);
    1412       10237 :   if (DEBUGMEM>2) err_printf("leaving recover()\n");
    1413       10237 :   BLOCK_SIGINT_END
    1414       10237 :   try_to_recover = 1;
    1415             : }
    1416             : 
    1417             : static void
    1418       10162 : err_recover(long numerr)
    1419             : {
    1420       10162 :   if (cb_pari_pre_recover)
    1421       10162 :     cb_pari_pre_recover(numerr);
    1422           0 :   evalstate_reset();
    1423           0 :   killallfiles();
    1424           0 :   pari_init_errcatch();
    1425           0 :   cb_pari_err_recover(numerr);
    1426           0 : }
    1427             : 
    1428             : static void
    1429       10831 : err_init(void)
    1430             : {
    1431             :   /* make sure pari_err msg starts at the beginning of line */
    1432       10831 :   if (!pari_last_was_newline()) pari_putc('\n');
    1433       10831 :   pariOut->flush();
    1434       10831 :   pariErr->flush();
    1435       10831 :   out_term_color(pariErr, c_ERR);
    1436       10831 : }
    1437             : 
    1438             : static void
    1439       10738 : err_init_msg(int user)
    1440             : {
    1441             :   const char *gp_function_name;
    1442       10738 :   out_puts(pariErr, "  *** ");
    1443       10738 :   if (!user && (gp_function_name = closure_func_err()))
    1444        7158 :     out_printf(pariErr, "%s: ", gp_function_name);
    1445             :   else
    1446        3580 :     out_puts(pariErr, "  ");
    1447       10738 : }
    1448             : 
    1449             : void
    1450         648 : pari_warn(int numerr, ...)
    1451             : {
    1452             :   char *ch1;
    1453             :   va_list ap;
    1454             : 
    1455         648 :   va_start(ap,numerr);
    1456             : 
    1457         648 :   err_init();
    1458         648 :   err_init_msg(numerr==warnuser || numerr==warnstack);
    1459         648 :   switch (numerr)
    1460             :   {
    1461           7 :     case warnuser:
    1462           7 :       out_puts(pariErr, "user warning: ");
    1463           7 :       out_print0(pariErr, NULL, va_arg(ap, GEN), f_RAW);
    1464           7 :       break;
    1465             : 
    1466           0 :     case warnmem:
    1467           0 :       out_puts(pariErr, "collecting garbage in "); ch1=va_arg(ap, char*);
    1468           0 :       out_vprintf(pariErr, ch1,ap); out_putc(pariErr, '.');
    1469           0 :       break;
    1470             : 
    1471         641 :     case warner:
    1472         641 :       out_puts(pariErr, "Warning: "); ch1=va_arg(ap, char*);
    1473         641 :       out_vprintf(pariErr, ch1,ap); out_putc(pariErr, '.');
    1474         641 :       break;
    1475             : 
    1476           0 :     case warnprec:
    1477           0 :       out_vprintf(pariErr, "Warning: increasing prec in %s; new prec = %ld",
    1478             :                       ap);
    1479           0 :       break;
    1480             : 
    1481           0 :     case warnfile:
    1482           0 :       out_puts(pariErr, "Warning: failed to "),
    1483           0 :       ch1 = va_arg(ap, char*);
    1484           0 :       out_printf(pariErr, "%s: %s", ch1, va_arg(ap, char*));
    1485           0 :       break;
    1486             : 
    1487           0 :     case warnstack:
    1488             :     case warnstackthread:
    1489             :     {
    1490           0 :       ulong  s = va_arg(ap, ulong);
    1491             :       char buf[128];
    1492           0 :       const char * stk = numerr == warnstackthread
    1493           0 :                          || mt_is_thread() ? "thread": "PARI";
    1494           0 :       sprintf(buf,"Warning: not enough memory, new %s stack %lu", stk, s);
    1495           0 :       out_puts(pariErr,buf);
    1496           0 :       break;
    1497             :     }
    1498             :   }
    1499         648 :   va_end(ap);
    1500         648 :   out_term_color(pariErr, c_NONE);
    1501         648 :   out_putc(pariErr, '\n');
    1502         648 :   pariErr->flush();
    1503         648 : }
    1504             : void
    1505           0 : pari_sigint(const char *time_s)
    1506             : {
    1507           0 :   int recover=0;
    1508           0 :   BLOCK_SIGALRM_START
    1509           0 :   err_init();
    1510           0 :   closure_err(0);
    1511           0 :   err_init_msg(0);
    1512           0 :   out_puts(pariErr, "user interrupt after ");
    1513           0 :   out_puts(pariErr, time_s);
    1514           0 :   out_term_color(pariErr, c_NONE);
    1515           0 :   pariErr->flush();
    1516           0 :   if (cb_pari_handle_exception)
    1517           0 :     recover = cb_pari_handle_exception(-1);
    1518           0 :   if (!recover && !block)
    1519           0 :     PARI_SIGINT_pending = 0;
    1520           0 :   BLOCK_SIGINT_END
    1521           0 :   if (!recover) err_recover(e_MISC);
    1522           0 : }
    1523             : 
    1524             : #define retmkerr2(x,y)\
    1525             :   do { GEN _v = cgetg(3, t_ERROR);\
    1526             :        _v[1] = (x);\
    1527             :        gel(_v,2) = (y); return _v; } while(0)
    1528             : #define retmkerr3(x,y,z)\
    1529             :   do { GEN _v = cgetg(4, t_ERROR);\
    1530             :        _v[1] = (x);\
    1531             :        gel(_v,2) = (y);\
    1532             :        gel(_v,3) = (z); return _v; } while(0)
    1533             : #define retmkerr4(x,y,z,t)\
    1534             :   do { GEN _v = cgetg(5, t_ERROR);\
    1535             :        _v[1] = (x);\
    1536             :        gel(_v,2) = (y);\
    1537             :        gel(_v,3) = (z);\
    1538             :        gel(_v,4) = (t); return _v; } while(0)
    1539             : #define retmkerr5(x,y,z,t,u)\
    1540             :   do { GEN _v = cgetg(6, t_ERROR);\
    1541             :        _v[1] = (x);\
    1542             :        gel(_v,2) = (y);\
    1543             :        gel(_v,3) = (z);\
    1544             :        gel(_v,4) = (t);\
    1545             :        gel(_v,5) = (u); return _v; } while(0)
    1546             : #define retmkerr6(x,y,z,t,u,v)\
    1547             :   do { GEN _v = cgetg(7, t_ERROR);\
    1548             :        _v[1] = (x);\
    1549             :        gel(_v,2) = (y);\
    1550             :        gel(_v,3) = (z);\
    1551             :        gel(_v,4) = (t);\
    1552             :        gel(_v,5) = (u);\
    1553             :        gel(_v,6) = (v); return _v; } while(0)
    1554             : 
    1555             : static GEN
    1556       45383 : pari_err2GEN(long numerr, va_list ap)
    1557             : {
    1558       45383 :   switch ((enum err_list) numerr)
    1559             :   {
    1560          93 :   case e_SYNTAX:
    1561             :     {
    1562          93 :       const char *msg = va_arg(ap, char*);
    1563          93 :       const char *s = va_arg(ap,char *);
    1564          93 :       const char *entry = va_arg(ap,char *);
    1565          93 :       retmkerr3(numerr,strtoGENstr(msg), mkvecsmall2((long)s,(long)entry));
    1566             :     }
    1567         251 :   case e_MISC: case e_ALARM:
    1568             :     {
    1569         251 :       const char *ch1 = va_arg(ap, char*);
    1570         251 :       retmkerr2(numerr, gvsprintf(ch1,ap));
    1571             :     }
    1572        2723 :   case e_NOTFUNC:
    1573             :   case e_USER:
    1574        2723 :     retmkerr2(numerr,va_arg(ap, GEN));
    1575           0 :   case e_FILE:
    1576             :     {
    1577           0 :       const char *f = va_arg(ap, const char*);
    1578           0 :       retmkerr3(numerr, strtoGENstr(f), strtoGENstr(va_arg(ap, char*)));
    1579             :     }
    1580           0 :   case e_FILEDESC:
    1581             :     {
    1582           0 :       const char *f = va_arg(ap, const char*);
    1583           0 :       retmkerr3(numerr, strtoGENstr(f), stoi(va_arg(ap, long)));
    1584             :     }
    1585        1477 :   case e_OVERFLOW:
    1586             :   case e_IMPL:
    1587             :   case e_DIM:
    1588             :   case e_CONSTPOL:
    1589             :   case e_ROOTS0:
    1590             :   case e_FLAG:
    1591             :   case e_PREC:
    1592             :   case e_BUG:
    1593             :   case e_ARCH:
    1594             :   case e_PACKAGE:
    1595        1477 :     retmkerr2(numerr, strtoGENstr(va_arg(ap, char*)));
    1596        1029 :   case e_MODULUS:
    1597             :   case e_VAR:
    1598             :     {
    1599        1029 :       const char *f = va_arg(ap, const char*);
    1600        1029 :       GEN x = va_arg(ap, GEN);
    1601        1029 :       GEN y = va_arg(ap, GEN);
    1602        1029 :       retmkerr4(numerr, strtoGENstr(f), x,y);
    1603             :     }
    1604       33276 :   case e_INV:
    1605             :   case e_IRREDPOL:
    1606             :   case e_PRIME:
    1607             :   case e_SQRTN:
    1608             :   case e_TYPE:
    1609             :     {
    1610       33276 :       const char *f = va_arg(ap, const char*);
    1611       33276 :       GEN x = va_arg(ap, GEN);
    1612       33276 :       retmkerr3(numerr, strtoGENstr(f), x);
    1613             :     }
    1614        3836 :   case e_COPRIME: case e_OP: case e_TYPE2:
    1615             :     {
    1616        3836 :       const char *f = va_arg(ap, const char*);
    1617        3836 :       GEN x = va_arg(ap, GEN);
    1618        3836 :       GEN y = va_arg(ap, GEN);
    1619        3836 :       retmkerr4(numerr,strtoGENstr(f),x,y);
    1620             :     }
    1621         200 :   case e_COMPONENT:
    1622             :     {
    1623         200 :       const char *f= va_arg(ap, const char *);
    1624         200 :       const char *op = va_arg(ap, const char *);
    1625         200 :       GEN l = va_arg(ap, GEN);
    1626         200 :       GEN x = va_arg(ap, GEN);
    1627         200 :       retmkerr5(numerr,strtoGENstr(f),strtoGENstr(op),l,x);
    1628             :     }
    1629        2260 :   case e_DOMAIN:
    1630             :     {
    1631        2260 :       const char *f = va_arg(ap, const char*);
    1632        2260 :       const char *v = va_arg(ap, const char *);
    1633        2260 :       const char *op = va_arg(ap, const char *);
    1634        2260 :       GEN l = va_arg(ap, GEN);
    1635        2260 :       GEN x = va_arg(ap, GEN);
    1636        2260 :       retmkerr6(numerr,strtoGENstr(f),strtoGENstr(v),strtoGENstr(op),l,x);
    1637             :     }
    1638         231 :   case e_PRIORITY:
    1639             :     {
    1640         231 :       const char *f = va_arg(ap, const char*);
    1641         231 :       GEN x = va_arg(ap, GEN);
    1642         231 :       const char *op = va_arg(ap, const char *);
    1643         231 :       long v = va_arg(ap, long);
    1644         231 :       retmkerr5(numerr,strtoGENstr(f),x,strtoGENstr(op),stoi(v));
    1645             :     }
    1646           0 :   case e_MAXPRIME:
    1647           0 :     retmkerr2(numerr, utoi(va_arg(ap, ulong)));
    1648           7 :   case e_STACK:
    1649           7 :     return err_e_STACK;
    1650           0 :   case e_STACKTHREAD:
    1651           0 :     retmkerr3(numerr, utoi(va_arg(ap, ulong)), utoi(va_arg(ap, ulong)));
    1652           0 :   default:
    1653           0 :     return mkerr(numerr);
    1654             :   }
    1655             : }
    1656             : 
    1657             : static char *
    1658        7056 : type_dim(GEN x)
    1659             : {
    1660        7056 :   char *v = stack_malloc(64);
    1661        7056 :   switch(typ(x))
    1662             :   {
    1663          84 :     case t_MAT:
    1664             :     {
    1665          84 :       long l = lg(x), r = (l == 1)? 1: lgcols(x);
    1666          84 :       sprintf(v, "t_MAT (%ldx%ld)", r-1,l-1);
    1667          84 :       break;
    1668             :     }
    1669         105 :     case t_COL:
    1670         105 :       sprintf(v, "t_COL (%ld elts)", lg(x)-1);
    1671         105 :       break;
    1672         133 :     case t_VEC:
    1673         133 :       sprintf(v, "t_VEC (%ld elts)", lg(x)-1);
    1674         133 :       break;
    1675        6734 :     default:
    1676        6734 :       v = (char*)type_name(typ(x));
    1677             :   }
    1678        7056 :   return v;
    1679             : }
    1680             : 
    1681             : static char *
    1682        2464 : gdisplay(GEN x)
    1683             : {
    1684        2464 :   char *s = GENtostr_raw(x);
    1685        2464 :   if (strlen(s) < 1600) return s;
    1686          21 :   if (! GP_DATA->breakloop) return (char*)"(...)";
    1687           0 :   return stack_sprintf("\n  ***  (...) Huge %s omitted; you can access it via dbg_err()", type_name(typ(x)));
    1688             : }
    1689             : 
    1690             : char *
    1691       17825 : pari_err2str(GEN e)
    1692             : {
    1693       17825 :   long numerr = err_get_num(e);
    1694       17825 :   switch ((enum err_list) numerr)
    1695             :   {
    1696           0 :   case e_ALARM:
    1697           0 :     return pari_sprintf("alarm interrupt after %Ps.",gel(e,2));
    1698         245 :   case e_MISC:
    1699         245 :     return pari_sprintf("%Ps.",gel(e,2));
    1700             : 
    1701           0 :   case e_ARCH:
    1702           0 :     return pari_sprintf("sorry, '%Ps' not available on this system.",gel(e,2));
    1703          14 :   case e_BUG:
    1704          14 :     return pari_sprintf("bug in %Ps, please report.",gel(e,2));
    1705           7 :   case e_CONSTPOL:
    1706           7 :     return pari_sprintf("constant polynomial in %Ps.", gel(e,2));
    1707          70 :   case e_COPRIME:
    1708         210 :     return pari_sprintf("elements not coprime in %Ps:\n    %s\n    %s",
    1709          70 :                         gel(e,2), gdisplay(gel(e,3)), gdisplay(gel(e,4)));
    1710         529 :   case e_DIM:
    1711         529 :     return pari_sprintf("inconsistent dimensions in %Ps.", gel(e,2));
    1712           0 :   case e_FILE:
    1713           0 :     return pari_sprintf("error opening %Ps: `%Ps'.", gel(e,2), gel(e,3));
    1714           0 :   case e_FILEDESC:
    1715           0 :     return pari_sprintf("invalid file descriptor in %Ps [%Ps]", gel(e,2), gel(e,3));
    1716          84 :   case e_FLAG:
    1717          84 :     return pari_sprintf("invalid flag in %Ps.", gel(e,2));
    1718         413 :   case e_IMPL:
    1719         413 :     return pari_sprintf("sorry, %Ps is not yet implemented.", gel(e,2));
    1720           0 :   case e_PACKAGE:
    1721           0 :     return pari_sprintf("package %Ps is required, please install it.", gel(e,2));
    1722         602 :   case e_INV:
    1723         602 :     return pari_sprintf("impossible inverse in %Ps: %s.", gel(e,2),
    1724         602 :                         gdisplay(gel(e,3)));
    1725          63 :   case e_IRREDPOL:
    1726         126 :     return pari_sprintf("not an irreducible polynomial in %Ps: %s.",
    1727          63 :                         gel(e,2), gdisplay(gel(e,3)));
    1728           0 :   case e_MAXPRIME:
    1729             :     {
    1730           0 :       const char * msg = "not enough precomputed primes";
    1731           0 :       ulong c = itou(gel(e,2));
    1732           0 :       if (c) return pari_sprintf("%s, need primelimit ~ %lu.",msg, c);
    1733           0 :       else   return pari_strdup(msg);
    1734             :     }
    1735           0 :   case e_MEM:
    1736           0 :     return pari_strdup("not enough memory");
    1737         749 :   case e_MODULUS:
    1738             :     {
    1739         749 :       GEN x = gel(e,3), y = gel(e,4);
    1740         749 :       return pari_sprintf("inconsistent moduli in %Ps: %s != %s",
    1741         749 :                           gel(e,2), gdisplay(x), gdisplay(y));
    1742             :     }
    1743           0 :   case e_NONE: return NULL;
    1744        2709 :   case e_NOTFUNC:
    1745        2709 :     return pari_strdup("not a function in function call");
    1746        3528 :   case e_OP: case e_TYPE2:
    1747             :     {
    1748        3528 :       pari_sp av = avma;
    1749             :       char *v;
    1750        3528 :       const char *f, *op = GSTR(gel(e,2));
    1751        3528 :       const char *what = numerr == e_OP? "inconsistent": "forbidden";
    1752        3528 :       GEN x = gel(e,3);
    1753        3528 :       GEN y = gel(e,4);
    1754        3528 :       switch(*op)
    1755             :       {
    1756          14 :       case '+': f = "addition"; break;
    1757         126 :       case '*': f = "multiplication"; break;
    1758        2744 :       case '/': case '%': case '\\': f = "division"; break;
    1759           0 :       case '=': op = "-->"; f = "assignment"; break;
    1760         644 :       default:  f = op; op = ","; break;
    1761             :       }
    1762        3528 :       v = pari_sprintf("%s %s %s %s %s.", what,f,type_dim(x),op,type_dim(y));
    1763        3528 :       set_avma(av); return v;
    1764             :     }
    1765         200 :   case e_COMPONENT:
    1766             :     {
    1767         200 :       const char *f= GSTR(gel(e,2));
    1768         200 :       const char *op= GSTR(gel(e,3));
    1769         200 :       GEN l = gel(e,4);
    1770         200 :       if (!*f)
    1771         147 :         return pari_sprintf("nonexistent component: index %s %Ps",op,l);
    1772          53 :       return pari_sprintf("nonexistent component in %s: index %s %Ps",f,op,l);
    1773             :     }
    1774        2150 :   case e_DOMAIN:
    1775             :     {
    1776        2150 :       const char *f = GSTR(gel(e,2));
    1777        2150 :       const char *v = GSTR(gel(e,3));
    1778        2150 :       const char *op= GSTR(gel(e,4));
    1779        2150 :       GEN l = gel(e,5);
    1780        2150 :       if (!*op)
    1781          35 :         return pari_sprintf("domain error in %s: %s out of range",f,v);
    1782        2115 :       return pari_sprintf("domain error in %s: %s %s %Ps",f,v,op,l);
    1783             :     }
    1784         182 :   case e_PRIORITY:
    1785             :     {
    1786         182 :       const char *f = GSTR(gel(e,2));
    1787         182 :       long vx = gvar(gel(e,3));
    1788         182 :       const char *op= GSTR(gel(e,4));
    1789         182 :       long v = itos(gel(e,5));
    1790         182 :       return pari_sprintf("incorrect priority in %s: variable %Ps %s %Ps",f,
    1791             :              pol_x(vx), op, pol_x(v));
    1792             :     }
    1793         119 :   case e_OVERFLOW:
    1794         119 :     return pari_sprintf("overflow in %Ps.", gel(e,2));
    1795         217 :   case e_PREC:
    1796         217 :     return pari_sprintf("precision too low in %Ps.", gel(e,2));
    1797          77 :   case e_PRIME:
    1798         154 :     return pari_sprintf("not a prime number in %Ps: %s.",
    1799          77 :                         gel(e,2), gdisplay(gel(e,3)));
    1800          49 :   case e_ROOTS0:
    1801          49 :     return pari_sprintf("zero polynomial in %Ps.", gel(e,2));
    1802          84 :   case e_SQRTN:
    1803         168 :     return pari_sprintf("not an n-th power residue in %Ps: %s.",
    1804          84 :                         gel(e,2), gdisplay(gel(e,3)));
    1805           7 :   case e_STACK:
    1806             :   case e_STACKTHREAD:
    1807             :     {
    1808           7 :       const char *stack = numerr == e_STACK? "PARI": "thread";
    1809           7 :       const char *var = numerr == e_STACK? "parisizemax": "threadsizemax";
    1810           0 :       size_t rsize = numerr == e_STACKTHREAD && GP_DATA->threadsize ?
    1811           7 :                                 GP_DATA->threadsize: pari_mainstack->rsize;
    1812           7 :       size_t vsize = numerr == e_STACK? pari_mainstack->vsize:
    1813           0 :                                         GP_DATA->threadsizemax;
    1814           7 :       char *buf = (char *) pari_malloc(512*sizeof(char));
    1815           7 :       if (vsize)
    1816             :       {
    1817           0 :         sprintf(buf, "the %s stack overflows !\n"
    1818             :             "  current stack size: %lu (%.3f Mbytes)\n"
    1819             :             "  [hint] you can increase '%s' using default()\n",
    1820           0 :             stack, (ulong)vsize, (double)vsize/1048576., var);
    1821             :       }
    1822             :       else
    1823             :       {
    1824           7 :         sprintf(buf, "the %s stack overflows !\n"
    1825             :             "  current stack size: %lu (%.3f Mbytes)\n"
    1826             :             "  [hint] set '%s' to a nonzero value in your GPRC\n",
    1827           7 :             stack, (ulong)rsize, (double)rsize/1048576., var);
    1828             :       }
    1829           7 :       return buf;
    1830             :     }
    1831           0 :   case e_SYNTAX:
    1832           0 :     return pari_strdup(GSTR(gel(e,2)));
    1833        5433 :   case e_TYPE:
    1834       10866 :     return pari_sprintf("incorrect type in %Ps (%s).",
    1835        5433 :                         gel(e,2), type_name(typ(gel(e,3))));
    1836          14 :   case e_USER:
    1837          14 :     return pari_sprint0("user error: ", gel(e,2), f_RAW);
    1838         280 :   case e_VAR:
    1839             :     {
    1840         280 :       GEN x = gel(e,3), y = gel(e,4);
    1841         840 :       return pari_sprintf("inconsistent variables in %Ps, %Ps != %Ps.",
    1842         280 :                           gel(e,2), pol_x(varn(x)), pol_x(varn(y)));
    1843             :     }
    1844             :   }
    1845             :   return NULL; /*LCOV_EXCL_LINE*/
    1846             : }
    1847             : 
    1848             : static int
    1849       10183 : pari_err_display(GEN err)
    1850             : {
    1851       10183 :   long numerr=err_get_num(err);
    1852       10183 :   err_init();
    1853       10183 :   if (numerr==e_SYNTAX)
    1854             :   {
    1855          93 :     const char *msg = GSTR(gel(err,2));
    1856          93 :     const char *s     = (const char *) gmael(err,3,1);
    1857          93 :     const char *entry = (const char *) gmael(err,3,2);
    1858          93 :     print_errcontext(pariErr, msg, s, entry);
    1859             :   }
    1860             :   else
    1861             :   {
    1862             :     char *s;
    1863       10090 :     closure_err(0);
    1864       10090 :     err_init_msg(numerr==e_USER);
    1865       10090 :     s = pari_err2str(err); pariErr->puts(s); pari_free(s);
    1866       10090 :     if (numerr==e_NOTFUNC)
    1867             :     {
    1868        2709 :       GEN fun = gel(err,2);
    1869        2709 :       if (gequalX(fun))
    1870             :       {
    1871        2709 :         entree *ep = varentries[varn(fun)];
    1872        2709 :         const char *t = ep->name;
    1873        2709 :         if (cb_pari_whatnow) cb_pari_whatnow(pariErr,t,1);
    1874             :       }
    1875             :     }
    1876             :   }
    1877       10169 :   out_term_color(pariErr, c_NONE);
    1878       10169 :   pariErr->flush(); return 0;
    1879             : }
    1880             : 
    1881             : void
    1882       45402 : pari_err(int numerr, ...)
    1883             : {
    1884             :   va_list ap;
    1885             :   GEN E;
    1886             : 
    1887       45402 :   va_start(ap,numerr);
    1888             : 
    1889       45402 :   if (numerr)
    1890       45383 :     E = pari_err2GEN(numerr,ap);
    1891             :   else
    1892             :   {
    1893          19 :     E = va_arg(ap,GEN);
    1894          19 :     numerr = err_get_num(E);
    1895             :   }
    1896       45400 :   global_err_data = E;
    1897       45400 :   if (*iferr_env) longjmp(*iferr_env, numerr);
    1898       10190 :   mt_err_recover(numerr);
    1899       10183 :   va_end(ap);
    1900       20352 :   if (cb_pari_err_handle &&
    1901       10183 :       cb_pari_err_handle(E)) return;
    1902       20329 :   if (cb_pari_handle_exception &&
    1903       10167 :       cb_pari_handle_exception(numerr)) return;
    1904       10162 :   err_recover(numerr);
    1905             : }
    1906             : 
    1907             : GEN
    1908       70414 : pari_err_last(void) { return global_err_data; }
    1909             : 
    1910             : const char *
    1911       26912 : numerr_name(long numerr)
    1912             : {
    1913       26912 :   switch ((enum err_list) numerr)
    1914             :   {
    1915           0 :   case e_ALARM:    return "e_ALARM";
    1916           0 :   case e_ARCH:     return "e_ARCH";
    1917           0 :   case e_BUG:      return "e_BUG";
    1918           0 :   case e_COMPONENT: return "e_COMPONENT";
    1919           0 :   case e_CONSTPOL: return "e_CONSTPOL";
    1920           0 :   case e_COPRIME:  return "e_COPRIME";
    1921           0 :   case e_DIM:      return "e_DIM";
    1922          56 :   case e_DOMAIN:   return "e_DOMAIN";
    1923           0 :   case e_FILE:     return "e_FILE";
    1924           0 :   case e_FILEDESC: return "e_FILEDESC";
    1925           7 :   case e_FLAG:     return "e_FLAG";
    1926          28 :   case e_IMPL:     return "e_IMPL";
    1927       19093 :   case e_INV:      return "e_INV";
    1928           0 :   case e_IRREDPOL: return "e_IRREDPOL";
    1929           0 :   case e_MAXPRIME: return "e_MAXPRIME";
    1930           0 :   case e_MEM:      return "e_MEM";
    1931           0 :   case e_MISC:     return "e_MISC";
    1932           0 :   case e_MODULUS:  return "e_MODULUS";
    1933           0 :   case e_NONE:     return "e_NONE";
    1934           0 :   case e_NOTFUNC:  return "e_NOTFUNC";
    1935           0 :   case e_OP:       return "e_OP";
    1936           0 :   case e_OVERFLOW: return "e_OVERFLOW";
    1937           0 :   case e_PACKAGE:  return "e_PACKAGE";
    1938           0 :   case e_PREC:     return "e_PREC";
    1939           0 :   case e_PRIME:    return "e_PRIME";
    1940          49 :   case e_PRIORITY: return "e_PRIORITY";
    1941           0 :   case e_ROOTS0:   return "e_ROOTS0";
    1942           0 :   case e_SQRTN:    return "e_SQRTN";
    1943           0 :   case e_STACK:    return "e_STACK";
    1944           0 :   case e_SYNTAX:   return "e_SYNTAX";
    1945           0 :   case e_STACKTHREAD:   return "e_STACKTHREAD";
    1946           0 :   case e_TYPE2:    return "e_TYPE2";
    1947        7679 :   case e_TYPE:     return "e_TYPE";
    1948           0 :   case e_USER:     return "e_USER";
    1949           0 :   case e_VAR:      return "e_VAR";
    1950             :   }
    1951           0 :   return "invalid error number";
    1952             : }
    1953             : 
    1954             : long
    1955          21 : name_numerr(const char *s)
    1956             : {
    1957          21 :   if (!strcmp(s,"e_ALARM"))    return e_ALARM;
    1958          21 :   if (!strcmp(s,"e_ARCH"))     return e_ARCH;
    1959          21 :   if (!strcmp(s,"e_BUG"))      return e_BUG;
    1960          21 :   if (!strcmp(s,"e_COMPONENT")) return e_COMPONENT;
    1961          21 :   if (!strcmp(s,"e_CONSTPOL")) return e_CONSTPOL;
    1962          21 :   if (!strcmp(s,"e_COPRIME"))  return e_COPRIME;
    1963          21 :   if (!strcmp(s,"e_DIM"))      return e_DIM;
    1964          21 :   if (!strcmp(s,"e_DOMAIN"))   return e_DOMAIN;
    1965          21 :   if (!strcmp(s,"e_FILE"))     return e_FILE;
    1966          21 :   if (!strcmp(s,"e_FILEDESC")) return e_FILEDESC;
    1967          21 :   if (!strcmp(s,"e_FLAG"))     return e_FLAG;
    1968          21 :   if (!strcmp(s,"e_IMPL"))     return e_IMPL;
    1969          21 :   if (!strcmp(s,"e_INV"))      return e_INV;
    1970           0 :   if (!strcmp(s,"e_IRREDPOL")) return e_IRREDPOL;
    1971           0 :   if (!strcmp(s,"e_MAXPRIME")) return e_MAXPRIME;
    1972           0 :   if (!strcmp(s,"e_MEM"))      return e_MEM;
    1973           0 :   if (!strcmp(s,"e_MISC"))     return e_MISC;
    1974           0 :   if (!strcmp(s,"e_MODULUS"))  return e_MODULUS;
    1975           0 :   if (!strcmp(s,"e_NONE"))     return e_NONE;
    1976           0 :   if (!strcmp(s,"e_NOTFUNC"))  return e_NOTFUNC;
    1977           0 :   if (!strcmp(s,"e_OP"))       return e_OP;
    1978           0 :   if (!strcmp(s,"e_OVERFLOW")) return e_OVERFLOW;
    1979           0 :   if (!strcmp(s,"e_PACKAGE"))  return e_PACKAGE;
    1980           0 :   if (!strcmp(s,"e_PREC"))     return e_PREC;
    1981           0 :   if (!strcmp(s,"e_PRIME"))    return e_PRIME;
    1982           0 :   if (!strcmp(s,"e_PRIORITY")) return e_PRIORITY;
    1983           0 :   if (!strcmp(s,"e_ROOTS0"))   return e_ROOTS0;
    1984           0 :   if (!strcmp(s,"e_SQRTN"))    return e_SQRTN;
    1985           0 :   if (!strcmp(s,"e_STACK"))    return e_STACK;
    1986           0 :   if (!strcmp(s,"e_SYNTAX"))   return e_SYNTAX;
    1987           0 :   if (!strcmp(s,"e_TYPE"))     return e_TYPE;
    1988           0 :   if (!strcmp(s,"e_TYPE2"))    return e_TYPE2;
    1989           0 :   if (!strcmp(s,"e_USER"))     return e_USER;
    1990           0 :   if (!strcmp(s,"e_VAR"))      return e_VAR;
    1991           0 :   pari_err(e_MISC,"unknown error name");
    1992             :   return -1; /* LCOV_EXCL_LINE */
    1993             : }
    1994             : 
    1995             : GEN
    1996       26912 : errname(GEN err)
    1997             : {
    1998       26912 :   if (typ(err)!=t_ERROR) pari_err_TYPE("errname",err);
    1999       26912 :   return strtoGENstr(numerr_name(err_get_num(err)));
    2000             : }
    2001             : 
    2002             : /* Try f (trapping error e), recover using r (break_loop, if NULL) */
    2003             : GEN
    2004          21 : trap0(const char *e, GEN r, GEN f)
    2005             : {
    2006          21 :   long numerr = CATCH_ALL;
    2007             :   GEN x;
    2008          21 :   if (!e || !*e) numerr = CATCH_ALL;
    2009          21 :   else numerr = name_numerr(e);
    2010          21 :   if (!f) {
    2011           0 :     pari_warn(warner,"default handlers are no longer supported --> ignored");
    2012           0 :     return gnil;
    2013             :   }
    2014          21 :   x = closure_trapgen(f, numerr);
    2015          14 :   if (x == (GEN)1L) x = r? closure_evalgen(r): gnil;
    2016          14 :   return x;
    2017             : }
    2018             : 
    2019             : /*******************************************************************/
    2020             : /*                                                                */
    2021             : /*                       CLONING & COPY                            */
    2022             : /*                  Replicate an existing GEN                      */
    2023             : /*                                                                 */
    2024             : /*******************************************************************/
    2025             : /* lontyp[tx] = 0 (non recursive type) or number of codewords for type tx */
    2026             : 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 };
    2027             : 
    2028             : static GEN
    2029        3737 : list_internal_copy(GEN z, long nmax)
    2030             : {
    2031             :   long i, l;
    2032             :   GEN a;
    2033        3737 :   if (!z) return NULL;
    2034        1045 :   l = lg(z);
    2035        1045 :   a = newblock(nmax+1);
    2036       49050 :   for (i = 1; i < l; i++) gel(a,i) = gel(z,i)? gclone(gel(z,i)): gen_0;
    2037        1045 :   a[0] = z[0]; setisclone(a); return a;
    2038             : }
    2039             : 
    2040             : static void
    2041        3737 : listassign(GEN x, GEN y)
    2042             : {
    2043        3737 :   long nmax = list_nmax(x);
    2044        3737 :   GEN L = list_data(x);
    2045        3737 :   if (!nmax && L) nmax = lg(L) + 32; /* not malloc'ed yet */
    2046        3737 :   y[1] = evaltyp(list_typ(x))|evallg(nmax);
    2047        3737 :   list_data(y) = list_internal_copy(L, nmax);
    2048        3737 : }
    2049             : 
    2050             : /* transform a non-malloced list (e.g. from gtolist or gtomap) to a malloced
    2051             :  * list suitable for listput */
    2052             : GEN
    2053           0 : listinit(GEN x)
    2054             : {
    2055           0 :   GEN y = cgetg(3, t_LIST);
    2056           0 :   listassign(x, y); return y;
    2057             : }
    2058             : 
    2059             : /* copy list on the PARI stack */
    2060             : GEN
    2061         541 : listcopy(GEN x)
    2062             : {
    2063         541 :   GEN y = mklist(), L = list_data(x);
    2064         541 :   if (L) list_data(y) = gcopy(L);
    2065         541 :   y[1] = evaltyp(list_typ(x));
    2066         541 :   return y;
    2067             : }
    2068             : 
    2069             : GEN
    2070  4073649430 : gcopy(GEN x)
    2071             : {
    2072  4073649430 :   long tx = typ(x), lx, i;
    2073             :   GEN y;
    2074  4073649430 :   switch(tx)
    2075             :   { /* non recursive types */
    2076  3520321906 :     case t_INT: return signe(x)? icopy(x): gen_0;
    2077   347421221 :     case t_REAL:
    2078             :     case t_STR:
    2079   347421221 :     case t_VECSMALL: return leafcopy(x);
    2080             :     /* one more special case */
    2081         541 :     case t_LIST: return listcopy(x);
    2082             :   }
    2083   205905762 :   y = cgetg_copy(x, &lx);
    2084   206218038 :   if (lontyp[tx] == 1) i = 1; else { y[1] = x[1]; i = 2; }
    2085   976524800 :   for (; i<lx; i++) gel(y,i) = gcopy(gel(x,i));
    2086   206219841 :   return y;
    2087             : }
    2088             : 
    2089             : /* as gcopy, but truncate to the first lx components if recursive type
    2090             :  * [ leaves use their own lg ]. No checks. */
    2091             : GEN
    2092         742 : gcopy_lg(GEN x, long lx)
    2093             : {
    2094         742 :   long tx = typ(x), i;
    2095             :   GEN y;
    2096         742 :   switch(tx)
    2097             :   { /* non recursive types */
    2098           0 :     case t_INT: return signe(x)? icopy(x): gen_0;
    2099           0 :     case t_REAL:
    2100             :     case t_STR:
    2101           0 :     case t_VECSMALL: return leafcopy(x);
    2102             :     /* one more special case */
    2103           0 :     case t_LIST: return listcopy(x);
    2104             :   }
    2105         742 :   y = cgetg(lx, tx);
    2106         742 :   if (lontyp[tx] == 1) i = 1; else { y[1] = x[1]; i = 2; }
    2107        2051 :   for (; i<lx; i++) gel(y,i) = gcopy(gel(x,i));
    2108         742 :   return y;
    2109             : }
    2110             : 
    2111             : /* cf cgetg_copy: "allocate" (by updating first codeword only) for subsequent
    2112             :  * copy of x, as if avma = *AVMA */
    2113             : INLINE GEN
    2114   801703247 : cgetg_copy_avma(GEN x, long *plx, pari_sp *AVMA) {
    2115             :   GEN z;
    2116   801703247 :   *plx = lg(x);
    2117   801703247 :   z = ((GEN)*AVMA) - *plx;
    2118   801703247 :   z[0] = x[0] & (TYPBITS|LGBITS);
    2119   801703247 :   *AVMA = (pari_sp)z; return z;
    2120             : }
    2121             : INLINE GEN
    2122         448 : cgetlist_avma(pari_sp *AVMA)
    2123             : {
    2124         448 :   GEN y = ((GEN)*AVMA) - 3;
    2125         448 :   y[0] = _evallg(3) | evaltyp(t_LIST);
    2126         448 :   *AVMA = (pari_sp)y; return y;
    2127             : }
    2128             : 
    2129             : /* copy x as if avma = *AVMA, update *AVMA */
    2130             : GEN
    2131  2921040515 : gcopy_avma(GEN x, pari_sp *AVMA)
    2132             : {
    2133  2921040515 :   long i, lx, tx = typ(x);
    2134             :   GEN y;
    2135             : 
    2136  2921040515 :   switch(typ(x))
    2137             :   { /* non recursive types */
    2138  2737578097 :     case t_INT:
    2139  2737578097 :       if (lgefint(x) == 2) return gen_0;
    2140  2246408269 :       *AVMA = (pari_sp)icopy_avma(x, *AVMA);
    2141  2246409499 :       return (GEN)*AVMA;
    2142    57868997 :     case t_REAL: case t_STR: case t_VECSMALL:
    2143    57868997 :       *AVMA = (pari_sp)leafcopy_avma(x, *AVMA);
    2144    57976907 :       return (GEN)*AVMA;
    2145             : 
    2146             :     /* one more special case */
    2147         448 :     case t_LIST:
    2148         448 :       y = cgetlist_avma(AVMA);
    2149         448 :       listassign(x, y); return y;
    2150             : 
    2151             :   }
    2152   125592973 :   y = cgetg_copy_avma(x, &lx, AVMA);
    2153   126250962 :   if (lontyp[tx] == 1) i = 1; else { y[1] = x[1]; i = 2; }
    2154   585468459 :   for (; i<lx; i++) gel(y,i) = gcopy_avma(gel(x,i), AVMA);
    2155   126348210 :   return y;
    2156             : }
    2157             : 
    2158             : /* [copy_bin/bin_copy:] same as gcopy_avma but use NULL to code an exact 0, and
    2159             :  * make shallow copies of finalized t_LISTs */
    2160             : static GEN
    2161  4175299673 : gcopy_av0(GEN x, pari_sp *AVMA)
    2162             : {
    2163  4175299673 :   long i, lx, tx = typ(x);
    2164             :   GEN y;
    2165             : 
    2166  4175299673 :   switch(tx)
    2167             :   { /* non recursive types */
    2168  3117379086 :     case t_INT:
    2169  3117379086 :       if (!signe(x)) return NULL; /* special marker */
    2170  1540260932 :       *AVMA = (pari_sp)icopy_avma(x, *AVMA);
    2171  1540660079 :       return (GEN)*AVMA;
    2172          49 :     case t_LIST:
    2173          49 :       if (list_data(x) && !list_nmax(x)) break; /* not finalized, need copy */
    2174             :       /* else finalized: shallow copy */
    2175             :     case t_REAL: case t_STR: case t_VECSMALL:
    2176   383757275 :       *AVMA = (pari_sp)leafcopy_avma(x, *AVMA);
    2177   383756561 :       return (GEN)*AVMA;
    2178             :   }
    2179   674163312 :   y = cgetg_copy_avma(x, &lx, AVMA);
    2180   675419462 :   if (lontyp[tx] == 1) i = 1; else { y[1] = x[1]; i = 2; }
    2181  4366069615 :   for (; i<lx; i++) gel(y,i) = gcopy_av0(gel(x,i), AVMA);
    2182   675683838 :   return y;
    2183             : }
    2184             : 
    2185             : INLINE GEN
    2186           0 : icopy_avma_canon(GEN x, pari_sp AVMA)
    2187             : {
    2188           0 :   long i, lx = lgefint(x);
    2189           0 :   GEN y = ((GEN)AVMA) - lx;
    2190           0 :   y[0] = evaltyp(t_INT)|evallg(lx); /* kills isclone */
    2191           0 :   y[1] = x[1]; x = int_MSW(x);
    2192           0 :   for (i=2; i<lx; i++, x = int_precW(x)) y[i] = *x;
    2193           0 :   return y;
    2194             : }
    2195             : 
    2196             : /* [copy_bin_canon:] same as gcopy_av0, but copy integers in
    2197             :  * canonical (native kernel) form and make a full copy of t_LISTs */
    2198             : static GEN
    2199           0 : gcopy_av0_canon(GEN x, pari_sp *AVMA)
    2200             : {
    2201           0 :   long i, lx, tx = typ(x);
    2202             :   GEN y;
    2203             : 
    2204           0 :   switch(tx)
    2205             :   { /* non recursive types */
    2206           0 :     case t_INT:
    2207           0 :       if (!signe(x)) return NULL; /* special marker */
    2208           0 :       *AVMA = (pari_sp)icopy_avma_canon(x, *AVMA);
    2209           0 :       return (GEN)*AVMA;
    2210           0 :     case t_REAL: case t_STR: case t_VECSMALL:
    2211           0 :       *AVMA = (pari_sp)leafcopy_avma(x, *AVMA);
    2212           0 :       return (GEN)*AVMA;
    2213             : 
    2214             :     /* one more special case */
    2215           0 :     case t_LIST:
    2216             :     {
    2217           0 :       long t = list_typ(x);
    2218           0 :       GEN y = cgetlist_avma(AVMA), z = list_data(x);
    2219           0 :       if (z) {
    2220           0 :         list_data(y) = gcopy_av0_canon(z, AVMA);
    2221           0 :         y[1] = evaltyp(t)|evallg(lg(z)-1);
    2222             :       } else {
    2223           0 :         list_data(y) = NULL;
    2224           0 :         y[1] = evaltyp(t);
    2225             :       }
    2226           0 :       return y;
    2227             :     }
    2228             :   }
    2229           0 :   y = cgetg_copy_avma(x, &lx, AVMA);
    2230           0 :   if (lontyp[tx] == 1) i = 1; else { y[1] = x[1]; i = 2; }
    2231           0 :   for (; i<lx; i++) gel(y,i) = gcopy_av0_canon(gel(x,i), AVMA);
    2232           0 :   return y;
    2233             : }
    2234             : 
    2235             : /* [copy_bin/bin_copy:] size (number of words) required for
    2236             :  * gcopy_av0_canon(x) */
    2237             : static long
    2238           0 : taille0_canon(GEN x)
    2239             : {
    2240           0 :   long i,n,lx, tx = typ(x);
    2241           0 :   switch(tx)
    2242             :   { /* non recursive types */
    2243           0 :     case t_INT: return signe(x)? lgefint(x): 0;
    2244           0 :     case t_REAL:
    2245             :     case t_STR:
    2246           0 :     case t_VECSMALL: return lg(x);
    2247             : 
    2248             :     /* one more special case */
    2249           0 :     case t_LIST:
    2250             :     {
    2251           0 :       GEN L = list_data(x);
    2252           0 :       return L? 3 + taille0_canon(L): 3;
    2253             :     }
    2254             :   }
    2255           0 :   n = lx = lg(x);
    2256           0 :   for (i=lontyp[tx]; i<lx; i++) n += taille0_canon(gel(x,i));
    2257           0 :   return n;
    2258             : }
    2259             : 
    2260             : /* [copy_bin/bin_copy:] size (number of words) required for gcopy_av0(x) */
    2261             : static long
    2262  4177269881 : taille0(GEN x)
    2263             : {
    2264  4177269881 :   long i,n,lx, tx = typ(x);
    2265  4177269881 :   switch(tx)
    2266             :   { /* non recursive types */
    2267  3118145178 :     case t_INT:
    2268  3118145178 :       lx = lgefint(x);
    2269  3118145178 :       return lx == 2? 0: lx;
    2270          49 :     case t_LIST:
    2271             :     {
    2272          49 :       GEN L = list_data(x);
    2273          49 :       if (L && !list_nmax(x)) break; /* not finalized, deep copy */
    2274             :     }
    2275             :     /* else finalized: shallow */
    2276             :     case t_REAL:
    2277             :     case t_STR:
    2278             :     case t_VECSMALL:
    2279   383793445 :       return lg(x);
    2280             :   }
    2281   675331258 :   n = lx = lg(x);
    2282  4367753536 :   for (i=lontyp[tx]; i<lx; i++) n += taille0(gel(x,i));
    2283   675381083 :   return n;
    2284             : }
    2285             : 
    2286             : static long
    2287  3005652864 : gsizeclone_i(GEN x)
    2288             : {
    2289  3005652864 :   long i,n,lx, tx = typ(x);
    2290  3005652864 :   switch(tx)
    2291             :   { /* non recursive types */
    2292  2737587684 :     case t_INT: lx = lgefint(x); return lx == 2? 0: lx;;
    2293    69515225 :     case t_REAL:
    2294             :     case t_STR:
    2295    69515225 :     case t_VECSMALL: return lg(x);
    2296             : 
    2297        3737 :     case t_LIST: return 3;
    2298   198546218 :     default:
    2299   198546218 :       n = lx = lg(x);
    2300  3122771657 :       for (i=lontyp[tx]; i<lx; i++) n += gsizeclone_i(gel(x,i));
    2301   198678721 :       return n;
    2302             :   }
    2303             : }
    2304             : 
    2305             : /* #words needed to clone x; t_LIST is a special case since list_data() is
    2306             :  * malloc'ed later, in list_internal_copy() */
    2307             : static long
    2308   222586629 : gsizeclone(GEN x) { return (typ(x) == t_INT)? lgefint(x): gsizeclone_i(x); }
    2309             : 
    2310             : long
    2311     2214422 : gsizeword(GEN x)
    2312             : {
    2313     2214422 :   long i, n, lx, tx = typ(x);
    2314     2214422 :   switch(tx)
    2315             :   { /* non recursive types */
    2316     1676388 :     case t_INT:
    2317             :     case t_REAL:
    2318             :     case t_STR:
    2319     1676388 :     case t_VECSMALL: return lg(x);
    2320             : 
    2321           7 :     case t_LIST:
    2322           7 :       x = list_data(x);
    2323           7 :       return x? 3 + gsizeword(x): 3;
    2324             : 
    2325      538027 :     default:
    2326      538027 :       n = lx = lg(x);
    2327     2752295 :       for (i=lontyp[tx]; i<lx; i++) n += gsizeword(gel(x,i));
    2328      538027 :       return n;
    2329             :   }
    2330             : }
    2331             : long
    2332         147 : gsizebyte(GEN x) { return gsizeword(x) * sizeof(long); }
    2333             : 
    2334             : /* return a clone of x structured as a gcopy */
    2335             : GENbin*
    2336   485037642 : copy_bin(GEN x)
    2337             : {
    2338   485037642 :   long t = taille0(x);
    2339   485068267 :   GENbin *p = (GENbin*)pari_malloc(sizeof(GENbin) + t*sizeof(long));
    2340   485118789 :   pari_sp AVMA = (pari_sp)(GENbinbase(p) + t);
    2341   485093401 :   p->rebase = &shiftaddress;
    2342   485093401 :   p->len = t;
    2343   485093401 :   p->x   = gcopy_av0(x, &AVMA);
    2344   485070580 :   p->base= (GEN)AVMA; return p;
    2345             : }
    2346             : 
    2347             : /* same, writing t_INT in canonical native form */
    2348             : GENbin*
    2349           0 : copy_bin_canon(GEN x)
    2350             : {
    2351           0 :   long t = taille0_canon(x);
    2352           0 :   GENbin *p = (GENbin*)pari_malloc(sizeof(GENbin) + t*sizeof(long));
    2353           0 :   pari_sp AVMA = (pari_sp)(GENbinbase(p) + t);
    2354           0 :   p->rebase = &shiftaddress_canon;
    2355           0 :   p->len = t;
    2356           0 :   p->x   = gcopy_av0_canon(x, &AVMA);
    2357           0 :   p->base= (GEN)AVMA; return p;
    2358             : }
    2359             : 
    2360             : GEN
    2361   222586911 : gclone(GEN x)
    2362             : {
    2363   222586911 :   long i,lx,tx = typ(x), t = gsizeclone(x);
    2364   222591157 :   GEN y = newblock(t);
    2365   222597417 :   switch(tx)
    2366             :   { /* non recursive types */
    2367   141118301 :     case t_INT:
    2368   141118301 :       lx = lgefint(x);
    2369   141118301 :       y[0] = evaltyp(t_INT)|evallg(lx);
    2370   762181003 :       for (i=1; i<lx; i++) y[i] = x[i];
    2371   141118288 :       break;
    2372     9519232 :     case t_REAL:
    2373             :     case t_STR:
    2374             :     case t_VECSMALL:
    2375     9519232 :       lx = lg(x);
    2376   133020008 :       for (i=0; i<lx; i++) y[i] = x[i];
    2377     9519232 :       break;
    2378             : 
    2379             :     /* one more special case */
    2380        3289 :     case t_LIST:
    2381        3289 :       y[0] = evaltyp(t_LIST)|_evallg(3);
    2382        3289 :       listassign(x, y);
    2383        3289 :       break;
    2384    71956595 :     default: {
    2385    71956595 :       pari_sp AVMA = (pari_sp)(y + t);
    2386    71956595 :       lx = lg(x);
    2387    71956595 :       y[0] = x[0];
    2388    71956595 :       if (lontyp[tx] == 1) i = 1; else { y[1] = x[1]; i = 2; }
    2389  2534436389 :       for (; i<lx; i++) gel(y,i) = gcopy_avma(gel(x,i), &AVMA);
    2390             :     }
    2391             :   }
    2392   222616131 :   setisclone(y); return y;
    2393             : }
    2394             : 
    2395             : void
    2396  2600286427 : shiftaddress(GEN x, long dec)
    2397             : {
    2398  2600286427 :   long i, lx, tx = typ(x);
    2399  2600286427 :   if (is_recursive_t(tx))
    2400             :   {
    2401   675824727 :     if (tx == t_LIST)
    2402             :     {
    2403          49 :       if (!list_data(x) || list_nmax(x)) return; /* empty or finalized */
    2404             :       /* not finalized, update pointers  */
    2405             :     }
    2406   675824685 :     lx = lg(x);
    2407  4368225800 :     for (i=lontyp[tx]; i<lx; i++) {
    2408  3692582752 :       if (!x[i]) gel(x,i) = gen_0;
    2409             :       else
    2410             :       {
    2411  2150604493 :         x[i] += dec;
    2412  2150604493 :         shiftaddress(gel(x,i), dec);
    2413             :       }
    2414             :     }
    2415             :   }
    2416             : }
    2417             : 
    2418             : void
    2419           0 : shiftaddress_canon(GEN x, long dec)
    2420             : {
    2421           0 :   long i, lx, tx = typ(x);
    2422           0 :   switch(tx)
    2423             :   { /* non recursive types */
    2424           0 :     case t_INT: {
    2425             :       GEN y;
    2426           0 :       lx = lgefint(x); if (lx <= 3) return;
    2427           0 :       y = x + 2;
    2428           0 :       x = int_MSW(x);  if (x == y) return;
    2429           0 :       while (x > y) { lswap(*x, *y); x = int_precW(x); y++; }
    2430           0 :       break;
    2431             :     }
    2432           0 :     case t_REAL:
    2433             :     case t_STR:
    2434             :     case t_VECSMALL:
    2435           0 :       break;
    2436             : 
    2437             :     /* one more special case */
    2438           0 :     case t_LIST:
    2439           0 :       if (!list_data(x)) break;
    2440             :     default: /* Fall through */
    2441           0 :       lx = lg(x);
    2442           0 :       for (i=lontyp[tx]; i<lx; i++) {
    2443           0 :         if (!x[i]) gel(x,i) = gen_0;
    2444             :         else
    2445             :         {
    2446           0 :           x[i] += dec;
    2447           0 :           shiftaddress_canon(gel(x,i), dec);
    2448             :         }
    2449             :       }
    2450             :   }
    2451             : }
    2452             : 
    2453             : /********************************************************************/
    2454             : /**                                                                **/
    2455             : /**                INSERT DYNAMIC OBJECT IN STRUCTURE              **/
    2456             : /**                                                                **/
    2457             : /********************************************************************/
    2458             : GEN
    2459          35 : obj_reinit(GEN S)
    2460             : {
    2461          35 :   GEN s, T = leafcopy(S);
    2462          35 :   long a = lg(T)-1;
    2463          35 :   s = gel(T,a);
    2464          35 :   gel(T,a) = zerovec(lg(s)-1);
    2465          35 :   return T;
    2466             : }
    2467             : 
    2468             : GEN
    2469     1269588 : obj_init(long d, long n)
    2470             : {
    2471     1269588 :   GEN S = cgetg(d+2, t_VEC);
    2472     1269588 :   gel(S, d+1) = zerovec(n);
    2473     1269589 :   return S;
    2474             : }
    2475             : 
    2476             : /* as obj_insert. WITHOUT cloning (for libpari, when creating a *new* obj
    2477             :  * from an existing one) */
    2478             : GEN
    2479     1157866 : obj_insert(GEN S, long K, GEN O)
    2480             : {
    2481     1157866 :   GEN o, v = gel(S, lg(S)-1);
    2482     1157866 :   if (typ(v) != t_VEC) pari_err_TYPE("obj_insert", S);
    2483     1157866 :   if (!check_clone(v))
    2484             :   {
    2485           0 :     if (DEBUGLEVEL) pari_warn(warner,"trying to update parent object");
    2486           0 :     return gclone(O);
    2487             :   }
    2488     1157866 :   o = gel(v,K);
    2489     1157866 :   gel(v,K) = gclone(O); /*SIGINT: before unclone(o)*/
    2490     1157867 :   if (isclone(o)) gunclone(o); return gel(v,K);
    2491             : }
    2492             : 
    2493             : GEN
    2494       66416 : obj_insert_shallow(GEN S, long K, GEN O)
    2495             : {
    2496       66416 :   GEN v = gel(S, lg(S)-1);
    2497       66416 :   if (typ(v) != t_VEC) pari_err_TYPE("obj_insert", S);
    2498       66416 :   gel(v,K) = O;
    2499       66416 :   return gel(v,K);
    2500             : }
    2501             : 
    2502             : /* Does S [last position] contain data at position K ? Return it, or NULL */
    2503             : GEN
    2504     2644869 : obj_check(GEN S, long K)
    2505             : {
    2506     2644869 :   GEN O, v = gel(S, lg(S)-1);
    2507     2644869 :   if (typ(v) != t_VEC || K >= lg(v)) pari_err_TYPE("obj_check", S);
    2508     2644869 :   O = gel(v,K); return isintzero(O)? NULL: O;
    2509             : }
    2510             : 
    2511             : GEN
    2512      908515 : obj_checkbuild(GEN S, long tag, GEN (*build)(GEN))
    2513             : {
    2514      908515 :   GEN O = obj_check(S, tag);
    2515      908515 :   if (!O)
    2516      682905 :   { pari_sp av = avma; O = obj_insert(S, tag, build(S)); set_avma(av); }
    2517      908509 :   return O;
    2518             : }
    2519             : 
    2520             : GEN
    2521      164845 : obj_checkbuild_prec(GEN S, long tag, GEN (*build)(GEN,long),
    2522             :   long (*pr)(GEN), long prec)
    2523             : {
    2524      164845 :   pari_sp av = avma;
    2525      164845 :   GEN w = obj_check(S, tag);
    2526      164845 :   if (!w || pr(w) < prec) w = obj_insert(S, tag, build(S, prec));
    2527      164845 :   set_avma(av); return gcopy(w);
    2528             : }
    2529             : GEN
    2530       62386 : obj_checkbuild_realprec(GEN S, long tag, GEN (*build)(GEN,long), long prec)
    2531       62386 : { return obj_checkbuild_prec(S,tag,build,gprecision,prec); }
    2532             : GEN
    2533         497 : obj_checkbuild_padicprec(GEN S, long tag, GEN (*build)(GEN,long), long prec)
    2534         497 : { return obj_checkbuild_prec(S,tag,build,padicprec_relative,prec); }
    2535             : 
    2536             : /* Reset S [last position], freeing all clones */
    2537             : void
    2538       15008 : obj_free(GEN S)
    2539             : {
    2540       15008 :   GEN v = gel(S, lg(S)-1);
    2541             :   long i;
    2542       15008 :   if (typ(v) != t_VEC) pari_err_TYPE("obj_free", S);
    2543       88060 :   for (i = 1; i < lg(v); i++)
    2544             :   {
    2545       73052 :     GEN o = gel(v,i);
    2546       73052 :     gel(v,i) = gen_0;
    2547       73052 :     gunclone_deep(o);
    2548             :   }
    2549       15008 : }
    2550             : 
    2551             : /*******************************************************************/
    2552             : /*                                                                 */
    2553             : /*                         STACK MANAGEMENT                        */
    2554             : /*                                                                 */
    2555             : /*******************************************************************/
    2556             : INLINE void
    2557  4607869281 : dec_gerepile(pari_sp *x, pari_sp av0, pari_sp av, pari_sp tetpil, size_t dec)
    2558             : {
    2559  4607869281 :   if (*x < av && *x >= av0)
    2560             :   { /* update address if in stack */
    2561  4103606707 :     if (*x < tetpil) *x += dec;
    2562           0 :     else pari_err_BUG("gerepile, significant pointers lost");
    2563             :   }
    2564  4607877430 : }
    2565             : 
    2566             : void
    2567     4980369 : gerepileallsp(pari_sp av, pari_sp tetpil, int n, ...)
    2568             : {
    2569     4980369 :   const pari_sp av0 = avma;
    2570     4980369 :   const size_t dec = av-tetpil;
    2571             :   int i;
    2572     4980369 :   va_list a; va_start(a, n);
    2573     4980369 :   (void)gerepile(av,tetpil,NULL);
    2574    22841419 :   for (i=0; i<n; i++) dec_gerepile((pari_sp*)va_arg(a,GEN*), av0,av,tetpil,dec);
    2575     4981262 :   va_end(a);
    2576     4981262 : }
    2577             : 
    2578             : /* Takes an array of pointers to GENs, of length n.
    2579             :  * Cleans up the stack between av and tetpil, updating those GENs. */
    2580             : void
    2581     9035574 : gerepilemanysp(pari_sp av, pari_sp tetpil, GEN* gptr[], int n)
    2582             : {
    2583     9035574 :   const pari_sp av0 = avma;
    2584     9035574 :   const size_t dec = av-tetpil;
    2585             :   int i;
    2586     9035574 :   (void)gerepile(av,tetpil,NULL);
    2587    27136544 :   for (i=0; i<n; i++) dec_gerepile((pari_sp*)gptr[i], av0, av, tetpil, dec);
    2588     9035605 : }
    2589             : 
    2590             : /* Takes an array of GENs (cast to longs), of length n.
    2591             :  * Cleans up the stack between av and tetpil, updating those GENs. */
    2592             : void
    2593   514180799 : gerepilecoeffssp(pari_sp av, pari_sp tetpil, long *g, int n)
    2594             : {
    2595   514180799 :   const pari_sp av0 = avma;
    2596   514180799 :   const size_t dec = av-tetpil;
    2597             :   int i;
    2598   514180799 :   (void)gerepile(av,tetpil,NULL);
    2599  1543042707 :   for (i=0; i<n; i++,g++) dec_gerepile((pari_sp*)g, av0, av, tetpil, dec);
    2600   514351493 : }
    2601             : 
    2602             : static int
    2603           0 : dochk_gerepileupto(GEN av, GEN x)
    2604             : {
    2605             :   long i,lx,tx;
    2606           0 :   if (!isonstack(x)) return 1;
    2607           0 :   if (x > av)
    2608             :   {
    2609           0 :     pari_warn(warner,"bad object %Ps",x);
    2610           0 :     return 0;
    2611             :   }
    2612           0 :   tx = typ(x);
    2613           0 :   if (! is_recursive_t(tx)) return 1;
    2614             : 
    2615           0 :   lx = lg(x);
    2616           0 :   for (i=lontyp[tx]; i<lx; i++)
    2617           0 :     if (!dochk_gerepileupto(av, gel(x,i)))
    2618             :     {
    2619           0 :       pari_warn(warner,"bad component %ld in object %Ps",i,x);
    2620           0 :       return 0;
    2621             :     }
    2622           0 :   return 1;
    2623             : }
    2624             : /* check that x and all its components are out of stack, or have been
    2625             :  * created after av */
    2626             : int
    2627           0 : chk_gerepileupto(GEN x) { return dochk_gerepileupto(x, x); }
    2628             : 
    2629             : /* print stack between avma & av */
    2630             : void
    2631           0 : dbg_gerepile(pari_sp av)
    2632             : {
    2633           0 :   GEN x = (GEN)avma;
    2634           0 :   while (x < (GEN)av)
    2635             :   {
    2636           0 :     const long tx = typ(x), lx = lg(x);
    2637             :     GEN *a;
    2638             : 
    2639           0 :     pari_printf(" [%ld] %Ps:", x - (GEN)avma, x);
    2640           0 :     if (! is_recursive_t(tx)) { pari_putc('\n'); x += lx; continue; }
    2641           0 :     a = (GEN*)x + lontyp[tx]; x += lx;
    2642           0 :     for (  ; a < (GEN*)x; a++)
    2643             :     {
    2644           0 :       if (*a == gen_0)
    2645           0 :         pari_puts("  gen_0");
    2646           0 :       else if (*a == gen_1)
    2647           0 :         pari_puts("  gen_1");
    2648           0 :       else if (*a == gen_m1)
    2649           0 :         pari_puts("  gen_m1");
    2650           0 :       else if (*a == gen_2)
    2651           0 :         pari_puts("  gen_2");
    2652           0 :       else if (*a == gen_m2)
    2653           0 :         pari_puts("  gen_m2");
    2654           0 :       else if (*a == ghalf)
    2655           0 :         pari_puts("  ghalf");
    2656           0 :       else if (isclone(*a))
    2657           0 :         pari_printf("  %Ps (clone)", *a);
    2658             :       else
    2659           0 :         pari_printf("  %Ps [%ld]", *a, *a - (GEN)avma);
    2660           0 :       if (a+1 < (GEN*)x) pari_putc(',');
    2661             :     }
    2662           0 :     pari_printf("\n");
    2663             :   }
    2664           0 : }
    2665             : void
    2666           0 : dbg_gerepileupto(GEN q)
    2667             : {
    2668           0 :   err_printf("%Ps:\n", q);
    2669           0 :   dbg_gerepile((pari_sp) (q+lg(q)));
    2670           0 : }
    2671             : 
    2672             : GEN
    2673  1240976547 : gerepile(pari_sp av, pari_sp tetpil, GEN q)
    2674             : {
    2675  1240976547 :   const size_t dec = av - tetpil;
    2676  1240976547 :   const pari_sp av0 = avma;
    2677             :   GEN x, a;
    2678             : 
    2679  1240976547 :   if (dec == 0) return q;
    2680  1074727150 :   if ((long)dec < 0) pari_err(e_MISC,"lbot>ltop in gerepile");
    2681             : 
    2682             :   /* dec_gerepile(&q, av0, av, tetpil, dec), saving 1 comparison */
    2683  1075314958 :   if (q >= (GEN)av0 && q < (GEN)tetpil)
    2684   553060149 :     q = (GEN) (((pari_sp)q) + dec);
    2685             : 
    2686 24977795541 :   for (x = (GEN)av, a = (GEN)tetpil; a > (GEN)av0; ) *--x = *--a;
    2687  1075314958 :   set_avma((pari_sp)x);
    2688  5811001513 :   while (x < (GEN)av)
    2689             :   {
    2690  4735043060 :     const long tx = typ(x), lx = lg(x);
    2691             : 
    2692  4735043060 :     if (! is_recursive_t(tx)) { x += lx; continue; }
    2693   886445748 :     a = x + lontyp[tx]; x += lx;
    2694  4430153453 :     for (  ; a < x; a++) dec_gerepile((pari_sp*)a, av0, av, tetpil, dec);
    2695             :   }
    2696  1075958453 :   return q;
    2697             : }
    2698             : 
    2699             : void
    2700           0 : fill_stack(void)
    2701             : {
    2702           0 :   GEN x = ((GEN)pari_mainstack->bot);
    2703           0 :   while (x < (GEN)avma) *x++ = 0xfefefefeUL;
    2704           0 : }
    2705             : 
    2706             : void
    2707           0 : debug_stack(void)
    2708             : {
    2709           0 :   pari_sp top = pari_mainstack->top, bot = pari_mainstack->bot;
    2710             :   GEN z;
    2711           0 :   err_printf("bot=0x%lx\ttop=0x%lx\tavma=0x%lx\n", bot, top, avma);
    2712           0 :   for (z = ((GEN)top)-1; z >= (GEN)avma; z--)
    2713           0 :     err_printf("%p:\t0x%lx\t%lu\n",z,*z,*z);
    2714           0 : }
    2715             : 
    2716             : void
    2717           0 : setdebugvar(long n) { DEBUGVAR=n; }
    2718             : 
    2719             : long
    2720           0 : getdebugvar(void) { return DEBUGVAR; }
    2721             : 
    2722             : long
    2723           7 : getstack(void) { return pari_mainstack->top-avma; }
    2724             : 
    2725             : /*******************************************************************/
    2726             : /*                                                                 */
    2727             : /*                               timer_delay                             */
    2728             : /*                                                                 */
    2729             : /*******************************************************************/
    2730             : 
    2731             : #if defined(USE_CLOCK_GETTIME)
    2732             : #if defined(_POSIX_THREAD_CPUTIME)
    2733             : static THREAD clockid_t time_type = CLOCK_THREAD_CPUTIME_ID;
    2734             : #else
    2735             : static const THREAD clockid_t time_type = CLOCK_PROCESS_CPUTIME_ID;
    2736             : #endif
    2737             : static void
    2738             : pari_init_timer(void)
    2739             : {
    2740             : #if defined(_POSIX_THREAD_CPUTIME)
    2741             :   time_type = CLOCK_PROCESS_CPUTIME_ID;
    2742             : #endif
    2743             : }
    2744             : 
    2745             : void
    2746             : timer_start(pari_timer *T)
    2747             : {
    2748             :   struct timespec t;
    2749             :   clock_gettime(time_type,&t);
    2750             :   T->us = t.tv_nsec / 1000;
    2751             :   T->s  = t.tv_sec;
    2752             : }
    2753             : #elif defined(USE_GETRUSAGE)
    2754             : #ifdef RUSAGE_THREAD
    2755             : static THREAD int rusage_type = RUSAGE_THREAD;
    2756             : #else
    2757             : static const THREAD int rusage_type = RUSAGE_SELF;
    2758             : #endif /*RUSAGE_THREAD*/
    2759             : static void
    2760        1699 : pari_init_timer(void)
    2761             : {
    2762             : #ifdef RUSAGE_THREAD
    2763        1699 :   rusage_type = RUSAGE_SELF;
    2764             : #endif
    2765        1699 : }
    2766             : 
    2767             : void
    2768      295969 : timer_start(pari_timer *T)
    2769             : {
    2770             :   struct rusage r;
    2771      295969 :   getrusage(rusage_type,&r);
    2772      295970 :   T->us = r.ru_utime.tv_usec;
    2773      295970 :   T->s  = r.ru_utime.tv_sec;
    2774      295970 : }
    2775             : #elif defined(USE_FTIME)
    2776             : 
    2777             : static void
    2778             : pari_init_timer(void) { }
    2779             : 
    2780             : void
    2781             : timer_start(pari_timer *T)
    2782             : {
    2783             :   struct timeb t;
    2784             :   ftime(&t);
    2785             :   T->us = ((long)t.millitm) * 1000;
    2786             :   T->s  = t.time;
    2787             : }
    2788             : 
    2789             : #else
    2790             : 
    2791             : static void
    2792             : _get_time(pari_timer *T, long Ticks, long TickPerSecond)
    2793             : {
    2794             :   T->us = (long) ((Ticks % TickPerSecond) * (1000000. / TickPerSecond));
    2795             :   T->s  = Ticks / TickPerSecond;
    2796             : }
    2797             : 
    2798             : # ifdef USE_TIMES
    2799             : static void
    2800             : pari_init_timer(void) { }
    2801             : 
    2802             : void
    2803             : timer_start(pari_timer *T)
    2804             : {
    2805             : # ifdef _SC_CLK_TCK
    2806             :   long tck = sysconf(_SC_CLK_TCK);
    2807             : # else
    2808             :   long tck = CLK_TCK;
    2809             : # endif
    2810             :   struct tms t; times(&t);
    2811             :   _get_time(T, t.tms_utime, tck);
    2812             : }
    2813             : # elif defined(_WIN32)
    2814             : static void
    2815             : pari_init_timer(void) { }
    2816             : 
    2817             : void
    2818             : timer_start(pari_timer *T)
    2819             : { _get_time(T, win32_timer(), 1000); }
    2820             : # else
    2821             : #  include <time.h>
    2822             : #  ifndef CLOCKS_PER_SEC
    2823             : #   define CLOCKS_PER_SEC 1000000 /* may be false on YOUR system */
    2824             : #  endif
    2825             : static void
    2826             : pari_init_timer(void) { }
    2827             : 
    2828             : void
    2829             : timer_start(pari_timer *T)
    2830             : { _get_time(T, clock(), CLOCKS_PER_SEC); }
    2831             : # endif
    2832             : #endif
    2833             : 
    2834             : /* round microseconds to milliseconds */
    2835             : static long
    2836      170301 : rndus(long x) { return (x + 500) / 1000; }
    2837             : static long
    2838      170301 : timer_aux(pari_timer *T, pari_timer *U, void (*settime)(pari_timer *))
    2839             : {
    2840      170301 :   long s = T->s, us = T->us;
    2841      170301 :   settime(U); return 1000 * (U->s - s) + rndus(U->us - us);
    2842             : }
    2843             : 
    2844             : /* return delay, set timer checkpoint */
    2845             : long
    2846       85972 : timer_delay(pari_timer *T) { return timer_aux(T, T, &timer_start); }
    2847             : /* return delay, don't set checkpoint */
    2848             : long
    2849        1701 : timer_get(pari_timer *T) {pari_timer t; return timer_aux(T, &t, &timer_start);}
    2850             : 
    2851             : static void
    2852           0 : timer_vprintf(pari_timer *T, const char *format, va_list args)
    2853             : {
    2854           0 :   out_puts(pariErr, "Time ");
    2855           0 :   out_vprintf(pariErr, format,args);
    2856           0 :   out_printf(pariErr, ": %ld\n", timer_delay(T));
    2857           0 :   pariErr->flush();
    2858           0 : }
    2859             : void
    2860           0 : timer_printf(pari_timer *T, const char *format, ...)
    2861             : {
    2862           0 :   va_list args; va_start(args, format);
    2863           0 :   timer_vprintf(T, format, args);
    2864           0 :   va_end(args);
    2865           0 : }
    2866             : 
    2867             : long
    2868           0 : timer(void)  { static THREAD pari_timer T; return timer_delay(&T);}
    2869             : long
    2870        3344 : gettime(void)  { static THREAD pari_timer T; return timer_delay(&T);}
    2871             : 
    2872             : static THREAD pari_timer timer2_T, abstimer_T;
    2873             : long
    2874           0 : timer2(void) {  return timer_delay(&timer2_T);}
    2875             : void
    2876           0 : msgtimer(const char *format, ...)
    2877             : {
    2878           0 :   va_list args; va_start(args, format);
    2879           0 :   timer_vprintf(&timer2_T, format, args);
    2880           0 :   va_end(args);
    2881           0 : }
    2882             : long
    2883        1699 : getabstime(void)  { return timer_get(&abstimer_T);}
    2884             : 
    2885             : void
    2886      195189 : walltimer_start(pari_timer *ti)
    2887             : {
    2888             : #if defined(USE_CLOCK_GETTIME)
    2889             :   struct timespec t;
    2890             :   if (!clock_gettime(CLOCK_REALTIME,&t))
    2891             :   { ti->s = t.tv_sec; ti->us = rndus(t.tv_nsec); return; }
    2892             : #elif defined(USE_GETTIMEOFDAY)
    2893             :   struct timeval tv;
    2894      195189 :   if (!gettimeofday(&tv, NULL))
    2895      195189 :   {  ti->s = tv.tv_sec; ti->us = tv.tv_usec; return; }
    2896             : #elif defined(USE_FTIMEFORWALLTIME)
    2897             :   struct timeb tp;
    2898             :   if (!ftime(&tp))
    2899             :   { ti->s = tp.time; ti->us = tp.millitm*1000; return; }
    2900             : #endif
    2901           0 :   timer_start(ti);
    2902             : }
    2903             : /* return delay, set timer checkpoint */
    2904             : long
    2905       82628 : walltimer_delay(pari_timer *T) { return timer_aux(T, T, &walltimer_start); }
    2906             : /* return delay, don't set checkpoint */
    2907             : long
    2908           0 : walltimer_get(pari_timer *T)
    2909             : {
    2910             :   pari_timer t;
    2911           0 :   return timer_aux(T, &t, &walltimer_start);
    2912             : }
    2913             : 
    2914             : static GEN
    2915           0 : timetoi(ulong s, ulong m)
    2916             : {
    2917           0 :   pari_sp av = avma;
    2918           0 :   return gerepileuptoint(av, addiu(muluu(s, 1000), m));
    2919             : }
    2920             : GEN
    2921           0 : getwalltime(void)
    2922             : {
    2923             :   pari_timer ti;
    2924           0 :   walltimer_start(&ti);
    2925           0 :   return timetoi(ti.s, rndus(ti.us));
    2926             : }
    2927             : 
    2928             : /*******************************************************************/
    2929             : /*                                                                 */
    2930             : /*                   FUNCTIONS KNOWN TO THE ANALYZER               */
    2931             : /*                                                                 */
    2932             : /*******************************************************************/
    2933             : 
    2934             : GEN
    2935         119 : setdebug(const char *s, long n)
    2936             : {
    2937         119 :   long i, l = numberof(pari_DEBUGLEVEL_str);
    2938             :   GEN V, V1, V2;
    2939         119 :   if (s)
    2940             :   {
    2941         112 :     if (n > 20)
    2942           0 :       pari_err_DOMAIN("setdebug", "n", ">", utoipos(20), stoi(n));
    2943        1960 :     for (i = 0; i < l; i++)
    2944        1932 :       if (!strcmp(s, pari_DEBUGLEVEL_str[i])) break;
    2945         112 :     if (i == l)
    2946          28 :       pari_err_DOMAIN("setdebug", s, "not a valid",
    2947             :                       strtoGENstr("debug domain"), strtoGENstr(s));
    2948          84 :     if (n >= 0) { *pari_DEBUGLEVEL_ptr[i] = n; return gnil; }
    2949          42 :     return stoi(*pari_DEBUGLEVEL_ptr[i]);
    2950             :   }
    2951           7 :   V = cgetg(3,t_MAT);
    2952           7 :   V1 = gel(V,1) = cgetg(l+1, t_COL);
    2953           7 :   V2 = gel(V,2) = cgetg(l+1, t_COL);
    2954         406 :   for (i = 0; i < l; i++)
    2955             :   {
    2956         399 :     gel(V1, i+1) = strtoGENstr(pari_DEBUGLEVEL_str[i]);
    2957         399 :     gel(V2, i+1) = stoi(*pari_DEBUGLEVEL_ptr[i]);
    2958             :   }
    2959           7 :   return V;
    2960             : }
    2961             : 
    2962             : GEN
    2963           7 : pari_version(void)
    2964             : {
    2965           7 :   const ulong mask = (1UL<<PARI_VERSION_SHIFT) - 1;
    2966           7 :   ulong major, minor, patch, n = paricfg_version_code;
    2967           7 :   patch = n & mask; n >>= PARI_VERSION_SHIFT;
    2968           7 :   minor = n & mask; n >>= PARI_VERSION_SHIFT;
    2969           7 :   major = n;
    2970           7 :   if (*paricfg_vcsversion) {
    2971           7 :     const char *ver = paricfg_vcsversion;
    2972           7 :     const char *s = strchr(ver, '-');
    2973             :     char t[8];
    2974           7 :     const long len = s-ver;
    2975             :     GEN v;
    2976           7 :     if (!s || len > 6) pari_err_BUG("pari_version()"); /* paranoia */
    2977           7 :     memcpy(t, ver, len); t[len] = 0;
    2978           7 :     v = cgetg(6, t_VEC);
    2979           7 :     gel(v,1) = utoi(major);
    2980           7 :     gel(v,2) = utoi(minor);
    2981           7 :     gel(v,3) = utoi(patch);
    2982           7 :     gel(v,4) = stoi( atoi(t) );
    2983           7 :     gel(v,5) = strtoGENstr(s+1);
    2984           7 :     return v;
    2985             :   } else {
    2986           0 :     GEN v = cgetg(4, t_VEC);
    2987           0 :     gel(v,1) = utoi(major);
    2988           0 :     gel(v,2) = utoi(minor);
    2989           0 :     gel(v,3) = utoi(patch);
    2990           0 :     return v;
    2991             :   }
    2992             : }
    2993             : 
    2994             : /* List of GP functions: generated from the description system.
    2995             :  * Format (struct entree) :
    2996             :  *   char *name   : name (under GP).
    2997             :  *   ulong valence: (EpNEW, EpALIAS,EpVAR, EpINSTALL)|EpSTATIC
    2998             :  *   void *value  : For PREDEFINED FUNCTIONS: C function to call.
    2999             :  *                  For USER FUNCTIONS: pointer to defining data (block) =
    3000             :  *                   entree*: NULL, list of entree (arguments), NULL
    3001             :  *                   char*  : function text
    3002             :  *   long menu    : which help section do we belong to
    3003             :  *                   1: Standard monadic or dyadic OPERATORS
    3004             :  *                   2: CONVERSIONS and similar elementary functions
    3005             :  *                   3: functions related to COMBINATORICS
    3006             :  *                   4: TRANSCENDENTAL functions, etc.
    3007             :  *   char *code   : GP prototype, aka Parser Code (see libpari's manual)
    3008             :  *                  if NULL, use valence instead.
    3009             :  *   char *help   : short help text (init to NULL).
    3010             :  *   void *pvalue : push_val history.
    3011             :  *   long arity   : maximum number of arguments.
    3012             :  *   entree *next : next entree (init to NULL, used in hashing code). */
    3013             : #include "init.h"
    3014             : #include "default.h"

Generated by: LCOV version 1.13