-
Notifications
You must be signed in to change notification settings - Fork 17
/
pg_hexedit.c
4071 lines (3682 loc) · 132 KB
/
pg_hexedit.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* pg_hexedit.c - PostgreSQL file dump utility for
* viewing heap (data) and index files in wxHexEditor.
*
* Copyright (c) 2018-2021, Crunchy Data Solutions, Inc.
* Copyright (c) 2017-2018, VMware, Inc.
* Copyright (c) 2002-2010, Red Hat, Inc.
* Copyright (c) 2011-2021, PostgreSQL Global Development Group
*
* This specialized fork of pg_filedump is modified to output XML that can be
* used to annotate pages within the wxHexEditor hex editor.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Original pg_filedump Author: Patrick Macdonald <patrickm@redhat.com>
* pg_hexedit author: Peter Geoghegan <pg@bowt.ie>
*/
#define FRONTEND 1
#include "postgres.h"
#include "common/fe_memutils.h"
/*
* We must #undef frontend because certain headers are not really supposed to
* be included in frontend utilities because they include atomics.h.
*/
#undef FRONTEND
/*
* Define TrapMacro() as a no-op expression on builds that have assertions
* enabled. This is redundant though harmless when building without
* assertions, since the same macro definition happens to be visible there. It
* is only visible there because no-op definitions for all assert-related
* macros happen to be shared by frontend and backend code.
*/
#define TrapMacro(condition, errorType) (true)
#include <time.h>
#include "access/brin_page.h"
#include "access/brin_tuple.h"
#include "access/gin_private.h"
#include "access/gist.h"
#include "access/hash.h"
#include "access/htup.h"
#include "access/htup_details.h"
#include "access/itup.h"
#include "access/nbtree.h"
#include "access/spgist_private.h"
#include "storage/checksum.h"
#include "storage/checksum_impl.h"
#include "utils/pg_crc.h"
#define HEXEDIT_VERSION "0.1"
#define SEQUENCE_MAGIC 0x1717 /* PostgreSQL defined magic number */
#define EOF_ENCOUNTERED (-1) /* Indicator for partial read */
/*
* Postgres 12 removed WITH OIDS support. Preserve on-disk compatibility with
* prior versions, even though they're generally unsupported by us
*/
#define HEAP_HASOID HEAP_HASOID_OLD
/* Postgres 13 renamed BT_OFFSET_MASK. Preserve compatibility. */
#if PG_VERSION_NUM < 130000
#define BT_OFFSET_MASK BT_N_KEYS_OFFSET_MASK
#endif
#define COLOR_FONT_STANDARD "#313739"
#define COLOR_BLACK "#000000"
#define COLOR_BLUE_DARK "#2980B9"
#define COLOR_BLUE_LIGHT "#3498DB"
#define COLOR_BROWN "#97333D"
#define COLOR_GREEN_BRIGHT "#50E964"
#define COLOR_GREEN_DARK "#16A085"
#define COLOR_GREEN_LIGHT "#1ABC9C"
#define COLOR_MAROON "#E96950"
#define COLOR_ORANGE "#FF8C00"
#define COLOR_PINK "#E949D1"
#define COLOR_RED_DARK "#912C21"
#define COLOR_RED_LIGHT "#E74C3C"
#define COLOR_WHITE "#CCD1D1"
#define COLOR_YELLOW_DARK "#F1C40F"
#define COLOR_YELLOW_LIGHT "#E9E850"
typedef enum blockSwitches
{
BLOCK_RANGE = 0x00000020, /* -R: Specific block range to dump */
BLOCK_CHECKSUMS = 0x00000040, /* -k: verify block checksums */
BLOCK_ZEROSUMS = 0x00000080, /* -z: verify block checksums when
* non-zero */
BLOCK_SKIP_LEAF = 0x00000100, /* -l: Skip leaf pages (use whole page
* tag) */
BLOCK_SKIP_LSN = 0x00000200, /* -x: Skip pages before LSN */
BLOCK_DECODE = 0x00000400 /* -D: Decode tuple attributes */
} blockSwitches;
typedef enum segmentSwitches
{
SEGMENT_SIZE_FORCED = 0x00000001, /* -s: Segment size forced */
SEGMENT_NUMBER_FORCED = 0x00000002 /* -n: Segment number forced */
} segmentSwitches;
/* -R[start]:Block range start */
static int blockStart = -1;
/* -R[end]:Block range end */
static int blockEnd = -1;
/* -x:Skip pages whose LSN is before point */
static XLogRecPtr afterThreshold = InvalidXLogRecPtr;
static XLogRecPtr minPageLSN = (XLogRecPtr) PG_UINT64_MAX;
static XLogRecPtr maxPageLSN = InvalidXLogRecPtr;
static BlockNumber minPageLSNBlock = InvalidBlockNumber;
static BlockNumber maxPageLSNBlock = InvalidBlockNumber;
static BlockNumber maxBlockNumber = 0;
static uint32 nblockstagged = 0;
static uint32 nblocksskipped = 0;
/* Possible value types for the Special Section */
typedef enum specialSectionTypes
{
SPEC_SECT_NONE, /* No special section on block */
SPEC_SECT_SEQUENCE, /* Sequence info in special section */
SPEC_SECT_INDEX_BTREE, /* BTree index info in special section */
SPEC_SECT_INDEX_HASH, /* Hash index info in special section */
SPEC_SECT_INDEX_GIST, /* GIST index info in special section */
SPEC_SECT_INDEX_GIN, /* GIN index info in special section */
SPEC_SECT_INDEX_SPGIST, /* SP - GIST index info in special section */
SPEC_SECT_INDEX_BRIN, /* BRIN index info in special section */
SPEC_SECT_ERROR_UNKNOWN, /* Unknown error */
SPEC_SECT_ERROR_BOUNDARY /* Boundary error */
} specialSectionTypes;
/* Special section type that was encountered first */
static unsigned int firstType = SPEC_SECT_ERROR_UNKNOWN;
/* Current block special section type */
static unsigned int specialType = SPEC_SECT_NONE;
/*
* Possible return codes from option validation routine.
*
* pg_hexedit doesn't do much with them now but maybe in the future...
*/
typedef enum optionReturnCodes
{
OPT_RC_VALID, /* All options are valid */
OPT_RC_INVALID, /* Improper option string */
OPT_RC_FILE, /* File problems */
OPT_RC_DUPLICATE, /* Duplicate option encountered */
OPT_RC_COPYRIGHT /* Copyright should be displayed */
} optionReturnCodes;
/*
* Simple macro to check for duplicate options and then set an option flag for
* later consumption
*/
#define SET_OPTION(_x,_y,_z) if (_x & _y) \
{ \
rc = OPT_RC_DUPLICATE; \
duplicateSwitch = _z; \
} \
else \
_x |= _y;
/*
* Global variables for ease of use mostly
*/
/* Segment-related options */
static unsigned int segmentOptions = 0;
/* Options for Block formatting operations */
static unsigned int blockOptions = 0;
/* File to dump or format */
static FILE *fp = NULL;
/* File name for display */
static char *fileName = NULL;
/* Cache for current block */
static char *buffer = NULL;
/* Current block size */
static unsigned int blockSize = 0;
/* Current block in file */
static unsigned int currentBlock = 0;
/* Segment size in bytes */
static unsigned int segmentSize = RELSEG_SIZE * BLCKSZ;
/* Relation-relative block offset to beginning of the segment (our file) */
static unsigned int segmentBlockDelta = 0;
/* Number of current segment */
static unsigned int segmentNumber = 0;
/* Current wxHexEditor output tag number */
static unsigned int tagNumber = 0;
/* Offset of current block (in bytes) */
static unsigned int pageOffset = 0;
/* Number of bytes to format */
static unsigned int bytesToFormat = 0;
/* Block version number */
static unsigned int blockVersion = 0;
/* Number of attributes (used when decoding) */
static int nrelatts = 0;
/* attlen catalog metadata for relation (used when decoding) */
static int *attlenrel = NULL;
/* attnamerel catalog metadata for relation (used when decoding) */
static char **attnamerel = NULL;
/* attcolorrel attribute colors for relation (used when decoding) */
static char **attcolorrel = NULL;
/* attalign catalog metadata for relation (used when decoding) */
static char *attalignrel = NULL;
/* Program exit code */
static int exitCode = 0;
typedef enum formatChoice
{
ITEM_HEAP, /* Blocks contain HeapTuple items */
ITEM_INDEX, /* Blocks contain IndexTuple items */
ITEM_SPG_INN, /* Blocks contain SpGistInnerTuple items */
ITEM_SPG_LEAF, /* Blocks contain SpGistLeafTuple items */
ITEM_BRIN /* Blocks contain BrinTuple items */
} formatChoice;
static void DisplayOptions(unsigned int validOptions);
static unsigned int GetSegmentNumberFromFileName(const char *fileName);
static uint32 sdbmhash(const unsigned char *elem, size_t len);
static char *GetColorFromAttrname(const char *attrName);
static unsigned int ConsumeOptions(int numOptions, char **options);
static int GetOptionValue(char *optionString);
static XLogRecPtr GetOptionXlogRecPtr(char *optionString);
static bool ParseAttributeListString(const char *str);
static unsigned int GetBlockSize(void);
static unsigned int GetSpecialSectionType(Page page);
static const char *GetSpecialSectionString(unsigned int type);
static XLogRecPtr GetPageLsn(Page page);
static char *GetHeapTupleHeaderFlags(HeapTupleHeader htup, bool isInfomask2);
static char *GetIndexTupleFlags(IndexTuple itup);
static const char *GetSpGistStateString(unsigned int code);
static char *GetSpGistInnerTupleState(SpGistInnerTuple itup);
static char *GetSpGistLeafTupleState(SpGistLeafTuple itup);
static char *GetBrinTupleFlags(BrinTuple *itup);
static bool IsBrinPage(Page page);
static bool IsHashBitmapPage(Page page);
static bool IsLeafPage(Page page);
static void EmitXmlPage(BlockNumber blkno);
static void EmitXmlDocHeader(int numOptions, char **options);
static void EmitXmlFooter(void);
static void EmitXmlTag(BlockNumber blkno, uint32 level, const char *name,
const char *color, uint32 relfileOff,
uint32 relfileOffEnd);
static void EmitXmlItemId(BlockNumber blkno, OffsetNumber offset,
ItemId itemId, uint32 relfileOff,
const char *textFlags);
static inline void EmitXmlTupleTag(BlockNumber blkno, OffsetNumber offset,
const char *name, const char *color,
uint32 relfileOff, uint32 relfileOffEnd);
static void EmitXmlTupleTagFont(BlockNumber blkno, OffsetNumber offset,
const char *name, const char *color,
const char *fontColor, uint32 relfileOff,
uint32 relfileOffEnd);
static void EmitXmlTupleTagFontTwoName(BlockNumber blkno, OffsetNumber offset,
const char *name1, const char *name2,
const char *color, const char *fontColor,
uint32 relfileOff, uint32 relfileOffEnd);
static void EmitXmlAttributesHeap(BlockNumber blkno, OffsetNumber offset,
uint32 relfileOff, HeapTupleHeader htup,
int itemSize);
static void EmitXmlAttributesIndex(BlockNumber blkno, OffsetNumber offset,
uint32 relfileOff, IndexTuple itup,
uint32 tupHeaderOff, int itemSize);
static void EmitXmlAttributesData(BlockNumber blkno, OffsetNumber offset,
uint32 relfileOff, unsigned char *tupdata,
bits8 *t_bits, int nattrs, int datalen);
static void EmitXmlHeapTuple(BlockNumber blkno, OffsetNumber offset,
HeapTupleHeader htup, uint32 relfileOff,
int itemSize);
static void EmitXmlIndexTuple(Page page, BlockNumber blkno,
OffsetNumber offset, IndexTuple tuple,
uint32 relfileOff, int itemSize, bool dead);
static void EmitXmlSpGistInnerTuple(Page page, BlockNumber blkno,
OffsetNumber offset,
SpGistInnerTuple tuple,
uint32 relfileOff);
static void EmitXmlSpGistLeafTuple(Page page, BlockNumber blkno,
OffsetNumber offset,
SpGistLeafTuple tuple,
uint32 relfileOff);
static void EmitXmlBrinTuple(Page page, BlockNumber blkno,
OffsetNumber offset, BrinTuple *tuple,
uint32 relfileOff, int itemSize);
static int EmitXmlPageHeader(Page page, BlockNumber blkno, uint32 level);
static void EmitXmlPageMeta(BlockNumber blkno, uint32 level);
static void EmitXmlPageItemIdArray(Page page, BlockNumber blkno);
static void EmitXmlTuples(Page page, BlockNumber blkno);
static void EmitXmlPostingTreeTids(Page page, BlockNumber blkno);
static void EmitXmlHashBitmap(Page page, BlockNumber blkno);
static void EmitXmlRevmap(Page page, BlockNumber blkno);
static void EmitXmlSpecial(BlockNumber blkno, uint32 level);
static void EmitXmlBody(void);
/* Send properly formed usage information to the user. */
static void
DisplayOptions(unsigned int validOptions)
{
if (validOptions == OPT_RC_COPYRIGHT)
printf
("pg_hexedit %s (for PostgreSQL %s)"
"\nCopyright (c) 2018-2021, Crunchy Data Solutions, Inc."
"\nCopyright (c) 2017-2018, VMware, Inc."
"\nCopyright (c) 2002-2010, Red Hat, Inc."
"\nCopyright (c) 2011-2021, PostgreSQL Global Development Group\n",
HEXEDIT_VERSION, PG_VERSION);
printf
("\nUsage: pg_hexedit [-hklz] [-D attrlist] [-n segnumber] [-R startblock [endblock]] [-s segsize] [-x lsn] file\n\n"
"Output contents of PostgreSQL relation file as wxHexEditor XML tags\n"
" -D Decode tuples using given comma separated list of attribute metadata\n"
" See README.md for an explanation of the attrlist format\n"
" -h Display this information\n"
" -k Verify all block checksums\n"
" -l Skip leaf pages\n"
" -n Force segment number to [segnumber]\n"
" -R Display specific block ranges within the file (Blocks are\n"
" indexed from 0)\n" " [startblock]: block to start at\n"
" [endblock]: block to end at\n"
" A startblock without an endblock will format the single block\n"
" -s Force segment size to [segsize]\n"
" -x Skip pages whose LSN is before [lsn]\n"
" -z Verify block checksums when non-zero\n"
"\nReport bugs to <pg@bowt.ie>\n");
}
/*
* Determine segment number by segment file name. For instance, if file
* name is /path/to/xxxx.7 procedure returns 7. Default return value is 0.
*/
static unsigned int
GetSegmentNumberFromFileName(const char *fileName)
{
int segnumOffset = strlen(fileName) - 1;
if (segnumOffset < 0)
return 0;
while (isdigit(fileName[segnumOffset]))
{
segnumOffset--;
if (segnumOffset < 0)
return 0;
}
if (fileName[segnumOffset] != '.')
return 0;
return atoi(&fileName[segnumOffset + 1]);
}
/*
* Hash function is taken from sdbm, a public-domain reimplementation of the
* ndbm database library.
*/
static uint32
sdbmhash(const unsigned char *elem, size_t len)
{
uint32 hash = 0;
int i;
for (i = 0; i < len; elem++, i++)
{
hash = (*elem) + (hash << 6) + (hash << 16) - hash;
}
return hash;
}
/*
* Return a cstring of an html color that is a function of attrName argument.
*/
static char *
GetColorFromAttrname(const char *attrName)
{
uint32 hash;
uint8 red;
uint8 green;
uint8 blue;
char *colorStr = pg_malloc(8);
hash = sdbmhash((const unsigned char *) attrName, strlen(attrName) + 1);
/* Use muted pastel shades for user attributes */
red = 150 + ((uint8) hash % 90);
green = 150 + ((uint8) (hash >> 8) % 90);
blue = 150 + ((uint8) (hash >> 16) % 90);
snprintf(colorStr, 8, "#%02X%02X%02X", red, green, blue);
return colorStr;
}
/*
* Iterate through the provided options and set the option flags. An error
* will result in a positive rc and will force a display of the usage
* information. This routine returns enum option ReturnCode values.
*/
static unsigned int
ConsumeOptions(int numOptions, char **options)
{
unsigned int rc = OPT_RC_VALID;
unsigned int x;
unsigned int optionStringLength;
char *optionString;
char duplicateSwitch = 0x00;
for (x = 1; x < numOptions; x++)
{
optionString = options[x];
optionStringLength = strlen(optionString);
/*
* Range is a special case where we have to consume the next 1 or 2
* parameters to mark the range start and end
*/
if ((optionStringLength == 2) && (strcmp(optionString, "-R") == 0))
{
int range = 0;
SET_OPTION(blockOptions, BLOCK_RANGE, 'R');
/* Only accept the range option once */
if (rc == OPT_RC_DUPLICATE)
break;
/* Make sure there are options after the range identifier */
if (x >= (numOptions - 2))
{
rc = OPT_RC_INVALID;
fprintf(stderr, "pg_hexedit error: missing range start identifier\n");
exitCode = 1;
break;
}
/*
* Mark that we have the range and advance the option to what
* should be the range start. Check the value of the next
* parameter.
*/
optionString = options[++x];
if ((range = GetOptionValue(optionString)) < 0)
{
rc = OPT_RC_INVALID;
fprintf(stderr, "pg_hexedit error: invalid range start identifier \"%s\"\n",
optionString);
exitCode = 1;
break;
}
/* The default is to dump only one block */
blockStart = blockEnd = (unsigned int) range;
/*
* We have our range start marker, check if there is an end marker
* on the option line. Assume that the last option is the file we
* are dumping, so check if there are options range start marker
* and the file.
*/
if (x <= (numOptions - 3))
{
if ((range = GetOptionValue(options[x + 1])) >= 0)
{
/* End range must be => start range */
if (blockStart <= range)
{
blockEnd = (unsigned int) range;
x++;
}
else
{
rc = OPT_RC_INVALID;
fprintf(stderr, "pg_hexedit error: requested block range start %d is greater than end %d\n",
blockStart, range);
exitCode = 1;
break;
}
}
}
}
/* Check for the special case where the user requires tuple decoding */
else if ((optionStringLength == 2)
&& (strcmp(optionString, "-D") == 0))
{
SET_OPTION(blockOptions, BLOCK_DECODE, 'D');
/* Only accept the decode option once */
if (rc == OPT_RC_DUPLICATE)
break;
/*
* The string immediately following -D is a list of attlen,
* attname, and attalign tokens separated by commas. There is one
* set of each per attribute (i.e. there should be three times as
* many entries in the list as there are user attributes in the
* relation).
*/
if (x >= (numOptions - 2))
{
rc = OPT_RC_INVALID;
fprintf(stderr, "pg_hexedit error: missing attrlist string\n");
exitCode = 1;
break;
}
/* Next option encountered must be attribute metadata string */
optionString = options[++x];
if (!ParseAttributeListString(optionString))
{
/* Give details of problem in ParseAttributeListString() */
rc = OPT_RC_INVALID;
fprintf(stderr, "invalid attrlist string %s\n",
optionString);
exitCode = 1;
break;
}
}
/*
* Check for the special case where the user only requires tags for
* pages whose LSN equals or exceeds a supplied threshold.
*/
else if ((optionStringLength == 2) && (strcmp(optionString, "-x") == 0))
{
SET_OPTION(blockOptions, BLOCK_SKIP_LSN, 'x');
/* Only accept the LSN option once */
if (rc == OPT_RC_DUPLICATE)
break;
/* Make sure that there is an LSN option */
if (x >= (numOptions - 2))
{
rc = OPT_RC_INVALID;
fprintf(stderr, "pg_hexedit error: missing LSN\n");
exitCode = 1;
break;
}
/*
* Mark that we have the LSN and advance the option to what should
* be the LSN argument. Check the value of the next parameter.
*/
optionString = options[++x];
if ((afterThreshold = GetOptionXlogRecPtr(optionString)) == InvalidXLogRecPtr)
{
rc = OPT_RC_INVALID;
fprintf(stderr, "pg_hexedit error: invalid LSN identifier \"%s\"\n",
optionString);
exitCode = 1;
break;
}
}
/* Check for the special case where the user forces a segment size. */
else if ((optionStringLength == 2)
&& (strcmp(optionString, "-s") == 0))
{
int localSegmentSize;
SET_OPTION(segmentOptions, SEGMENT_SIZE_FORCED, 's');
/* Only accept the forced size option once */
if (rc == OPT_RC_DUPLICATE)
break;
/* The token immediately following -s is the segment size */
if (x >= (numOptions - 2))
{
rc = OPT_RC_INVALID;
fprintf(stderr, "pg_hexedit error: missing segment size identifier\n");
exitCode = 1;
break;
}
/* Next option encountered must be forced segment size */
optionString = options[++x];
if ((localSegmentSize = GetOptionValue(optionString)) > 0)
segmentSize = (unsigned int) localSegmentSize;
else
{
rc = OPT_RC_INVALID;
fprintf(stderr, "pg_hexedit error: invalid segment size requested \"%s\"\n",
optionString);
exitCode = 1;
break;
}
}
/*
* Check for the special case where the user forces a segment number
* instead of having the tool determine it by file name.
*/
else if ((optionStringLength == 2)
&& (strcmp(optionString, "-n") == 0))
{
int localSegmentNumber;
SET_OPTION(segmentOptions, SEGMENT_NUMBER_FORCED, 'n');
/* Only accept the forced segment number option once */
if (rc == OPT_RC_DUPLICATE)
break;
/* The token immediately following -n is the segment number */
if (x >= (numOptions - 2))
{
rc = OPT_RC_INVALID;
fprintf(stderr, "pg_hexedit error: missing segment number identifier\n");
exitCode = 1;
break;
}
/* Next option encountered must be forced segment number */
optionString = options[++x];
if ((localSegmentNumber = GetOptionValue(optionString)) > 0)
segmentNumber = (unsigned int) localSegmentNumber;
else
{
rc = OPT_RC_INVALID;
fprintf(stderr, "pg_hexedit error: invalid segment number requested \"%s\"\n",
optionString);
exitCode = 1;
break;
}
}
/* The last option MUST be the file name */
else if (x == (numOptions - 1))
{
/* Check to see if this looks like an option string before opening */
if (optionString[0] != '-')
{
fp = fopen(optionString, "rb");
if (fp)
{
fileName = options[x];
if (!(segmentOptions & SEGMENT_NUMBER_FORCED))
segmentNumber = GetSegmentNumberFromFileName(fileName);
}
else
{
rc = OPT_RC_FILE;
fprintf(stderr, "pg_hexedit error: could not open file \"%s\"\n",
optionString);
exitCode = 1;
break;
}
}
else
{
/*
* Could be the case where the help flag is used without a
* filename. Otherwise, the last option isn't a file
*/
if (strcmp(optionString, "-h") == 0)
rc = OPT_RC_COPYRIGHT;
else
{
rc = OPT_RC_FILE;
fprintf(stderr, "pg_hexedit error: missing file name to dump\n");
exitCode = 1;
}
break;
}
}
else
{
unsigned int y;
/* Option strings must start with '-' and contain switches */
if (optionString[0] != '-')
{
rc = OPT_RC_INVALID;
fprintf(stderr, "pg_hexedit error: invalid option string \"%s\"\n",
optionString);
exitCode = 1;
break;
}
/*
* Iterate through the singular option string, throw out garbage,
* duplicates and set flags to be used in formatting
*/
for (y = 1; y < optionStringLength; y++)
{
switch (optionString[y])
{
/* Display the usage screen */
case 'h':
rc = OPT_RC_COPYRIGHT;
break;
/* Verify all block checksums */
case 'k':
SET_OPTION(blockOptions, BLOCK_CHECKSUMS, 'k');
break;
/* Verify block checksums when non-zero */
case 'z':
SET_OPTION(blockOptions, BLOCK_ZEROSUMS, 'z');
break;
/* Skip non-root leaf pages */
case 'l':
SET_OPTION(blockOptions, BLOCK_SKIP_LEAF, 'l');
break;
default:
rc = OPT_RC_INVALID;
fprintf(stderr, "pg_hexedit error: unknown option '%c'\n",
optionString[y]);
exitCode = 1;
break;
}
if (rc)
break;
}
}
}
if (rc == OPT_RC_DUPLICATE)
{
fprintf(stderr, "pg_hexedit error: duplicate option listed '%c'\n",
duplicateSwitch);
exitCode = 1;
}
return (rc);
}
/*
* Given the index into the parameter list, convert and return the current
* string to a number if possible
*/
static int
GetOptionValue(char *optionString)
{
unsigned int x;
int value = -1;
int optionStringLength = strlen(optionString);
/* Verify the next option looks like a number */
for (x = 0; x < optionStringLength; x++)
{
if (!isdigit((int) optionString[x]))
break;
}
/* Convert the string to a number if it looks good */
if (x == optionStringLength)
value = atoi(optionString);
return value;
}
/*
* Given an alphanumeric LSN, convert and return it to an XLogRecPtr if
* possible
*/
static XLogRecPtr
GetOptionXlogRecPtr(char *optionString)
{
uint32 xlogid;
uint32 xrecoff;
XLogRecPtr value = InvalidXLogRecPtr;
if (sscanf(optionString, "%X/%X", &xlogid, &xrecoff) == 2)
value = (uint64) xlogid << 32 | xrecoff;
return value;
}
/*
* Given an attrlist string (pg_hexedit -D argument string), deserialize into
* data structures used by tuple decoding to create per-tuple, per-attribute
* tags.
*
* Returns false on failure, allowing caller to set exitCode and print
* supplemental information common to all parse failures.
*/
static bool
ParseAttributeListString(const char *arg)
{
char *attrlist;
int lennamealign;
char *curropt;
char *nextopt;
/* Allocate space for decoding state */
attlenrel = pg_malloc(sizeof(int) * MaxTupleAttributeNumber);
attnamerel = pg_malloc(sizeof(char *) * MaxTupleAttributeNumber);
attcolorrel = pg_malloc(sizeof(char *) * MaxTupleAttributeNumber);
attalignrel = pg_malloc(sizeof(char) * MaxTupleAttributeNumber);
/* Create copy of argument string to scribble on */
attrlist = pg_strdup(arg);
nrelatts = 0;
lennamealign = 0;
curropt = attrlist;
while (curropt)
{
if (*curropt == '"')
{
/* Move past leading " character, omitting it */
curropt++;
/* Find terminating " character, skipping any contained ',' char */
nextopt = strchr(curropt, '"');
if (!nextopt)
return false;
/* Eliminate trailing " character from current option */
*nextopt = '\0';
/* Prepare next option */
nextopt++;
nextopt = strchr(nextopt, ',');
}
else
nextopt = strchr(curropt, ',');
if (nextopt)
{
/* Eliminate , character from current option */
*nextopt = '\0';
nextopt++;
}
if (lennamealign == 0)
{
int attlen;
if (sscanf(curropt, "%d", &attlen) != 1)
{
fprintf(stderr, "pg_hexedit error: could not parse attlen from attrlist argument\n");
return false;
}
attlenrel[nrelatts] = attlen;
/* Prepare for next item */
lennamealign++;
}
else if (lennamealign == 1)
{
/*
* Copy attribute name, and dynamically generate color for
* attribute
*/
attnamerel[nrelatts] = pg_strdup(curropt);
attcolorrel[nrelatts] = GetColorFromAttrname(curropt);
/* Prepare for next item */
lennamealign++;
}
else
{
char attalign = *curropt;
if (attalign != 'i' && attalign != 'c' && attalign != 'd' &&
attalign != 's')
{
fprintf(stderr, "pg_hexedit error: invalid attalign value '%c' in attrlist argument\n",
attalign);
return false;
}
if (attlenrel[nrelatts] == -2 && attalign != 'c')
{
fprintf(stderr, "pg_hexedit error: unexpected attalign '%c' for cstring in attrlist argument\n",
attalign);
return false;
}
attalignrel[nrelatts] = attalign;
/* Prepare for next item, and next attribute in "descriptor" */
if (nrelatts >= MaxTupleAttributeNumber)
{
fprintf(stderr, "pg_hexedit error: too many attributes represented in attrlist argument\n");
return false;
}
lennamealign = 0;
nrelatts++;
}
curropt = nextopt;
}
/* Be tidy */
pg_free(attrlist);
/*
* Should be at least one attribute, and should have attlen, attname, and
* attalign for each attribute
*/
return nrelatts > 0 && lennamealign == 0;
}
/*
* Read the page header off of block 0 to determine the block size used in this
* file. Can be overridden using the -s option. The returned value is the
* block size of block 0 on disk. If a valid page size could not be read,
* assumes BLCKSZ.
*/
static unsigned int
GetBlockSize(void)
{
unsigned int pageHeaderSize = sizeof(PageHeaderData);
unsigned int localSize = BLCKSZ;
int bytesRead = 0;
char localCache[sizeof(PageHeaderData)];
/* Read the first header off of block 0 to determine the block size */
bytesRead = fread(&localCache, 1, pageHeaderSize, fp);
rewind(fp);
if (bytesRead == pageHeaderSize)
localSize = (unsigned int) PageGetPageSize((Page) &localCache);
else
{
fprintf(stderr, "pg_hexedit error: unable to read full page header from first block\n"
"read %u bytes\n", bytesRead);
exitCode = 1;
}
if (localSize == 0 || ((localSize - 1) & localSize) != 0)
{
fprintf(stderr, "pg_hexedit error: invalid block size %u encountered in first block\n",
localSize);
exitCode = 1;
localSize = BLCKSZ;
}
return localSize;
}
/*
* Determine the LSN of page as an XLogRecPtr
*/
static XLogRecPtr
GetPageLsn(Page page)
{
PageHeader pageHeader = (PageHeader) page;
return PageXLogRecPtrGet(pageHeader->pd_lsn);
}
/*
* Determine the contents of the special section on the block and return this
* enum value
*/
static unsigned int
GetSpecialSectionType(Page page)
{
unsigned int rc;
unsigned int specialOffset;
unsigned int specialSize;
unsigned int specialValue;
PageHeader pageHeader = (PageHeader) page;
/*
* If this is not a partial header, check the validity of the special
* section offset and contents
*/
if (bytesToFormat > sizeof(PageHeaderData))
{
specialOffset = (unsigned int) pageHeader->pd_special;
/*
* Check that the special offset can remain on the block or the
* partial block
*/
if ((specialOffset == 0) ||
(specialOffset > blockSize) || (specialOffset > bytesToFormat))
rc = SPEC_SECT_ERROR_BOUNDARY;
else