OSDN Git Service

3ffff2a2cce3fe0ee2bb50fd079a758bcf2b747b
[pg-rex/syncrep.git] / src / backend / bootstrap / bootstrap.c
1 /*-------------------------------------------------------------------------
2  *
3  * bootstrap.c
4  *        routines to support running postgres in 'bootstrap' mode
5  *      bootstrap mode is used to create the initial template database
6  *
7  * Portions Copyright (c) 1996-2007, PostgreSQL Global Development Group
8  * Portions Copyright (c) 1994, Regents of the University of California
9  *
10  * IDENTIFICATION
11  *        $PostgreSQL: pgsql/src/backend/bootstrap/bootstrap.c,v 1.235 2007/07/24 04:54:09 tgl Exp $
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16
17 #include <unistd.h>
18 #include <signal.h>
19 #ifdef HAVE_GETOPT_H
20 #include <getopt.h>
21 #endif
22
23 #include "access/genam.h"
24 #include "access/heapam.h"
25 #include "access/xact.h"
26 #include "bootstrap/bootstrap.h"
27 #include "catalog/index.h"
28 #include "catalog/pg_type.h"
29 #include "libpq/pqsignal.h"
30 #include "miscadmin.h"
31 #include "nodes/makefuncs.h"
32 #include "postmaster/bgwriter.h"
33 #include "postmaster/walwriter.h"
34 #include "storage/freespace.h"
35 #include "storage/ipc.h"
36 #include "storage/proc.h"
37 #include "tcop/tcopprot.h"
38 #include "utils/builtins.h"
39 #include "utils/flatfiles.h"
40 #include "utils/fmgroids.h"
41 #include "utils/memutils.h"
42 #include "utils/ps_status.h"
43
44 extern int      optind;
45 extern char *optarg;
46
47
48 #define ALLOC(t, c)             ((t *) calloc((unsigned)(c), sizeof(t)))
49
50 static void CheckerModeMain(void);
51 static void BootstrapModeMain(void);
52 static void bootstrap_signals(void);
53 static void ShutdownAuxiliaryProcess(int code, Datum arg);
54 static hashnode *AddStr(char *str, int strlength, int mderef);
55 static Form_pg_attribute AllocateAttribute(void);
56 static int      CompHash(char *str, int len);
57 static hashnode *FindStr(char *str, int length, hashnode *mderef);
58 static Oid      gettype(char *type);
59 static void cleanup(void);
60
61 /* ----------------
62  *              global variables
63  * ----------------
64  */
65
66 Relation        boot_reldesc;           /* current relation descriptor */
67
68 /*
69  * In the lexical analyzer, we need to get the reference number quickly from
70  * the string, and the string from the reference number.  Thus we have
71  * as our data structure a hash table, where the hashing key taken from
72  * the particular string.  The hash table is chained.  One of the fields
73  * of the hash table node is an index into the array of character pointers.
74  * The unique index number that every string is assigned is simply the
75  * position of its string pointer in the array of string pointers.
76  */
77
78 #define STRTABLESIZE    10000
79 #define HASHTABLESIZE   503
80
81 /* Hash function numbers */
82 #define NUM             23
83 #define NUMSQR  529
84 #define NUMCUBE 12167
85
86 char       *strtable[STRTABLESIZE];
87 hashnode   *hashtable[HASHTABLESIZE];
88
89 static int      strtable_end = -1;      /* Tells us last occupied string space */
90
91 /*-
92  * Basic information associated with each type.  This is used before
93  * pg_type is created.
94  *
95  *              XXX several of these input/output functions do catalog scans
96  *                      (e.g., F_REGPROCIN scans pg_proc).      this obviously creates some
97  *                      order dependencies in the catalog creation process.
98  */
99 struct typinfo
100 {
101         char            name[NAMEDATALEN];
102         Oid                     oid;
103         Oid                     elem;
104         int16           len;
105         bool            byval;
106         char            align;
107         char            storage;
108         Oid                     inproc;
109         Oid                     outproc;
110 };
111
112 static const struct typinfo TypInfo[] = {
113         {"bool", BOOLOID, 0, 1, true, 'c', 'p',
114         F_BOOLIN, F_BOOLOUT},
115         {"bytea", BYTEAOID, 0, -1, false, 'i', 'x',
116         F_BYTEAIN, F_BYTEAOUT},
117         {"char", CHAROID, 0, 1, true, 'c', 'p',
118         F_CHARIN, F_CHAROUT},
119         {"int2", INT2OID, 0, 2, true, 's', 'p',
120         F_INT2IN, F_INT2OUT},
121         {"int4", INT4OID, 0, 4, true, 'i', 'p',
122         F_INT4IN, F_INT4OUT},
123         {"float4", FLOAT4OID, 0, 4, false, 'i', 'p',
124         F_FLOAT4IN, F_FLOAT4OUT},
125         {"name", NAMEOID, CHAROID, NAMEDATALEN, false, 'i', 'p',
126         F_NAMEIN, F_NAMEOUT},
127         {"regclass", REGCLASSOID, 0, 4, true, 'i', 'p',
128         F_REGCLASSIN, F_REGCLASSOUT},
129         {"regproc", REGPROCOID, 0, 4, true, 'i', 'p',
130         F_REGPROCIN, F_REGPROCOUT},
131         {"regtype", REGTYPEOID, 0, 4, true, 'i', 'p',
132         F_REGTYPEIN, F_REGTYPEOUT},
133         {"text", TEXTOID, 0, -1, false, 'i', 'x',
134         F_TEXTIN, F_TEXTOUT},
135         {"oid", OIDOID, 0, 4, true, 'i', 'p',
136         F_OIDIN, F_OIDOUT},
137         {"tid", TIDOID, 0, 6, false, 's', 'p',
138         F_TIDIN, F_TIDOUT},
139         {"xid", XIDOID, 0, 4, true, 'i', 'p',
140         F_XIDIN, F_XIDOUT},
141         {"cid", CIDOID, 0, 4, true, 'i', 'p',
142         F_CIDIN, F_CIDOUT},
143         {"int2vector", INT2VECTOROID, INT2OID, -1, false, 'i', 'p',
144         F_INT2VECTORIN, F_INT2VECTOROUT},
145         {"oidvector", OIDVECTOROID, OIDOID, -1, false, 'i', 'p',
146         F_OIDVECTORIN, F_OIDVECTOROUT},
147         {"_int4", INT4ARRAYOID, INT4OID, -1, false, 'i', 'x',
148         F_ARRAY_IN, F_ARRAY_OUT},
149         {"_text", 1009, TEXTOID, -1, false, 'i', 'x',
150         F_ARRAY_IN, F_ARRAY_OUT},
151         {"_oid", 1028, OIDOID, -1, false, 'i', 'x',
152         F_ARRAY_IN, F_ARRAY_OUT},
153         {"_char", 1002, CHAROID, -1, false, 'i', 'x',
154         F_ARRAY_IN, F_ARRAY_OUT},
155         {"_aclitem", 1034, ACLITEMOID, -1, false, 'i', 'x',
156         F_ARRAY_IN, F_ARRAY_OUT}
157 };
158
159 static const int n_types = sizeof(TypInfo) / sizeof(struct typinfo);
160
161 struct typmap
162 {                                                               /* a hack */
163         Oid                     am_oid;
164         FormData_pg_type am_typ;
165 };
166
167 static struct typmap **Typ = NULL;
168 static struct typmap *Ap = NULL;
169
170 static char Blanks[MAXATTR];
171
172 Form_pg_attribute attrtypes[MAXATTR];   /* points to attribute info */
173 static Datum values[MAXATTR];   /* corresponding attribute values */
174 int                     numattr;                        /* number of attributes for cur. rel */
175
176 static MemoryContext nogc = NULL;               /* special no-gc mem context */
177
178 /*
179  *      At bootstrap time, we first declare all the indices to be built, and
180  *      then build them.  The IndexList structure stores enough information
181  *      to allow us to build the indices after they've been declared.
182  */
183
184 typedef struct _IndexList
185 {
186         Oid                     il_heap;
187         Oid                     il_ind;
188         IndexInfo  *il_info;
189         struct _IndexList *il_next;
190 } IndexList;
191
192 static IndexList *ILHead = NULL;
193
194
195 /*
196  *       AuxiliaryProcessMain
197  *
198  *       The main entry point for auxiliary processes, such as the bgwriter,
199  *       walwriter, bootstrapper and the shared memory checker code.
200  *
201  *       This code is here just because of historical reasons.
202  */
203 void
204 AuxiliaryProcessMain(int argc, char *argv[])
205 {
206         char       *progname = argv[0];
207         int                     flag;
208         AuxProcType     auxType = CheckerProcess;
209         char       *userDoption = NULL;
210
211         /*
212          * initialize globals
213          */
214         MyProcPid = getpid();
215
216         /*
217          * Fire up essential subsystems: error and memory management
218          *
219          * If we are running under the postmaster, this is done already.
220          */
221         if (!IsUnderPostmaster)
222                 MemoryContextInit();
223
224         /* Compute paths, if we didn't inherit them from postmaster */
225         if (my_exec_path[0] == '\0')
226         {
227                 if (find_my_exec(progname, my_exec_path) < 0)
228                         elog(FATAL, "%s: could not locate my own executable path",
229                                  progname);
230         }
231
232         /*
233          * process command arguments
234          */
235
236         /* Set defaults, to be overriden by explicit options below */
237         if (!IsUnderPostmaster)
238                 InitializeGUCOptions();
239
240         /* Ignore the initial --boot argument, if present */
241         if (argc > 1 && strcmp(argv[1], "--boot") == 0)
242         {
243                 argv++;
244                 argc--;
245         }
246
247         while ((flag = getopt(argc, argv, "B:c:d:D:Fr:x:-:")) != -1)
248         {
249                 switch (flag)
250                 {
251                         case 'B':
252                                 SetConfigOption("shared_buffers", optarg, PGC_POSTMASTER, PGC_S_ARGV);
253                                 break;
254                         case 'D':
255                                 userDoption = optarg;
256                                 break;
257                         case 'd':
258                                 {
259                                         /* Turn on debugging for the bootstrap process. */
260                                         char       *debugstr = palloc(strlen("debug") + strlen(optarg) + 1);
261
262                                         sprintf(debugstr, "debug%s", optarg);
263                                         SetConfigOption("log_min_messages", debugstr,
264                                                                         PGC_POSTMASTER, PGC_S_ARGV);
265                                         SetConfigOption("client_min_messages", debugstr,
266                                                                         PGC_POSTMASTER, PGC_S_ARGV);
267                                         pfree(debugstr);
268                                 }
269                                 break;
270                         case 'F':
271                                 SetConfigOption("fsync", "false", PGC_POSTMASTER, PGC_S_ARGV);
272                                 break;
273                         case 'r':
274                                 strlcpy(OutputFileName, optarg, MAXPGPATH);
275                                 break;
276                         case 'x':
277                                 auxType = atoi(optarg);
278                                 break;
279                         case 'c':
280                         case '-':
281                                 {
282                                         char       *name,
283                                                            *value;
284
285                                         ParseLongOption(optarg, &name, &value);
286                                         if (!value)
287                                         {
288                                                 if (flag == '-')
289                                                         ereport(ERROR,
290                                                                         (errcode(ERRCODE_SYNTAX_ERROR),
291                                                                          errmsg("--%s requires a value",
292                                                                                         optarg)));
293                                                 else
294                                                         ereport(ERROR,
295                                                                         (errcode(ERRCODE_SYNTAX_ERROR),
296                                                                          errmsg("-c %s requires a value",
297                                                                                         optarg)));
298                                         }
299
300                                         SetConfigOption(name, value, PGC_POSTMASTER, PGC_S_ARGV);
301                                         free(name);
302                                         if (value)
303                                                 free(value);
304                                         break;
305                                 }
306                         default:
307                                 write_stderr("Try \"%s --help\" for more information.\n",
308                                                          progname);
309                                 proc_exit(1);
310                                 break;
311                 }
312         }
313
314         if (argc != optind)
315         {
316                 write_stderr("%s: invalid command-line arguments\n", progname);
317                 proc_exit(1);
318         }
319
320         /*
321          * Identify myself via ps
322          */
323         if (IsUnderPostmaster)
324         {
325                 const char *statmsg;
326
327                 switch (auxType)
328                 {
329                         case StartupProcess:
330                                 statmsg = "startup process";
331                                 break;
332                         case BgWriterProcess:
333                                 statmsg = "writer process";
334                                 break;
335                         case WalWriterProcess:
336                                 statmsg = "wal writer process";
337                                 break;
338                         default:
339                                 statmsg = "??? process";
340                                 break;
341                 }
342                 init_ps_display(statmsg, "", "", "");
343         }
344
345         /* Acquire configuration parameters, unless inherited from postmaster */
346         if (!IsUnderPostmaster)
347         {
348                 if (!SelectConfigFiles(userDoption, progname))
349                         proc_exit(1);
350                 /* If timezone is not set, determine what the OS uses */
351                 pg_timezone_initialize();
352                 /* If timezone_abbreviations is not set, select default */
353                 pg_timezone_abbrev_initialize();
354         }
355
356         /* Validate we have been given a reasonable-looking DataDir */
357         Assert(DataDir);
358         ValidatePgVersion(DataDir);
359
360         /* Change into DataDir (if under postmaster, should be done already) */
361         if (!IsUnderPostmaster)
362                 ChangeToDataDir();
363
364         /* If standalone, create lockfile for data directory */
365         if (!IsUnderPostmaster)
366                 CreateDataDirLockFile(false);
367
368         SetProcessingMode(BootstrapProcessing);
369         IgnoreSystemIndexes = true;
370
371         BaseInit();
372
373         /*
374          * When we are an auxiliary process, we aren't going to do the full
375          * InitPostgres pushups, but there are a couple of things that need to get
376          * lit up even in an auxiliary process.
377          */
378         if (IsUnderPostmaster)
379         {
380                 /*
381                  * Create a PGPROC so we can use LWLocks.  In the EXEC_BACKEND case,
382                  * this was already done by SubPostmasterMain().
383                  */
384 #ifndef EXEC_BACKEND
385                 InitAuxiliaryProcess();
386 #endif
387
388                 /* finish setting up bufmgr.c */
389                 InitBufferPoolBackend();
390
391                 /* register a shutdown callback for LWLock cleanup */
392                 on_shmem_exit(ShutdownAuxiliaryProcess, 0);
393         }
394
395         /*
396          * XLOG operations
397          */
398         SetProcessingMode(NormalProcessing);
399
400         switch (auxType)
401         {
402                 case CheckerProcess:
403                         bootstrap_signals();
404                         CheckerModeMain();
405                         proc_exit(1);           /* should never return */
406
407                 case BootstrapProcess:
408                         bootstrap_signals();
409                         BootStrapXLOG();
410                         StartupXLOG();
411                         BootstrapModeMain();
412                         proc_exit(1);           /* should never return */
413
414                 case StartupProcess:
415                         bootstrap_signals();
416                         StartupXLOG();
417                         LoadFreeSpaceMap();
418                         BuildFlatFiles(false);
419                         proc_exit(0);           /* startup done */
420
421                 case BgWriterProcess:
422                         /* don't set signals, bgwriter has its own agenda */
423                         InitXLOGAccess();
424                         BackgroundWriterMain();
425                         proc_exit(1);           /* should never return */
426
427                 case WalWriterProcess:
428                         /* don't set signals, walwriter has its own agenda */
429                         InitXLOGAccess();
430                         WalWriterMain();
431                         proc_exit(1);           /* should never return */
432                         
433                 default:
434                         elog(PANIC, "unrecognized process type: %d", auxType);
435                         proc_exit(1);
436         }
437 }
438
439 /*
440  * In shared memory checker mode, all we really want to do is create shared
441  * memory and semaphores (just to prove we can do it with the current GUC
442  * settings).
443  */
444 static void
445 CheckerModeMain(void)
446 {
447         /*
448          * We must be getting invoked for bootstrap mode
449          */
450         Assert(!IsUnderPostmaster);
451
452         SetProcessingMode(BootstrapProcessing);
453
454         /*
455          * Do backend-like initialization for bootstrap mode
456          */
457         InitProcess();
458         InitPostgres(NULL, InvalidOid, NULL, NULL);
459         proc_exit(0);
460 }
461
462 /*
463  *       The main entry point for running the backend in bootstrap mode
464  *
465  *       The bootstrap mode is used to initialize the template database.
466  *       The bootstrap backend doesn't speak SQL, but instead expects
467  *       commands in a special bootstrap language.
468  */
469 static void
470 BootstrapModeMain(void)
471 {
472         int                     i;
473
474         Assert(!IsUnderPostmaster);
475
476         SetProcessingMode(BootstrapProcessing);
477
478         /*
479          * Do backend-like initialization for bootstrap mode
480          */
481         InitProcess();
482         InitPostgres(NULL, InvalidOid, NULL, NULL);
483
484         /* Initialize stuff for bootstrap-file processing */
485         for (i = 0; i < MAXATTR; i++)
486         {
487                 attrtypes[i] = NULL;
488                 Blanks[i] = ' ';
489         }
490         for (i = 0; i < STRTABLESIZE; ++i)
491                 strtable[i] = NULL;
492         for (i = 0; i < HASHTABLESIZE; ++i)
493                 hashtable[i] = NULL;
494
495         /*
496          * Process bootstrap input.
497          */
498         boot_yyparse();
499
500         /* Perform a checkpoint to ensure everything's down to disk */
501         SetProcessingMode(NormalProcessing);
502         CreateCheckPoint(CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_IMMEDIATE);
503
504         /* Clean up and exit */
505         cleanup();
506         proc_exit(0);
507 }
508
509
510 /* ----------------------------------------------------------------
511  *                                              misc functions
512  * ----------------------------------------------------------------
513  */
514
515 /*
516  * Set up signal handling for a bootstrap process
517  */
518 static void
519 bootstrap_signals(void)
520 {
521         if (IsUnderPostmaster)
522         {
523                 /*
524                  * If possible, make this process a group leader, so that the
525                  * postmaster can signal any child processes too.
526                  */
527 #ifdef HAVE_SETSID
528                 if (setsid() < 0)
529                         elog(FATAL, "setsid() failed: %m");
530 #endif
531
532                 /*
533                  * Properly accept or ignore signals the postmaster might send us
534                  */
535                 pqsignal(SIGHUP, SIG_IGN);
536                 pqsignal(SIGINT, SIG_IGN);              /* ignore query-cancel */
537                 pqsignal(SIGTERM, die);
538                 pqsignal(SIGQUIT, quickdie);
539                 pqsignal(SIGALRM, SIG_IGN);
540                 pqsignal(SIGPIPE, SIG_IGN);
541                 pqsignal(SIGUSR1, SIG_IGN);
542                 pqsignal(SIGUSR2, SIG_IGN);
543
544                 /*
545                  * Reset some signals that are accepted by postmaster but not here
546                  */
547                 pqsignal(SIGCHLD, SIG_DFL);
548                 pqsignal(SIGTTIN, SIG_DFL);
549                 pqsignal(SIGTTOU, SIG_DFL);
550                 pqsignal(SIGCONT, SIG_DFL);
551                 pqsignal(SIGWINCH, SIG_DFL);
552
553                 /*
554                  * Unblock signals (they were blocked when the postmaster forked us)
555                  */
556                 PG_SETMASK(&UnBlockSig);
557         }
558         else
559         {
560                 /* Set up appropriately for interactive use */
561                 pqsignal(SIGHUP, die);
562                 pqsignal(SIGINT, die);
563                 pqsignal(SIGTERM, die);
564                 pqsignal(SIGQUIT, die);
565         }
566 }
567
568 /*
569  * Begin shutdown of an auxiliary process.  This is approximately the equivalent
570  * of ShutdownPostgres() in postinit.c.  We can't run transactions in an
571  * auxiliary process, so most of the work of AbortTransaction() is not needed,
572  * but we do need to make sure we've released any LWLocks we are holding.
573  * (This is only critical during an error exit.)
574  */
575 static void
576 ShutdownAuxiliaryProcess(int code, Datum arg)
577 {
578         LWLockReleaseAll();
579 }
580
581 /* ----------------------------------------------------------------
582  *                              MANUAL BACKEND INTERACTIVE INTERFACE COMMANDS
583  * ----------------------------------------------------------------
584  */
585
586 /* ----------------
587  *              boot_openrel
588  * ----------------
589  */
590 void
591 boot_openrel(char *relname)
592 {
593         int                     i;
594         struct typmap **app;
595         Relation        rel;
596         HeapScanDesc scan;
597         HeapTuple       tup;
598
599         if (strlen(relname) >= NAMEDATALEN)
600                 relname[NAMEDATALEN - 1] = '\0';
601
602         if (Typ == NULL)
603         {
604                 /* We can now load the pg_type data */
605                 rel = heap_open(TypeRelationId, NoLock);
606                 scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
607                 i = 0;
608                 while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
609                         ++i;
610                 heap_endscan(scan);
611                 app = Typ = ALLOC(struct typmap *, i + 1);
612                 while (i-- > 0)
613                         *app++ = ALLOC(struct typmap, 1);
614                 *app = NULL;
615                 scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
616                 app = Typ;
617                 while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
618                 {
619                         (*app)->am_oid = HeapTupleGetOid(tup);
620                         memcpy((char *) &(*app)->am_typ,
621                                    (char *) GETSTRUCT(tup),
622                                    sizeof((*app)->am_typ));
623                         app++;
624                 }
625                 heap_endscan(scan);
626                 heap_close(rel, NoLock);
627         }
628
629         if (boot_reldesc != NULL)
630                 closerel(NULL);
631
632         elog(DEBUG4, "open relation %s, attrsize %d",
633                  relname, (int) ATTRIBUTE_TUPLE_SIZE);
634
635         boot_reldesc = heap_openrv(makeRangeVar(NULL, relname), NoLock);
636         numattr = boot_reldesc->rd_rel->relnatts;
637         for (i = 0; i < numattr; i++)
638         {
639                 if (attrtypes[i] == NULL)
640                         attrtypes[i] = AllocateAttribute();
641                 memmove((char *) attrtypes[i],
642                                 (char *) boot_reldesc->rd_att->attrs[i],
643                                 ATTRIBUTE_TUPLE_SIZE);
644
645                 {
646                         Form_pg_attribute at = attrtypes[i];
647
648                         elog(DEBUG4, "create attribute %d name %s len %d num %d type %u",
649                                  i, NameStr(at->attname), at->attlen, at->attnum,
650                                  at->atttypid);
651                 }
652         }
653 }
654
655 /* ----------------
656  *              closerel
657  * ----------------
658  */
659 void
660 closerel(char *name)
661 {
662         if (name)
663         {
664                 if (boot_reldesc)
665                 {
666                         if (strcmp(RelationGetRelationName(boot_reldesc), name) != 0)
667                                 elog(ERROR, "close of %s when %s was expected",
668                                          name, RelationGetRelationName(boot_reldesc));
669                 }
670                 else
671                         elog(ERROR, "close of %s before any relation was opened",
672                                  name);
673         }
674
675         if (boot_reldesc == NULL)
676                 elog(ERROR, "no open relation to close");
677         else
678         {
679                 elog(DEBUG4, "close relation %s",
680                          RelationGetRelationName(boot_reldesc));
681                 heap_close(boot_reldesc, NoLock);
682                 boot_reldesc = NULL;
683         }
684 }
685
686
687
688 /* ----------------
689  * DEFINEATTR()
690  *
691  * define a <field,type> pair
692  * if there are n fields in a relation to be created, this routine
693  * will be called n times
694  * ----------------
695  */
696 void
697 DefineAttr(char *name, char *type, int attnum)
698 {
699         Oid                     typeoid;
700
701         if (boot_reldesc != NULL)
702         {
703                 elog(WARNING, "no open relations allowed with CREATE command");
704                 closerel(NULL);
705         }
706
707         if (attrtypes[attnum] == NULL)
708                 attrtypes[attnum] = AllocateAttribute();
709         MemSet(attrtypes[attnum], 0, ATTRIBUTE_TUPLE_SIZE);
710
711         namestrcpy(&attrtypes[attnum]->attname, name);
712         elog(DEBUG4, "column %s %s", NameStr(attrtypes[attnum]->attname), type);
713         attrtypes[attnum]->attnum = attnum + 1;         /* fillatt */
714
715         typeoid = gettype(type);
716
717         if (Typ != NULL)
718         {
719                 attrtypes[attnum]->atttypid = Ap->am_oid;
720                 attrtypes[attnum]->attlen = Ap->am_typ.typlen;
721                 attrtypes[attnum]->attbyval = Ap->am_typ.typbyval;
722                 attrtypes[attnum]->attstorage = Ap->am_typ.typstorage;
723                 attrtypes[attnum]->attalign = Ap->am_typ.typalign;
724                 /* if an array type, assume 1-dimensional attribute */
725                 if (Ap->am_typ.typelem != InvalidOid && Ap->am_typ.typlen < 0)
726                         attrtypes[attnum]->attndims = 1;
727                 else
728                         attrtypes[attnum]->attndims = 0;
729         }
730         else
731         {
732                 attrtypes[attnum]->atttypid = TypInfo[typeoid].oid;
733                 attrtypes[attnum]->attlen = TypInfo[typeoid].len;
734                 attrtypes[attnum]->attbyval = TypInfo[typeoid].byval;
735                 attrtypes[attnum]->attstorage = TypInfo[typeoid].storage;
736                 attrtypes[attnum]->attalign = TypInfo[typeoid].align;
737                 /* if an array type, assume 1-dimensional attribute */
738                 if (TypInfo[typeoid].elem != InvalidOid &&
739                         attrtypes[attnum]->attlen < 0)
740                         attrtypes[attnum]->attndims = 1;
741                 else
742                         attrtypes[attnum]->attndims = 0;
743         }
744
745         attrtypes[attnum]->attstattarget = -1;
746         attrtypes[attnum]->attcacheoff = -1;
747         attrtypes[attnum]->atttypmod = -1;
748         attrtypes[attnum]->attislocal = true;
749
750         /*
751          * Mark as "not null" if type is fixed-width and prior columns are too.
752          * This corresponds to case where column can be accessed directly via C
753          * struct declaration.
754          *
755          * oidvector and int2vector are also treated as not-nullable, even though
756          * they are no longer fixed-width.
757          */
758 #define MARKNOTNULL(att) \
759         ((att)->attlen > 0 || \
760          (att)->atttypid == OIDVECTOROID || \
761          (att)->atttypid == INT2VECTOROID)
762
763         if (MARKNOTNULL(attrtypes[attnum]))
764         {
765                 int                     i;
766
767                 for (i = 0; i < attnum; i++)
768                 {
769                         if (!MARKNOTNULL(attrtypes[i]))
770                                 break;
771                 }
772                 if (i == attnum)
773                         attrtypes[attnum]->attnotnull = true;
774         }
775 }
776
777
778 /* ----------------
779  *              InsertOneTuple
780  *
781  * If objectid is not zero, it is a specific OID to assign to the tuple.
782  * Otherwise, an OID will be assigned (if necessary) by heap_insert.
783  * ----------------
784  */
785 void
786 InsertOneTuple(Oid objectid)
787 {
788         HeapTuple       tuple;
789         TupleDesc       tupDesc;
790         int                     i;
791
792         elog(DEBUG4, "inserting row oid %u, %d columns", objectid, numattr);
793
794         tupDesc = CreateTupleDesc(numattr,
795                                                           RelationGetForm(boot_reldesc)->relhasoids,
796                                                           attrtypes);
797         tuple = heap_formtuple(tupDesc, values, Blanks);
798         if (objectid != (Oid) 0)
799                 HeapTupleSetOid(tuple, objectid);
800         pfree(tupDesc);                         /* just free's tupDesc, not the attrtypes */
801
802         simple_heap_insert(boot_reldesc, tuple);
803         heap_freetuple(tuple);
804         elog(DEBUG4, "row inserted");
805
806         /*
807          * Reset blanks for next tuple
808          */
809         for (i = 0; i < numattr; i++)
810                 Blanks[i] = ' ';
811 }
812
813 /* ----------------
814  *              InsertOneValue
815  * ----------------
816  */
817 void
818 InsertOneValue(char *value, int i)
819 {
820         Oid                     typoid;
821         int16           typlen;
822         bool            typbyval;
823         char            typalign;
824         char            typdelim;
825         Oid                     typioparam;
826         Oid                     typinput;
827         Oid                     typoutput;
828         char       *prt;
829
830         AssertArg(i >= 0 || i < MAXATTR);
831
832         elog(DEBUG4, "inserting column %d value \"%s\"", i, value);
833
834         typoid = boot_reldesc->rd_att->attrs[i]->atttypid;
835
836         boot_get_type_io_data(typoid,
837                                                   &typlen, &typbyval, &typalign,
838                                                   &typdelim, &typioparam,
839                                                   &typinput, &typoutput);
840
841         values[i] = OidInputFunctionCall(typinput, value, typioparam, -1);
842         prt = OidOutputFunctionCall(typoutput, values[i]);
843         elog(DEBUG4, "inserted -> %s", prt);
844         pfree(prt);
845 }
846
847 /* ----------------
848  *              InsertOneNull
849  * ----------------
850  */
851 void
852 InsertOneNull(int i)
853 {
854         elog(DEBUG4, "inserting column %d NULL", i);
855         Assert(i >= 0 || i < MAXATTR);
856         values[i] = PointerGetDatum(NULL);
857         Blanks[i] = 'n';
858 }
859
860 /* ----------------
861  *              cleanup
862  * ----------------
863  */
864 static void
865 cleanup(void)
866 {
867         if (boot_reldesc != NULL)
868                 closerel(NULL);
869 }
870
871 /* ----------------
872  *              gettype
873  *
874  * NB: this is really ugly; it will return an integer index into TypInfo[],
875  * and not an OID at all, until the first reference to a type not known in
876  * TypInfo[].  At that point it will read and cache pg_type in the Typ array,
877  * and subsequently return a real OID (and set the global pointer Ap to
878  * point at the found row in Typ).      So caller must check whether Typ is
879  * still NULL to determine what the return value is!
880  * ----------------
881  */
882 static Oid
883 gettype(char *type)
884 {
885         int                     i;
886         Relation        rel;
887         HeapScanDesc scan;
888         HeapTuple       tup;
889         struct typmap **app;
890
891         if (Typ != NULL)
892         {
893                 for (app = Typ; *app != NULL; app++)
894                 {
895                         if (strncmp(NameStr((*app)->am_typ.typname), type, NAMEDATALEN) == 0)
896                         {
897                                 Ap = *app;
898                                 return (*app)->am_oid;
899                         }
900                 }
901         }
902         else
903         {
904                 for (i = 0; i < n_types; i++)
905                 {
906                         if (strncmp(type, TypInfo[i].name, NAMEDATALEN) == 0)
907                                 return i;
908                 }
909                 elog(DEBUG4, "external type: %s", type);
910                 rel = heap_open(TypeRelationId, NoLock);
911                 scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
912                 i = 0;
913                 while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
914                         ++i;
915                 heap_endscan(scan);
916                 app = Typ = ALLOC(struct typmap *, i + 1);
917                 while (i-- > 0)
918                         *app++ = ALLOC(struct typmap, 1);
919                 *app = NULL;
920                 scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
921                 app = Typ;
922                 while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
923                 {
924                         (*app)->am_oid = HeapTupleGetOid(tup);
925                         memmove((char *) &(*app++)->am_typ,
926                                         (char *) GETSTRUCT(tup),
927                                         sizeof((*app)->am_typ));
928                 }
929                 heap_endscan(scan);
930                 heap_close(rel, NoLock);
931                 return gettype(type);
932         }
933         elog(ERROR, "unrecognized type \"%s\"", type);
934         /* not reached, here to make compiler happy */
935         return 0;
936 }
937
938 /* ----------------
939  *              boot_get_type_io_data
940  *
941  * Obtain type I/O information at bootstrap time.  This intentionally has
942  * almost the same API as lsyscache.c's get_type_io_data, except that
943  * we only support obtaining the typinput and typoutput routines, not
944  * the binary I/O routines.  It is exported so that array_in and array_out
945  * can be made to work during early bootstrap.
946  * ----------------
947  */
948 void
949 boot_get_type_io_data(Oid typid,
950                                           int16 *typlen,
951                                           bool *typbyval,
952                                           char *typalign,
953                                           char *typdelim,
954                                           Oid *typioparam,
955                                           Oid *typinput,
956                                           Oid *typoutput)
957 {
958         if (Typ != NULL)
959         {
960                 /* We have the boot-time contents of pg_type, so use it */
961                 struct typmap **app;
962                 struct typmap *ap;
963
964                 app = Typ;
965                 while (*app && (*app)->am_oid != typid)
966                         ++app;
967                 ap = *app;
968                 if (ap == NULL)
969                         elog(ERROR, "type OID %u not found in Typ list", typid);
970
971                 *typlen = ap->am_typ.typlen;
972                 *typbyval = ap->am_typ.typbyval;
973                 *typalign = ap->am_typ.typalign;
974                 *typdelim = ap->am_typ.typdelim;
975
976                 /* XXX this logic must match getTypeIOParam() */
977                 if (OidIsValid(ap->am_typ.typelem))
978                         *typioparam = ap->am_typ.typelem;
979                 else
980                         *typioparam = typid;
981
982                 *typinput = ap->am_typ.typinput;
983                 *typoutput = ap->am_typ.typoutput;
984         }
985         else
986         {
987                 /* We don't have pg_type yet, so use the hard-wired TypInfo array */
988                 int                     typeindex;
989
990                 for (typeindex = 0; typeindex < n_types; typeindex++)
991                 {
992                         if (TypInfo[typeindex].oid == typid)
993                                 break;
994                 }
995                 if (typeindex >= n_types)
996                         elog(ERROR, "type OID %u not found in TypInfo", typid);
997
998                 *typlen = TypInfo[typeindex].len;
999                 *typbyval = TypInfo[typeindex].byval;
1000                 *typalign = TypInfo[typeindex].align;
1001                 /* We assume typdelim is ',' for all boot-time types */
1002                 *typdelim = ',';
1003
1004                 /* XXX this logic must match getTypeIOParam() */
1005                 if (OidIsValid(TypInfo[typeindex].elem))
1006                         *typioparam = TypInfo[typeindex].elem;
1007                 else
1008                         *typioparam = typid;
1009
1010                 *typinput = TypInfo[typeindex].inproc;
1011                 *typoutput = TypInfo[typeindex].outproc;
1012         }
1013 }
1014
1015 /* ----------------
1016  *              AllocateAttribute
1017  * ----------------
1018  */
1019 static Form_pg_attribute
1020 AllocateAttribute(void)
1021 {
1022         Form_pg_attribute attribute = (Form_pg_attribute) malloc(ATTRIBUTE_TUPLE_SIZE);
1023
1024         if (!PointerIsValid(attribute))
1025                 elog(FATAL, "out of memory");
1026         MemSet(attribute, 0, ATTRIBUTE_TUPLE_SIZE);
1027
1028         return attribute;
1029 }
1030
1031 /* ----------------
1032  *              MapArrayTypeName
1033  * XXX arrays of "basetype" are always "_basetype".
1034  *         this is an evil hack inherited from rel. 3.1.
1035  * XXX array dimension is thrown away because we
1036  *         don't support fixed-dimension arrays.  again,
1037  *         sickness from 3.1.
1038  *
1039  * the string passed in must have a '[' character in it
1040  *
1041  * the string returned is a pointer to static storage and should NOT
1042  * be freed by the CALLER.
1043  * ----------------
1044  */
1045 char *
1046 MapArrayTypeName(char *s)
1047 {
1048         int                     i,
1049                                 j;
1050         static char newStr[NAMEDATALEN];        /* array type names < NAMEDATALEN long */
1051
1052         if (s == NULL || s[0] == '\0')
1053                 return s;
1054
1055         j = 1;
1056         newStr[0] = '_';
1057         for (i = 0; i < NAMEDATALEN - 1 && s[i] != '['; i++, j++)
1058                 newStr[j] = s[i];
1059
1060         newStr[j] = '\0';
1061
1062         return newStr;
1063 }
1064
1065 /* ----------------
1066  *              EnterString
1067  *              returns the string table position of the identifier
1068  *              passed to it.  We add it to the table if we can't find it.
1069  * ----------------
1070  */
1071 int
1072 EnterString(char *str)
1073 {
1074         hashnode   *node;
1075         int                     len;
1076
1077         len = strlen(str);
1078
1079         node = FindStr(str, len, NULL);
1080         if (node)
1081                 return node->strnum;
1082         else
1083         {
1084                 node = AddStr(str, len, 0);
1085                 return node->strnum;
1086         }
1087 }
1088
1089 /* ----------------
1090  *              LexIDStr
1091  *              when given an idnum into the 'string-table' return the string
1092  *              associated with the idnum
1093  * ----------------
1094  */
1095 char *
1096 LexIDStr(int ident_num)
1097 {
1098         return strtable[ident_num];
1099 }
1100
1101
1102 /* ----------------
1103  *              CompHash
1104  *
1105  *              Compute a hash function for a given string.  We look at the first,
1106  *              the last, and the middle character of a string to try to get spread
1107  *              the strings out.  The function is rather arbitrary, except that we
1108  *              are mod'ing by a prime number.
1109  * ----------------
1110  */
1111 static int
1112 CompHash(char *str, int len)
1113 {
1114         int                     result;
1115
1116         result = (NUM * str[0] + NUMSQR * str[len - 1] + NUMCUBE * str[(len - 1) / 2]);
1117
1118         return result % HASHTABLESIZE;
1119
1120 }
1121
1122 /* ----------------
1123  *              FindStr
1124  *
1125  *              This routine looks for the specified string in the hash
1126  *              table.  It returns a pointer to the hash node found,
1127  *              or NULL if the string is not in the table.
1128  * ----------------
1129  */
1130 static hashnode *
1131 FindStr(char *str, int length, hashnode *mderef)
1132 {
1133         hashnode   *node;
1134
1135         node = hashtable[CompHash(str, length)];
1136         while (node != NULL)
1137         {
1138                 /*
1139                  * We must differentiate between string constants that might have the
1140                  * same value as a identifier and the identifier itself.
1141                  */
1142                 if (!strcmp(str, strtable[node->strnum]))
1143                 {
1144                         return node;            /* no need to check */
1145                 }
1146                 else
1147                         node = node->next;
1148         }
1149         /* Couldn't find it in the list */
1150         return NULL;
1151 }
1152
1153 /* ----------------
1154  *              AddStr
1155  *
1156  *              This function adds the specified string, along with its associated
1157  *              data, to the hash table and the string table.  We return the node
1158  *              so that the calling routine can find out the unique id that AddStr
1159  *              has assigned to this string.
1160  * ----------------
1161  */
1162 static hashnode *
1163 AddStr(char *str, int strlength, int mderef)
1164 {
1165         hashnode   *temp,
1166                            *trail,
1167                            *newnode;
1168         int                     hashresult;
1169         int                     len;
1170
1171         if (++strtable_end >= STRTABLESIZE)
1172                 elog(FATAL, "bootstrap string table overflow");
1173
1174         /*
1175          * Some of the utilites (eg, define type, create relation) assume that the
1176          * string they're passed is a NAMEDATALEN.  We get array bound read
1177          * violations from purify if we don't allocate at least NAMEDATALEN bytes
1178          * for strings of this sort.  Because we're lazy, we allocate at least
1179          * NAMEDATALEN bytes all the time.
1180          */
1181
1182         if ((len = strlength + 1) < NAMEDATALEN)
1183                 len = NAMEDATALEN;
1184
1185         strtable[strtable_end] = malloc((unsigned) len);
1186         strcpy(strtable[strtable_end], str);
1187
1188         /* Now put a node in the hash table */
1189
1190         newnode = (hashnode *) malloc(sizeof(hashnode) * 1);
1191         newnode->strnum = strtable_end;
1192         newnode->next = NULL;
1193
1194         /* Find out where it goes */
1195
1196         hashresult = CompHash(str, strlength);
1197         if (hashtable[hashresult] == NULL)
1198                 hashtable[hashresult] = newnode;
1199         else
1200         {                                                       /* There is something in the list */
1201                 trail = hashtable[hashresult];
1202                 temp = trail->next;
1203                 while (temp != NULL)
1204                 {
1205                         trail = temp;
1206                         temp = temp->next;
1207                 }
1208                 trail->next = newnode;
1209         }
1210         return newnode;
1211 }
1212
1213
1214
1215 /*
1216  *      index_register() -- record an index that has been set up for building
1217  *                                              later.
1218  *
1219  *              At bootstrap time, we define a bunch of indexes on system catalogs.
1220  *              We postpone actually building the indexes until just before we're
1221  *              finished with initialization, however.  This is because the indexes
1222  *              themselves have catalog entries, and those have to be included in the
1223  *              indexes on those catalogs.      Doing it in two phases is the simplest
1224  *              way of making sure the indexes have the right contents at the end.
1225  */
1226 void
1227 index_register(Oid heap,
1228                            Oid ind,
1229                            IndexInfo *indexInfo)
1230 {
1231         IndexList  *newind;
1232         MemoryContext oldcxt;
1233
1234         /*
1235          * XXX mao 10/31/92 -- don't gc index reldescs, associated info at
1236          * bootstrap time.      we'll declare the indexes now, but want to create them
1237          * later.
1238          */
1239
1240         if (nogc == NULL)
1241                 nogc = AllocSetContextCreate(NULL,
1242                                                                          "BootstrapNoGC",
1243                                                                          ALLOCSET_DEFAULT_MINSIZE,
1244                                                                          ALLOCSET_DEFAULT_INITSIZE,
1245                                                                          ALLOCSET_DEFAULT_MAXSIZE);
1246
1247         oldcxt = MemoryContextSwitchTo(nogc);
1248
1249         newind = (IndexList *) palloc(sizeof(IndexList));
1250         newind->il_heap = heap;
1251         newind->il_ind = ind;
1252         newind->il_info = (IndexInfo *) palloc(sizeof(IndexInfo));
1253
1254         memcpy(newind->il_info, indexInfo, sizeof(IndexInfo));
1255         /* expressions will likely be null, but may as well copy it */
1256         newind->il_info->ii_Expressions = (List *)
1257                 copyObject(indexInfo->ii_Expressions);
1258         newind->il_info->ii_ExpressionsState = NIL;
1259         /* predicate will likely be null, but may as well copy it */
1260         newind->il_info->ii_Predicate = (List *)
1261                 copyObject(indexInfo->ii_Predicate);
1262         newind->il_info->ii_PredicateState = NIL;
1263
1264         newind->il_next = ILHead;
1265         ILHead = newind;
1266
1267         MemoryContextSwitchTo(oldcxt);
1268 }
1269
1270
1271 /*
1272  * build_indices -- fill in all the indexes registered earlier
1273  */
1274 void
1275 build_indices(void)
1276 {
1277         for (; ILHead != NULL; ILHead = ILHead->il_next)
1278         {
1279                 Relation        heap;
1280                 Relation        ind;
1281
1282                 /* need not bother with locks during bootstrap */
1283                 heap = heap_open(ILHead->il_heap, NoLock);
1284                 ind = index_open(ILHead->il_ind, NoLock);
1285
1286                 index_build(heap, ind, ILHead->il_info, false);
1287
1288                 index_close(ind, NoLock);
1289                 heap_close(heap, NoLock);
1290         }
1291 }