Don't try to process junk after a string value as UTF-16.
[hivex.git] / lib / hivex.c
1 /* hivex - Windows Registry "hive" extraction library.
2  * Copyright (C) 2009-2010 Red Hat Inc.
3  * Derived from code by Petter Nordahl-Hagen under a compatible license:
4  *   Copyright (c) 1997-2007 Petter Nordahl-Hagen.
5  * Derived from code by Markus Stephany under a compatible license:
6  *   Copyright (c) 2000-2004, Markus Stephany.
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation;
11  * version 2.1 of the License.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * See file LICENSE for the full license.
19  */
20
21 #include <config.h>
22
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <stdint.h>
26 #include <stddef.h>
27 #include <inttypes.h>
28 #include <string.h>
29 #include <fcntl.h>
30 #include <unistd.h>
31 #include <errno.h>
32 #include <iconv.h>
33 #include <sys/mman.h>
34 #include <sys/stat.h>
35 #include <assert.h>
36
37 #include "c-ctype.h"
38 #include "full-read.h"
39 #include "full-write.h"
40
41 #ifndef O_CLOEXEC
42 #define O_CLOEXEC 0
43 #endif
44
45 #define STREQ(a,b) (strcmp((a),(b)) == 0)
46 #define STRCASEEQ(a,b) (strcasecmp((a),(b)) == 0)
47 //#define STRNEQ(a,b) (strcmp((a),(b)) != 0)
48 //#define STRCASENEQ(a,b) (strcasecmp((a),(b)) != 0)
49 #define STREQLEN(a,b,n) (strncmp((a),(b),(n)) == 0)
50 //#define STRCASEEQLEN(a,b,n) (strncasecmp((a),(b),(n)) == 0)
51 //#define STRNEQLEN(a,b,n) (strncmp((a),(b),(n)) != 0)
52 //#define STRCASENEQLEN(a,b,n) (strncasecmp((a),(b),(n)) != 0)
53 #define STRPREFIX(a,b) (strncmp((a),(b),strlen((b))) == 0)
54
55 #include "hivex.h"
56 #include "byte_conversions.h"
57
58 /* These limits are in place to stop really stupid stuff and/or exploits. */
59 #define HIVEX_MAX_SUBKEYS       15000
60 #define HIVEX_MAX_VALUES        10000
61 #define HIVEX_MAX_VALUE_LEN   1000000
62 #define HIVEX_MAX_ALLOCATION  1000000
63
64 static char *windows_utf16_to_utf8 (/* const */ char *input, size_t len);
65 static size_t utf16_string_len_in_bytes (const char *str);
66 static size_t utf16_string_len_in_bytes_max (const char *str, size_t len);
67
68 struct hive_h {
69   char *filename;
70   int fd;
71   size_t size;
72   int msglvl;
73   int writable;
74
75   /* Registry file, memory mapped if read-only, or malloc'd if writing. */
76   union {
77     char *addr;
78     struct ntreg_header *hdr;
79   };
80
81   /* Use a bitmap to store which file offsets are valid (point to a
82    * used block).  We only need to store 1 bit per 32 bits of the file
83    * (because blocks are 4-byte aligned).  We found that the average
84    * block size in a registry file is ~50 bytes.  So roughly 1 in 12
85    * bits in the bitmap will be set, making it likely a more efficient
86    * structure than a hash table.
87    */
88   char *bitmap;
89 #define BITMAP_SET(bitmap,off) (bitmap[(off)>>5] |= 1 << (((off)>>2)&7))
90 #define BITMAP_CLR(bitmap,off) (bitmap[(off)>>5] &= ~ (1 << (((off)>>2)&7)))
91 #define BITMAP_TST(bitmap,off) (bitmap[(off)>>5] & (1 << (((off)>>2)&7)))
92 #define IS_VALID_BLOCK(h,off)               \
93   (((off) & 3) == 0 &&                      \
94    (off) >= 0x1000 &&                       \
95    (off) < (h)->size &&                     \
96    BITMAP_TST((h)->bitmap,(off)))
97
98   /* Fields from the header, extracted from little-endianness hell. */
99   size_t rootoffs;              /* Root key offset (always an nk-block). */
100   size_t endpages;              /* Offset of end of pages. */
101
102   /* For writing. */
103   size_t endblocks;             /* Offset to next block allocation (0
104                                    if not allocated anything yet). */
105 };
106
107 /* NB. All fields are little endian. */
108 struct ntreg_header {
109   char magic[4];                /* "regf" */
110   uint32_t sequence1;
111   uint32_t sequence2;
112   char last_modified[8];
113   uint32_t major_ver;           /* 1 */
114   uint32_t minor_ver;           /* 3 */
115   uint32_t unknown5;            /* 0 */
116   uint32_t unknown6;            /* 1 */
117   uint32_t offset;              /* offset of root key record - 4KB */
118   uint32_t blocks;              /* pointer AFTER last hbin in file - 4KB */
119   uint32_t unknown7;            /* 1 */
120   /* 0x30 */
121   char name[64];                /* original file name of hive */
122   char unknown_guid1[16];
123   char unknown_guid2[16];
124   /* 0x90 */
125   uint32_t unknown8;
126   char unknown_guid3[16];
127   uint32_t unknown9;
128   /* 0xa8 */
129   char unknown10[340];
130   /* 0x1fc */
131   uint32_t csum;                /* checksum: xor of dwords 0-0x1fb. */
132   /* 0x200 */
133   char unknown11[3528];
134   /* 0xfc8 */
135   char unknown_guid4[16];
136   char unknown_guid5[16];
137   char unknown_guid6[16];
138   uint32_t unknown12;
139   uint32_t unknown13;
140   /* 0x1000 */
141 } __attribute__((__packed__));
142
143 struct ntreg_hbin_page {
144   char magic[4];                /* "hbin" */
145   uint32_t offset_first;        /* offset from 1st block */
146   uint32_t page_size;           /* size of this page (multiple of 4KB) */
147   char unknown[20];
148   /* Linked list of blocks follows here. */
149 } __attribute__((__packed__));
150
151 struct ntreg_hbin_block {
152   int32_t seg_len;              /* length of this block (-ve for used block) */
153   char id[2];                   /* the block type (eg. "nk" for nk record) */
154   /* Block data follows here. */
155 } __attribute__((__packed__));
156
157 #define BLOCK_ID_EQ(h,offs,eqid) \
158   (STREQLEN (((struct ntreg_hbin_block *)((h)->addr + (offs)))->id, (eqid), 2))
159
160 static size_t
161 block_len (hive_h *h, size_t blkoff, int *used)
162 {
163   struct ntreg_hbin_block *block;
164   block = (struct ntreg_hbin_block *) (h->addr + blkoff);
165
166   int32_t len = le32toh (block->seg_len);
167   if (len < 0) {
168     if (used) *used = 1;
169     len = -len;
170   } else {
171     if (used) *used = 0;
172   }
173
174   return (size_t) len;
175 }
176
177 struct ntreg_nk_record {
178   int32_t seg_len;              /* length (always -ve because used) */
179   char id[2];                   /* "nk" */
180   uint16_t flags;
181   char timestamp[8];
182   uint32_t unknown1;
183   uint32_t parent;              /* offset of owner/parent */
184   uint32_t nr_subkeys;          /* number of subkeys */
185   uint32_t nr_subkeys_volatile;
186   uint32_t subkey_lf;           /* lf record containing list of subkeys */
187   uint32_t subkey_lf_volatile;
188   uint32_t nr_values;           /* number of values */
189   uint32_t vallist;             /* value-list record */
190   uint32_t sk;                  /* offset of sk-record */
191   uint32_t classname;           /* offset of classname record */
192   uint16_t max_subkey_name_len; /* maximum length of a subkey name in bytes
193                                    if the subkey was reencoded as UTF-16LE */
194   uint16_t unknown2;
195   uint32_t unknown3;
196   uint32_t max_vk_name_len;     /* maximum length of any vk name in bytes
197                                    if the name was reencoded as UTF-16LE */
198   uint32_t max_vk_data_len;     /* maximum length of any vk data in bytes */
199   uint32_t unknown6;
200   uint16_t name_len;            /* length of name */
201   uint16_t classname_len;       /* length of classname */
202   char name[1];                 /* name follows here */
203 } __attribute__((__packed__));
204
205 struct ntreg_lf_record {
206   int32_t seg_len;
207   char id[2];                   /* "lf"|"lh" */
208   uint16_t nr_keys;             /* number of keys in this record */
209   struct {
210     uint32_t offset;            /* offset of nk-record for this subkey */
211     char hash[4];               /* hash of subkey name */
212   } keys[1];
213 } __attribute__((__packed__));
214
215 struct ntreg_ri_record {
216   int32_t seg_len;
217   char id[2];                   /* "ri" */
218   uint16_t nr_offsets;          /* number of pointers to lh records */
219   uint32_t offset[1];           /* list of pointers to lh records */
220 } __attribute__((__packed__));
221
222 /* This has no ID header. */
223 struct ntreg_value_list {
224   int32_t seg_len;
225   uint32_t offset[1];           /* list of pointers to vk records */
226 } __attribute__((__packed__));
227
228 struct ntreg_vk_record {
229   int32_t seg_len;              /* length (always -ve because used) */
230   char id[2];                   /* "vk" */
231   uint16_t name_len;            /* length of name */
232   /* length of the data:
233    * If data_len is <= 4, then it's stored inline.
234    * Top bit is set to indicate inline.
235    */
236   uint32_t data_len;
237   uint32_t data_offset;         /* pointer to the data (or data if inline) */
238   uint32_t data_type;           /* type of the data */
239   uint16_t flags;               /* bit 0 set => key name ASCII,
240                                    bit 0 clr => key name UTF-16.
241                                    Only seen ASCII here in the wild.
242                                    NB: this is CLEAR for default key. */
243   uint16_t unknown2;
244   char name[1];                 /* key name follows here */
245 } __attribute__((__packed__));
246
247 struct ntreg_sk_record {
248   int32_t seg_len;              /* length (always -ve because used) */
249   char id[2];                   /* "sk" */
250   uint16_t unknown1;
251   uint32_t sk_next;             /* linked into a circular list */
252   uint32_t sk_prev;
253   uint32_t refcount;            /* reference count */
254   uint32_t sec_len;             /* length of security info */
255   char sec_desc[1];             /* security info follows */
256 } __attribute__((__packed__));
257
258 static uint32_t
259 header_checksum (const hive_h *h)
260 {
261   uint32_t *daddr = (uint32_t *) h->addr;
262   size_t i;
263   uint32_t sum = 0;
264
265   for (i = 0; i < 0x1fc / 4; ++i) {
266     sum ^= le32toh (*daddr);
267     daddr++;
268   }
269
270   return sum;
271 }
272
273 #define HIVEX_OPEN_MSGLVL_MASK (HIVEX_OPEN_VERBOSE|HIVEX_OPEN_DEBUG)
274
275 hive_h *
276 hivex_open (const char *filename, int flags)
277 {
278   hive_h *h = NULL;
279
280   assert (sizeof (struct ntreg_header) == 0x1000);
281   assert (offsetof (struct ntreg_header, csum) == 0x1fc);
282
283   h = calloc (1, sizeof *h);
284   if (h == NULL)
285     goto error;
286
287   h->msglvl = flags & HIVEX_OPEN_MSGLVL_MASK;
288
289   const char *debug = getenv ("HIVEX_DEBUG");
290   if (debug && STREQ (debug, "1"))
291     h->msglvl = 2;
292
293   if (h->msglvl >= 2)
294     fprintf (stderr, "hivex_open: created handle %p\n", h);
295
296   h->writable = !!(flags & HIVEX_OPEN_WRITE);
297   h->filename = strdup (filename);
298   if (h->filename == NULL)
299     goto error;
300
301   h->fd = open (filename, O_RDONLY | O_CLOEXEC);
302   if (h->fd == -1)
303     goto error;
304
305   struct stat statbuf;
306   if (fstat (h->fd, &statbuf) == -1)
307     goto error;
308
309   h->size = statbuf.st_size;
310
311   if (!h->writable) {
312     h->addr = mmap (NULL, h->size, PROT_READ, MAP_SHARED, h->fd, 0);
313     if (h->addr == MAP_FAILED)
314       goto error;
315
316     if (h->msglvl >= 2)
317       fprintf (stderr, "hivex_open: mapped file at %p\n", h->addr);
318   } else {
319     h->addr = malloc (h->size);
320     if (h->addr == NULL)
321       goto error;
322
323     if (full_read (h->fd, h->addr, h->size) < h->size)
324       goto error;
325   }
326
327   /* Check header. */
328   if (h->hdr->magic[0] != 'r' ||
329       h->hdr->magic[1] != 'e' ||
330       h->hdr->magic[2] != 'g' ||
331       h->hdr->magic[3] != 'f') {
332     fprintf (stderr, "hivex: %s: not a Windows NT Registry hive file\n",
333              filename);
334     errno = ENOTSUP;
335     goto error;
336   }
337
338   /* Check major version. */
339   uint32_t major_ver = le32toh (h->hdr->major_ver);
340   if (major_ver != 1) {
341     fprintf (stderr,
342              "hivex: %s: hive file major version %" PRIu32 " (expected 1)\n",
343              filename, major_ver);
344     errno = ENOTSUP;
345     goto error;
346   }
347
348   h->bitmap = calloc (1 + h->size / 32, 1);
349   if (h->bitmap == NULL)
350     goto error;
351
352   /* Header checksum. */
353   uint32_t sum = header_checksum (h);
354   if (sum != le32toh (h->hdr->csum)) {
355     fprintf (stderr, "hivex: %s: bad checksum in hive header\n", filename);
356     errno = EINVAL;
357     goto error;
358   }
359
360   if (h->msglvl >= 2) {
361     char *name = windows_utf16_to_utf8 (h->hdr->name, 64);
362
363     fprintf (stderr,
364              "hivex_open: header fields:\n"
365              "  file version             %" PRIu32 ".%" PRIu32 "\n"
366              "  sequence nos             %" PRIu32 " %" PRIu32 "\n"
367              "    (sequences nos should match if hive was synched at shutdown)\n"
368              "  original file name       %s\n"
369              "    (only 32 chars are stored, name is probably truncated)\n"
370              "  root offset              0x%x + 0x1000\n"
371              "  end of last page         0x%x + 0x1000 (total file size 0x%zx)\n"
372              "  checksum                 0x%x (calculated 0x%x)\n",
373              major_ver, le32toh (h->hdr->minor_ver),
374              le32toh (h->hdr->sequence1), le32toh (h->hdr->sequence2),
375              name ? name : "(conversion failed)",
376              le32toh (h->hdr->offset),
377              le32toh (h->hdr->blocks), h->size,
378              le32toh (h->hdr->csum), sum);
379     free (name);
380   }
381
382   h->rootoffs = le32toh (h->hdr->offset) + 0x1000;
383   h->endpages = le32toh (h->hdr->blocks) + 0x1000;
384
385   if (h->msglvl >= 2)
386     fprintf (stderr, "hivex_open: root offset = 0x%zx\n", h->rootoffs);
387
388   /* We'll set this flag when we see a block with the root offset (ie.
389    * the root block).
390    */
391   int seen_root_block = 0, bad_root_block = 0;
392
393   /* Collect some stats. */
394   size_t pages = 0;           /* Number of hbin pages read. */
395   size_t smallest_page = SIZE_MAX, largest_page = 0;
396   size_t blocks = 0;          /* Total number of blocks found. */
397   size_t smallest_block = SIZE_MAX, largest_block = 0, blocks_bytes = 0;
398   size_t used_blocks = 0;     /* Total number of used blocks found. */
399   size_t used_size = 0;       /* Total size (bytes) of used blocks. */
400
401   /* Read the pages and blocks.  The aim here is to be robust against
402    * corrupt or malicious registries.  So we make sure the loops
403    * always make forward progress.  We add the address of each block
404    * we read to a hash table so pointers will only reference the start
405    * of valid blocks.
406    */
407   size_t off;
408   struct ntreg_hbin_page *page;
409   for (off = 0x1000; off < h->size; off += le32toh (page->page_size)) {
410     if (off >= h->endpages)
411       break;
412
413     page = (struct ntreg_hbin_page *) (h->addr + off);
414     if (page->magic[0] != 'h' ||
415         page->magic[1] != 'b' ||
416         page->magic[2] != 'i' ||
417         page->magic[3] != 'n') {
418       fprintf (stderr, "hivex: %s: trailing garbage at end of file (at 0x%zx, after %zu pages)\n",
419                filename, off, pages);
420       errno = ENOTSUP;
421       goto error;
422     }
423
424     size_t page_size = le32toh (page->page_size);
425     if (h->msglvl >= 2)
426       fprintf (stderr, "hivex_open: page at 0x%zx, size %zu\n", off, page_size);
427     pages++;
428     if (page_size < smallest_page) smallest_page = page_size;
429     if (page_size > largest_page) largest_page = page_size;
430
431     if (page_size <= sizeof (struct ntreg_hbin_page) ||
432         (page_size & 0x0fff) != 0) {
433       fprintf (stderr, "hivex: %s: page size %zu at 0x%zx, bad registry\n",
434                filename, page_size, off);
435       errno = ENOTSUP;
436       goto error;
437     }
438
439     /* Read the blocks in this page. */
440     size_t blkoff;
441     struct ntreg_hbin_block *block;
442     size_t seg_len;
443     for (blkoff = off + 0x20;
444          blkoff < off + page_size;
445          blkoff += seg_len) {
446       blocks++;
447
448       int is_root = blkoff == h->rootoffs;
449       if (is_root)
450         seen_root_block = 1;
451
452       block = (struct ntreg_hbin_block *) (h->addr + blkoff);
453       int used;
454       seg_len = block_len (h, blkoff, &used);
455       if (seg_len <= 4 || (seg_len & 3) != 0) {
456         fprintf (stderr, "hivex: %s: block size %" PRIu32 " at 0x%zx, bad registry\n",
457                  filename, le32toh (block->seg_len), blkoff);
458         errno = ENOTSUP;
459         goto error;
460       }
461
462       if (h->msglvl >= 2)
463         fprintf (stderr, "hivex_open: %s block id %d,%d at 0x%zx size %zu%s\n",
464                  used ? "used" : "free", block->id[0], block->id[1], blkoff,
465                  seg_len, is_root ? " (root)" : "");
466
467       blocks_bytes += seg_len;
468       if (seg_len < smallest_block) smallest_block = seg_len;
469       if (seg_len > largest_block) largest_block = seg_len;
470
471       if (is_root && !used)
472         bad_root_block = 1;
473
474       if (used) {
475         used_blocks++;
476         used_size += seg_len;
477
478         /* Root block must be an nk-block. */
479         if (is_root && (block->id[0] != 'n' || block->id[1] != 'k'))
480           bad_root_block = 1;
481
482         /* Note this blkoff is a valid address. */
483         BITMAP_SET (h->bitmap, blkoff);
484       }
485     }
486   }
487
488   if (!seen_root_block) {
489     fprintf (stderr, "hivex: %s: no root block found\n", filename);
490     errno = ENOTSUP;
491     goto error;
492   }
493
494   if (bad_root_block) {
495     fprintf (stderr, "hivex: %s: bad root block (free or not nk)\n", filename);
496     errno = ENOTSUP;
497     goto error;
498   }
499
500   if (h->msglvl >= 1)
501     fprintf (stderr,
502              "hivex_open: successfully read Windows Registry hive file:\n"
503              "  pages:          %zu [sml: %zu, lge: %zu]\n"
504              "  blocks:         %zu [sml: %zu, avg: %zu, lge: %zu]\n"
505              "  blocks used:    %zu\n"
506              "  bytes used:     %zu\n",
507              pages, smallest_page, largest_page,
508              blocks, smallest_block, blocks_bytes / blocks, largest_block,
509              used_blocks, used_size);
510
511   return h;
512
513  error:;
514   int err = errno;
515   if (h) {
516     free (h->bitmap);
517     if (h->addr && h->size && h->addr != MAP_FAILED) {
518       if (!h->writable)
519         munmap (h->addr, h->size);
520       else
521         free (h->addr);
522     }
523     if (h->fd >= 0)
524       close (h->fd);
525     free (h->filename);
526     free (h);
527   }
528   errno = err;
529   return NULL;
530 }
531
532 int
533 hivex_close (hive_h *h)
534 {
535   int r;
536
537   free (h->bitmap);
538   if (!h->writable)
539     munmap (h->addr, h->size);
540   else
541     free (h->addr);
542   r = close (h->fd);
543   free (h->filename);
544   free (h);
545
546   return r;
547 }
548
549 /*----------------------------------------------------------------------
550  * Reading.
551  */
552
553 hive_node_h
554 hivex_root (hive_h *h)
555 {
556   hive_node_h ret = h->rootoffs;
557   if (!IS_VALID_BLOCK (h, ret)) {
558     errno = ENOKEY;
559     return 0;
560   }
561   return ret;
562 }
563
564 char *
565 hivex_node_name (hive_h *h, hive_node_h node)
566 {
567   if (!IS_VALID_BLOCK (h, node) || !BLOCK_ID_EQ (h, node, "nk")) {
568     errno = EINVAL;
569     return NULL;
570   }
571
572   struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
573
574   /* AFAIK the node name is always plain ASCII, so no conversion
575    * to UTF-8 is necessary.  However we do need to nul-terminate
576    * the string.
577    */
578
579   /* nk->name_len is unsigned, 16 bit, so this is safe ...  However
580    * we have to make sure the length doesn't exceed the block length.
581    */
582   size_t len = le16toh (nk->name_len);
583   size_t seg_len = block_len (h, node, NULL);
584   if (sizeof (struct ntreg_nk_record) + len - 1 > seg_len) {
585     if (h->msglvl >= 2)
586       fprintf (stderr, "hivex_node_name: returning EFAULT because node name is too long (%zu, %zu)\n",
587               len, seg_len);
588     errno = EFAULT;
589     return NULL;
590   }
591
592   char *ret = malloc (len + 1);
593   if (ret == NULL)
594     return NULL;
595   memcpy (ret, nk->name, len);
596   ret[len] = '\0';
597   return ret;
598 }
599
600 #if 0
601 /* I think the documentation for the sk and classname fields in the nk
602  * record is wrong, or else the offset field is in the wrong place.
603  * Otherwise this makes no sense.  Disabled this for now -- it's not
604  * useful for reading the registry anyway.
605  */
606
607 hive_security_h
608 hivex_node_security (hive_h *h, hive_node_h node)
609 {
610   if (!IS_VALID_BLOCK (h, node) || !BLOCK_ID_EQ (h, node, "nk")) {
611     errno = EINVAL;
612     return 0;
613   }
614
615   struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
616
617   hive_node_h ret = le32toh (nk->sk);
618   ret += 0x1000;
619   if (!IS_VALID_BLOCK (h, ret)) {
620     errno = EFAULT;
621     return 0;
622   }
623   return ret;
624 }
625
626 hive_classname_h
627 hivex_node_classname (hive_h *h, hive_node_h node)
628 {
629   if (!IS_VALID_BLOCK (h, node) || !BLOCK_ID_EQ (h, node, "nk")) {
630     errno = EINVAL;
631     return 0;
632   }
633
634   struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
635
636   hive_node_h ret = le32toh (nk->classname);
637   ret += 0x1000;
638   if (!IS_VALID_BLOCK (h, ret)) {
639     errno = EFAULT;
640     return 0;
641   }
642   return ret;
643 }
644 #endif
645
646 /* Structure for returning 0-terminated lists of offsets (nodes,
647  * values, etc).
648  */
649 struct offset_list {
650   size_t *offsets;
651   size_t len;
652   size_t alloc;
653 };
654
655 static void
656 init_offset_list (struct offset_list *list)
657 {
658   list->len = 0;
659   list->alloc = 0;
660   list->offsets = NULL;
661 }
662
663 #define INIT_OFFSET_LIST(name) \
664   struct offset_list name; \
665   init_offset_list (&name)
666
667 /* Preallocates the offset_list, but doesn't make the contents longer. */
668 static int
669 grow_offset_list (struct offset_list *list, size_t alloc)
670 {
671   assert (alloc >= list->len);
672   size_t *p = realloc (list->offsets, alloc * sizeof (size_t));
673   if (p == NULL)
674     return -1;
675   list->offsets = p;
676   list->alloc = alloc;
677   return 0;
678 }
679
680 static int
681 add_to_offset_list (struct offset_list *list, size_t offset)
682 {
683   if (list->len >= list->alloc) {
684     if (grow_offset_list (list, list->alloc ? list->alloc * 2 : 4) == -1)
685       return -1;
686   }
687   list->offsets[list->len] = offset;
688   list->len++;
689   return 0;
690 }
691
692 static void
693 free_offset_list (struct offset_list *list)
694 {
695   free (list->offsets);
696 }
697
698 static size_t *
699 return_offset_list (struct offset_list *list)
700 {
701   if (add_to_offset_list (list, 0) == -1)
702     return NULL;
703   return list->offsets;         /* caller frees */
704 }
705
706 /* Iterate over children, returning child nodes and intermediate blocks. */
707 #define GET_CHILDREN_NO_CHECK_NK 1
708
709 static int
710 get_children (hive_h *h, hive_node_h node,
711               hive_node_h **children_ret, size_t **blocks_ret,
712               int flags)
713 {
714   if (!IS_VALID_BLOCK (h, node) || !BLOCK_ID_EQ (h, node, "nk")) {
715     errno = EINVAL;
716     return -1;
717   }
718
719   struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
720
721   size_t nr_subkeys_in_nk = le32toh (nk->nr_subkeys);
722
723   INIT_OFFSET_LIST (children);
724   INIT_OFFSET_LIST (blocks);
725
726   /* Deal with the common "no subkeys" case quickly. */
727   if (nr_subkeys_in_nk == 0)
728     goto ok;
729
730   /* Arbitrarily limit the number of subkeys we will ever deal with. */
731   if (nr_subkeys_in_nk > HIVEX_MAX_SUBKEYS) {
732     if (h->msglvl >= 2)
733       fprintf (stderr, "hivex: get_children: returning ERANGE because nr_subkeys_in_nk > HIVEX_MAX_SUBKEYS (%zu > %d)\n",
734                nr_subkeys_in_nk, HIVEX_MAX_SUBKEYS);
735     errno = ERANGE;
736     goto error;
737   }
738
739   /* Preallocate space for the children. */
740   if (grow_offset_list (&children, nr_subkeys_in_nk) == -1)
741     goto error;
742
743   /* The subkey_lf field can point either to an lf-record, which is
744    * the common case, or if there are lots of subkeys, to an
745    * ri-record.
746    */
747   size_t subkey_lf = le32toh (nk->subkey_lf);
748   subkey_lf += 0x1000;
749   if (!IS_VALID_BLOCK (h, subkey_lf)) {
750     if (h->msglvl >= 2)
751       fprintf (stderr, "hivex_node_children: returning EFAULT because subkey_lf is not a valid block (0x%zx)\n",
752                subkey_lf);
753     errno = EFAULT;
754     goto error;
755   }
756
757   if (add_to_offset_list (&blocks, subkey_lf) == -1)
758     goto error;
759
760   struct ntreg_hbin_block *block =
761     (struct ntreg_hbin_block *) (h->addr + subkey_lf);
762
763   /* Points to lf-record?  (Note, also "lh" but that is basically the
764    * same as "lf" as far as we are concerned here).
765    */
766   if (block->id[0] == 'l' && (block->id[1] == 'f' || block->id[1] == 'h')) {
767     struct ntreg_lf_record *lf = (struct ntreg_lf_record *) block;
768
769     /* Check number of subkeys in the nk-record matches number of subkeys
770      * in the lf-record.
771      */
772     size_t nr_subkeys_in_lf = le16toh (lf->nr_keys);
773
774     if (h->msglvl >= 2)
775       fprintf (stderr, "hivex_node_children: nr_subkeys_in_nk = %zu, nr_subkeys_in_lf = %zu\n",
776                nr_subkeys_in_nk, nr_subkeys_in_lf);
777
778     if (nr_subkeys_in_nk != nr_subkeys_in_lf) {
779       errno = ENOTSUP;
780       goto error;
781     }
782
783     size_t len = block_len (h, subkey_lf, NULL);
784     if (8 + nr_subkeys_in_lf * 8 > len) {
785       if (h->msglvl >= 2)
786         fprintf (stderr, "hivex_node_children: returning EFAULT because too many subkeys (%zu, %zu)\n",
787                  nr_subkeys_in_lf, len);
788       errno = EFAULT;
789       goto error;
790     }
791
792     size_t i;
793     for (i = 0; i < nr_subkeys_in_lf; ++i) {
794       hive_node_h subkey = le32toh (lf->keys[i].offset);
795       subkey += 0x1000;
796       if (!(flags & GET_CHILDREN_NO_CHECK_NK)) {
797         if (!IS_VALID_BLOCK (h, subkey)) {
798           if (h->msglvl >= 2)
799             fprintf (stderr, "hivex_node_children: returning EFAULT because subkey is not a valid block (0x%zx)\n",
800                      subkey);
801           errno = EFAULT;
802           goto error;
803         }
804       }
805       if (add_to_offset_list (&children, subkey) == -1)
806         goto error;
807     }
808     goto ok;
809   }
810   /* Points to ri-record? */
811   else if (block->id[0] == 'r' && block->id[1] == 'i') {
812     struct ntreg_ri_record *ri = (struct ntreg_ri_record *) block;
813
814     size_t nr_offsets = le16toh (ri->nr_offsets);
815
816     /* Count total number of children. */
817     size_t i, count = 0;
818     for (i = 0; i < nr_offsets; ++i) {
819       hive_node_h offset = le32toh (ri->offset[i]);
820       offset += 0x1000;
821       if (!IS_VALID_BLOCK (h, offset)) {
822         if (h->msglvl >= 2)
823           fprintf (stderr, "hivex_node_children: returning EFAULT because ri-offset is not a valid block (0x%zx)\n",
824                    offset);
825         errno = EFAULT;
826         goto error;
827       }
828       if (!BLOCK_ID_EQ (h, offset, "lf") && !BLOCK_ID_EQ (h, offset, "lh")) {
829         if (h->msglvl >= 2)
830           fprintf (stderr, "get_children: returning ENOTSUP because ri-record offset does not point to lf/lh (0x%zx)\n",
831                    offset);
832         errno = ENOTSUP;
833         goto error;
834       }
835
836       if (add_to_offset_list (&blocks, offset) == -1)
837         goto error;
838
839       struct ntreg_lf_record *lf =
840         (struct ntreg_lf_record *) (h->addr + offset);
841
842       count += le16toh (lf->nr_keys);
843     }
844
845     if (h->msglvl >= 2)
846       fprintf (stderr, "hivex_node_children: nr_subkeys_in_nk = %zu, counted = %zu\n",
847                nr_subkeys_in_nk, count);
848
849     if (nr_subkeys_in_nk != count) {
850       errno = ENOTSUP;
851       goto error;
852     }
853
854     /* Copy list of children.  Note nr_subkeys_in_nk is limited to
855      * something reasonable above.
856      */
857     for (i = 0; i < nr_offsets; ++i) {
858       hive_node_h offset = le32toh (ri->offset[i]);
859       offset += 0x1000;
860       if (!IS_VALID_BLOCK (h, offset)) {
861         if (h->msglvl >= 2)
862           fprintf (stderr, "hivex_node_children: returning EFAULT because ri-offset is not a valid block (0x%zx)\n",
863                    offset);
864         errno = EFAULT;
865         goto error;
866       }
867       if (!BLOCK_ID_EQ (h, offset, "lf") && !BLOCK_ID_EQ (h, offset, "lh")) {
868         if (h->msglvl >= 2)
869           fprintf (stderr, "get_children: returning ENOTSUP because ri-record offset does not point to lf/lh (0x%zx)\n",
870                    offset);
871         errno = ENOTSUP;
872         goto error;
873       }
874
875       struct ntreg_lf_record *lf =
876         (struct ntreg_lf_record *) (h->addr + offset);
877
878       size_t j;
879       for (j = 0; j < le16toh (lf->nr_keys); ++j) {
880         hive_node_h subkey = le32toh (lf->keys[j].offset);
881         subkey += 0x1000;
882         if (!(flags & GET_CHILDREN_NO_CHECK_NK)) {
883           if (!IS_VALID_BLOCK (h, subkey)) {
884             if (h->msglvl >= 2)
885               fprintf (stderr, "hivex_node_children: returning EFAULT because indirect subkey is not a valid block (0x%zx)\n",
886                        subkey);
887             errno = EFAULT;
888             goto error;
889           }
890         }
891         if (add_to_offset_list (&children, subkey) == -1)
892           goto error;
893       }
894     }
895     goto ok;
896   }
897   /* else not supported, set errno and fall through */
898   if (h->msglvl >= 2)
899     fprintf (stderr, "get_children: returning ENOTSUP because subkey block is not lf/lh/ri (0x%zx, %d, %d)\n",
900              subkey_lf, block->id[0], block->id[1]);
901   errno = ENOTSUP;
902  error:
903   free_offset_list (&children);
904   free_offset_list (&blocks);
905   return -1;
906
907  ok:
908   *children_ret = return_offset_list (&children);
909   *blocks_ret = return_offset_list (&blocks);
910   if (!*children_ret || !*blocks_ret)
911     goto error;
912   return 0;
913 }
914
915 hive_node_h *
916 hivex_node_children (hive_h *h, hive_node_h node)
917 {
918   hive_node_h *children;
919   size_t *blocks;
920
921   if (get_children (h, node, &children, &blocks, 0) == -1)
922     return NULL;
923
924   free (blocks);
925   return children;
926 }
927
928 /* Very inefficient, but at least having a separate API call
929  * allows us to make it more efficient in future.
930  */
931 hive_node_h
932 hivex_node_get_child (hive_h *h, hive_node_h node, const char *nname)
933 {
934   hive_node_h *children = NULL;
935   char *name = NULL;
936   hive_node_h ret = 0;
937
938   children = hivex_node_children (h, node);
939   if (!children) goto error;
940
941   size_t i;
942   for (i = 0; children[i] != 0; ++i) {
943     name = hivex_node_name (h, children[i]);
944     if (!name) goto error;
945     if (STRCASEEQ (name, nname)) {
946       ret = children[i];
947       break;
948     }
949     free (name); name = NULL;
950   }
951
952  error:
953   free (children);
954   free (name);
955   return ret;
956 }
957
958 hive_node_h
959 hivex_node_parent (hive_h *h, hive_node_h node)
960 {
961   if (!IS_VALID_BLOCK (h, node) || !BLOCK_ID_EQ (h, node, "nk")) {
962     errno = EINVAL;
963     return 0;
964   }
965
966   struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
967
968   hive_node_h ret = le32toh (nk->parent);
969   ret += 0x1000;
970   if (!IS_VALID_BLOCK (h, ret)) {
971     if (h->msglvl >= 2)
972       fprintf (stderr, "hivex_node_parent: returning EFAULT because parent is not a valid block (0x%zx)\n",
973               ret);
974     errno = EFAULT;
975     return 0;
976   }
977   return ret;
978 }
979
980 static int
981 get_values (hive_h *h, hive_node_h node,
982             hive_value_h **values_ret, size_t **blocks_ret)
983 {
984   if (!IS_VALID_BLOCK (h, node) || !BLOCK_ID_EQ (h, node, "nk")) {
985     errno = EINVAL;
986     return -1;
987   }
988
989   struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
990
991   size_t nr_values = le32toh (nk->nr_values);
992
993   if (h->msglvl >= 2)
994     fprintf (stderr, "hivex_node_values: nr_values = %zu\n", nr_values);
995
996   INIT_OFFSET_LIST (values);
997   INIT_OFFSET_LIST (blocks);
998
999   /* Deal with the common "no values" case quickly. */
1000   if (nr_values == 0)
1001     goto ok;
1002
1003   /* Arbitrarily limit the number of values we will ever deal with. */
1004   if (nr_values > HIVEX_MAX_VALUES) {
1005     if (h->msglvl >= 2)
1006       fprintf (stderr, "hivex: get_values: returning ERANGE because nr_values > HIVEX_MAX_VALUES (%zu > %d)\n",
1007                nr_values, HIVEX_MAX_VALUES);
1008     errno = ERANGE;
1009     goto error;
1010   }
1011
1012   /* Preallocate space for the values. */
1013   if (grow_offset_list (&values, nr_values) == -1)
1014     goto error;
1015
1016   /* Get the value list and check it looks reasonable. */
1017   size_t vlist_offset = le32toh (nk->vallist);
1018   vlist_offset += 0x1000;
1019   if (!IS_VALID_BLOCK (h, vlist_offset)) {
1020     if (h->msglvl >= 2)
1021       fprintf (stderr, "hivex_node_values: returning EFAULT because value list is not a valid block (0x%zx)\n",
1022                vlist_offset);
1023     errno = EFAULT;
1024     goto error;
1025   }
1026
1027   if (add_to_offset_list (&blocks, vlist_offset) == -1)
1028     goto error;
1029
1030   struct ntreg_value_list *vlist =
1031     (struct ntreg_value_list *) (h->addr + vlist_offset);
1032
1033   size_t len = block_len (h, vlist_offset, NULL);
1034   if (4 + nr_values * 4 > len) {
1035     if (h->msglvl >= 2)
1036       fprintf (stderr, "hivex_node_values: returning EFAULT because value list is too long (%zu, %zu)\n",
1037                nr_values, len);
1038     errno = EFAULT;
1039     goto error;
1040   }
1041
1042   size_t i;
1043   for (i = 0; i < nr_values; ++i) {
1044     hive_node_h value = vlist->offset[i];
1045     value += 0x1000;
1046     if (!IS_VALID_BLOCK (h, value)) {
1047       if (h->msglvl >= 2)
1048         fprintf (stderr, "hivex_node_values: returning EFAULT because value is not a valid block (0x%zx)\n",
1049                  value);
1050       errno = EFAULT;
1051       goto error;
1052     }
1053     if (add_to_offset_list (&values, value) == -1)
1054       goto error;
1055   }
1056
1057  ok:
1058   *values_ret = return_offset_list (&values);
1059   *blocks_ret = return_offset_list (&blocks);
1060   if (!*values_ret || !*blocks_ret)
1061     goto error;
1062   return 0;
1063
1064  error:
1065   free_offset_list (&values);
1066   free_offset_list (&blocks);
1067   return -1;
1068 }
1069
1070 hive_value_h *
1071 hivex_node_values (hive_h *h, hive_node_h node)
1072 {
1073   hive_value_h *values;
1074   size_t *blocks;
1075
1076   if (get_values (h, node, &values, &blocks) == -1)
1077     return NULL;
1078
1079   free (blocks);
1080   return values;
1081 }
1082
1083 /* Very inefficient, but at least having a separate API call
1084  * allows us to make it more efficient in future.
1085  */
1086 hive_value_h
1087 hivex_node_get_value (hive_h *h, hive_node_h node, const char *key)
1088 {
1089   hive_value_h *values = NULL;
1090   char *name = NULL;
1091   hive_value_h ret = 0;
1092
1093   values = hivex_node_values (h, node);
1094   if (!values) goto error;
1095
1096   size_t i;
1097   for (i = 0; values[i] != 0; ++i) {
1098     name = hivex_value_key (h, values[i]);
1099     if (!name) goto error;
1100     if (STRCASEEQ (name, key)) {
1101       ret = values[i];
1102       break;
1103     }
1104     free (name); name = NULL;
1105   }
1106
1107  error:
1108   free (values);
1109   free (name);
1110   return ret;
1111 }
1112
1113 char *
1114 hivex_value_key (hive_h *h, hive_value_h value)
1115 {
1116   if (!IS_VALID_BLOCK (h, value) || !BLOCK_ID_EQ (h, value, "vk")) {
1117     errno = EINVAL;
1118     return 0;
1119   }
1120
1121   struct ntreg_vk_record *vk = (struct ntreg_vk_record *) (h->addr + value);
1122
1123   /* AFAIK the key is always plain ASCII, so no conversion to UTF-8 is
1124    * necessary.  However we do need to nul-terminate the string.
1125    */
1126
1127   /* vk->name_len is unsigned, 16 bit, so this is safe ...  However
1128    * we have to make sure the length doesn't exceed the block length.
1129    */
1130   size_t len = le16toh (vk->name_len);
1131   size_t seg_len = block_len (h, value, NULL);
1132   if (sizeof (struct ntreg_vk_record) + len - 1 > seg_len) {
1133     if (h->msglvl >= 2)
1134       fprintf (stderr, "hivex_value_key: returning EFAULT because key length is too long (%zu, %zu)\n",
1135                len, seg_len);
1136     errno = EFAULT;
1137     return NULL;
1138   }
1139
1140   char *ret = malloc (len + 1);
1141   if (ret == NULL)
1142     return NULL;
1143   memcpy (ret, vk->name, len);
1144   ret[len] = '\0';
1145   return ret;
1146 }
1147
1148 int
1149 hivex_value_type (hive_h *h, hive_value_h value, hive_type *t, size_t *len)
1150 {
1151   if (!IS_VALID_BLOCK (h, value) || !BLOCK_ID_EQ (h, value, "vk")) {
1152     errno = EINVAL;
1153     return -1;
1154   }
1155
1156   struct ntreg_vk_record *vk = (struct ntreg_vk_record *) (h->addr + value);
1157
1158   if (t)
1159     *t = le32toh (vk->data_type);
1160
1161   if (len) {
1162     *len = le32toh (vk->data_len);
1163     *len &= 0x7fffffff;         /* top bit indicates if data is stored inline */
1164   }
1165
1166   return 0;
1167 }
1168
1169 char *
1170 hivex_value_value (hive_h *h, hive_value_h value,
1171                    hive_type *t_rtn, size_t *len_rtn)
1172 {
1173   if (!IS_VALID_BLOCK (h, value) || !BLOCK_ID_EQ (h, value, "vk")) {
1174     errno = EINVAL;
1175     return NULL;
1176   }
1177
1178   struct ntreg_vk_record *vk = (struct ntreg_vk_record *) (h->addr + value);
1179
1180   hive_type t;
1181   size_t len;
1182   int is_inline;
1183
1184   t = le32toh (vk->data_type);
1185
1186   len = le32toh (vk->data_len);
1187   is_inline = !!(len & 0x80000000);
1188   len &= 0x7fffffff;
1189
1190   if (h->msglvl >= 2)
1191     fprintf (stderr, "hivex_value_value: value=0x%zx, t=%d, len=%zu, inline=%d\n",
1192              value, t, len, is_inline);
1193
1194   if (t_rtn)
1195     *t_rtn = t;
1196   if (len_rtn)
1197     *len_rtn = len;
1198
1199   if (is_inline && len > 4) {
1200     errno = ENOTSUP;
1201     return NULL;
1202   }
1203
1204   /* Arbitrarily limit the length that we will read. */
1205   if (len > HIVEX_MAX_VALUE_LEN) {
1206     if (h->msglvl >= 2)
1207       fprintf (stderr, "hivex_value_value: returning ERANGE because data length > HIVEX_MAX_VALUE_LEN (%zu > %d)\n",
1208                len, HIVEX_MAX_SUBKEYS);
1209     errno = ERANGE;
1210     return NULL;
1211   }
1212
1213   char *ret = malloc (len);
1214   if (ret == NULL)
1215     return NULL;
1216
1217   if (is_inline) {
1218     memcpy (ret, (char *) &vk->data_offset, len);
1219     return ret;
1220   }
1221
1222   size_t data_offset = le32toh (vk->data_offset);
1223   data_offset += 0x1000;
1224   if (!IS_VALID_BLOCK (h, data_offset)) {
1225     if (h->msglvl >= 2)
1226       fprintf (stderr, "hivex_value_value: returning EFAULT because data offset is not a valid block (0x%zx)\n",
1227                data_offset);
1228     errno = EFAULT;
1229     free (ret);
1230     return NULL;
1231   }
1232
1233   /* Check that the declared size isn't larger than the block its in.
1234    *
1235    * XXX Some apparently valid registries are seen to have this,
1236    * so turn this into a warning and substitute the smaller length
1237    * instead.
1238    */
1239   size_t blen = block_len (h, data_offset, NULL);
1240   if (len > blen - 4 /* subtract 4 for block header */) {
1241     if (h->msglvl >= 2)
1242       fprintf (stderr, "hivex_value_value: warning: declared data length is longer than the block it is in (data 0x%zx, data len %zu, block len %zu)\n",
1243                data_offset, len, blen);
1244     len = blen - 4;
1245   }
1246
1247   char *data = h->addr + data_offset + 4;
1248   memcpy (ret, data, len);
1249   return ret;
1250 }
1251
1252 static char *
1253 windows_utf16_to_utf8 (/* const */ char *input, size_t len)
1254 {
1255   iconv_t ic = iconv_open ("UTF-8", "UTF-16");
1256   if (ic == (iconv_t) -1)
1257     return NULL;
1258
1259   /* iconv(3) has an insane interface ... */
1260
1261   /* Mostly UTF-8 will be smaller, so this is a good initial guess. */
1262   size_t outalloc = len;
1263
1264  again:;
1265   size_t inlen = len;
1266   size_t outlen = outalloc;
1267   char *out = malloc (outlen + 1);
1268   if (out == NULL) {
1269     int err = errno;
1270     iconv_close (ic);
1271     errno = err;
1272     return NULL;
1273   }
1274   char *inp = input;
1275   char *outp = out;
1276
1277   size_t r = iconv (ic, &inp, &inlen, &outp, &outlen);
1278   if (r == (size_t) -1) {
1279     if (errno == E2BIG) {
1280       int err = errno;
1281       size_t prev = outalloc;
1282       /* Try again with a larger output buffer. */
1283       free (out);
1284       outalloc *= 2;
1285       if (outalloc < prev) {
1286         iconv_close (ic);
1287         errno = err;
1288         return NULL;
1289       }
1290       goto again;
1291     }
1292     else {
1293       /* Else some conversion failure, eg. EILSEQ, EINVAL. */
1294       int err = errno;
1295       iconv_close (ic);
1296       free (out);
1297       errno = err;
1298       return NULL;
1299     }
1300   }
1301
1302   *outp = '\0';
1303   iconv_close (ic);
1304
1305   return out;
1306 }
1307
1308 char *
1309 hivex_value_string (hive_h *h, hive_value_h value)
1310 {
1311   hive_type t;
1312   size_t len;
1313   char *data = hivex_value_value (h, value, &t, &len);
1314
1315   if (data == NULL)
1316     return NULL;
1317
1318   if (t != hive_t_string && t != hive_t_expand_string && t != hive_t_link) {
1319     free (data);
1320     errno = EINVAL;
1321     return NULL;
1322   }
1323
1324   /* Deal with the case where Windows has allocated a large buffer
1325    * full of random junk, and only the first few bytes of the buffer
1326    * contain a genuine UTF-16 string.
1327    *
1328    * In this case, iconv would try to process the junk bytes as UTF-16
1329    * and inevitably find an illegal sequence (EILSEQ).  Instead, stop
1330    * after we find the first \0\0.
1331    *
1332    * (Found by Hilko Bengen in a fresh Windows XP SOFTWARE hive).
1333    */
1334   size_t slen = utf16_string_len_in_bytes_max (data, len);
1335   if (slen > len)
1336     len = slen;
1337
1338   char *ret = windows_utf16_to_utf8 (data, len);
1339   free (data);
1340   if (ret == NULL)
1341     return NULL;
1342
1343   return ret;
1344 }
1345
1346 static void
1347 free_strings (char **argv)
1348 {
1349   if (argv) {
1350     size_t i;
1351
1352     for (i = 0; argv[i] != NULL; ++i)
1353       free (argv[i]);
1354     free (argv);
1355   }
1356 }
1357
1358 /* Get the length of a UTF-16 format string.  Handle the string as
1359  * pairs of bytes, looking for the first \0\0 pair.
1360  */
1361 static size_t
1362 utf16_string_len_in_bytes (const char *str)
1363 {
1364   size_t ret = 0;
1365
1366   while (str[0] || str[1]) {
1367     str += 2;
1368     ret += 2;
1369   }
1370
1371   return ret;
1372 }
1373
1374 /* As for utf16_string_len_in_bytes but only read up to a maximum length. */
1375 static size_t
1376 utf16_string_len_in_bytes_max (const char *str, size_t len)
1377 {
1378   size_t ret = 0;
1379
1380   while (len > 0 && (str[0] || str[1])) {
1381     str += 2;
1382     ret += 2;
1383     len -= 2;
1384   }
1385
1386   return ret;
1387 }
1388
1389 /* http://blogs.msdn.com/oldnewthing/archive/2009/10/08/9904646.aspx */
1390 char **
1391 hivex_value_multiple_strings (hive_h *h, hive_value_h value)
1392 {
1393   hive_type t;
1394   size_t len;
1395   char *data = hivex_value_value (h, value, &t, &len);
1396
1397   if (data == NULL)
1398     return NULL;
1399
1400   if (t != hive_t_multiple_strings) {
1401     free (data);
1402     errno = EINVAL;
1403     return NULL;
1404   }
1405
1406   size_t nr_strings = 0;
1407   char **ret = malloc ((1 + nr_strings) * sizeof (char *));
1408   if (ret == NULL) {
1409     free (data);
1410     return NULL;
1411   }
1412   ret[0] = NULL;
1413
1414   char *p = data;
1415   size_t plen;
1416
1417   while (p < data + len && (plen = utf16_string_len_in_bytes (p)) > 0) {
1418     nr_strings++;
1419     char **ret2 = realloc (ret, (1 + nr_strings) * sizeof (char *));
1420     if (ret2 == NULL) {
1421       free_strings (ret);
1422       free (data);
1423       return NULL;
1424     }
1425     ret = ret2;
1426
1427     ret[nr_strings-1] = windows_utf16_to_utf8 (p, plen);
1428     ret[nr_strings] = NULL;
1429     if (ret[nr_strings-1] == NULL) {
1430       free_strings (ret);
1431       free (data);
1432       return NULL;
1433     }
1434
1435     p += plen + 2 /* skip over UTF-16 \0\0 at the end of this string */;
1436   }
1437
1438   free (data);
1439   return ret;
1440 }
1441
1442 int32_t
1443 hivex_value_dword (hive_h *h, hive_value_h value)
1444 {
1445   hive_type t;
1446   size_t len;
1447   char *data = hivex_value_value (h, value, &t, &len);
1448
1449   if (data == NULL)
1450     return -1;
1451
1452   if ((t != hive_t_dword && t != hive_t_dword_be) || len != 4) {
1453     free (data);
1454     errno = EINVAL;
1455     return -1;
1456   }
1457
1458   int32_t ret = *(int32_t*)data;
1459   free (data);
1460   if (t == hive_t_dword)        /* little endian */
1461     ret = le32toh (ret);
1462   else
1463     ret = be32toh (ret);
1464
1465   return ret;
1466 }
1467
1468 int64_t
1469 hivex_value_qword (hive_h *h, hive_value_h value)
1470 {
1471   hive_type t;
1472   size_t len;
1473   char *data = hivex_value_value (h, value, &t, &len);
1474
1475   if (data == NULL)
1476     return -1;
1477
1478   if (t != hive_t_qword || len != 8) {
1479     free (data);
1480     errno = EINVAL;
1481     return -1;
1482   }
1483
1484   int64_t ret = *(int64_t*)data;
1485   free (data);
1486   ret = le64toh (ret);          /* always little endian */
1487
1488   return ret;
1489 }
1490
1491 /*----------------------------------------------------------------------
1492  * Visiting.
1493  */
1494
1495 int
1496 hivex_visit (hive_h *h, const struct hivex_visitor *visitor, size_t len,
1497              void *opaque, int flags)
1498 {
1499   return hivex_visit_node (h, hivex_root (h), visitor, len, opaque, flags);
1500 }
1501
1502 static int hivex__visit_node (hive_h *h, hive_node_h node, const struct hivex_visitor *vtor, char *unvisited, void *opaque, int flags);
1503
1504 int
1505 hivex_visit_node (hive_h *h, hive_node_h node,
1506                   const struct hivex_visitor *visitor, size_t len, void *opaque,
1507                   int flags)
1508 {
1509   struct hivex_visitor vtor;
1510   memset (&vtor, 0, sizeof vtor);
1511
1512   /* Note that len might be larger *or smaller* than the expected size. */
1513   size_t copysize = len <= sizeof vtor ? len : sizeof vtor;
1514   memcpy (&vtor, visitor, copysize);
1515
1516   /* This bitmap records unvisited nodes, so we don't loop if the
1517    * registry contains cycles.
1518    */
1519   char *unvisited = malloc (1 + h->size / 32);
1520   if (unvisited == NULL)
1521     return -1;
1522   memcpy (unvisited, h->bitmap, 1 + h->size / 32);
1523
1524   int r = hivex__visit_node (h, node, &vtor, unvisited, opaque, flags);
1525   free (unvisited);
1526   return r;
1527 }
1528
1529 static int
1530 hivex__visit_node (hive_h *h, hive_node_h node,
1531                    const struct hivex_visitor *vtor, char *unvisited,
1532                    void *opaque, int flags)
1533 {
1534   int skip_bad = flags & HIVEX_VISIT_SKIP_BAD;
1535   char *name = NULL;
1536   hive_value_h *values = NULL;
1537   hive_node_h *children = NULL;
1538   char *key = NULL;
1539   char *str = NULL;
1540   char **strs = NULL;
1541   int i;
1542
1543   /* Return -1 on all callback errors.  However on internal errors,
1544    * check if skip_bad is set and suppress those errors if so.
1545    */
1546   int ret = -1;
1547
1548   if (!BITMAP_TST (unvisited, node)) {
1549     if (h->msglvl >= 2)
1550       fprintf (stderr, "hivex__visit_node: contains cycle: visited node 0x%zx already\n",
1551                node);
1552
1553     errno = ELOOP;
1554     return skip_bad ? 0 : -1;
1555   }
1556   BITMAP_CLR (unvisited, node);
1557
1558   name = hivex_node_name (h, node);
1559   if (!name) return skip_bad ? 0 : -1;
1560   if (vtor->node_start && vtor->node_start (h, opaque, node, name) == -1)
1561     goto error;
1562
1563   values = hivex_node_values (h, node);
1564   if (!values) {
1565     ret = skip_bad ? 0 : -1;
1566     goto error;
1567   }
1568
1569   for (i = 0; values[i] != 0; ++i) {
1570     hive_type t;
1571     size_t len;
1572
1573     if (hivex_value_type (h, values[i], &t, &len) == -1) {
1574       ret = skip_bad ? 0 : -1;
1575       goto error;
1576     }
1577
1578     key = hivex_value_key (h, values[i]);
1579     if (key == NULL) {
1580       ret = skip_bad ? 0 : -1;
1581       goto error;
1582     }
1583
1584     if (vtor->value_any) {
1585       str = hivex_value_value (h, values[i], &t, &len);
1586       if (str == NULL) {
1587         ret = skip_bad ? 0 : -1;
1588         goto error;
1589       }
1590       if (vtor->value_any (h, opaque, node, values[i], t, len, key, str) == -1)
1591         goto error;
1592       free (str); str = NULL;
1593     }
1594     else {
1595       switch (t) {
1596       case hive_t_none:
1597         str = hivex_value_value (h, values[i], &t, &len);
1598         if (str == NULL) {
1599           ret = skip_bad ? 0 : -1;
1600           goto error;
1601         }
1602         if (t != hive_t_none) {
1603           ret = skip_bad ? 0 : -1;
1604           goto error;
1605         }
1606         if (vtor->value_none &&
1607             vtor->value_none (h, opaque, node, values[i], t, len, key, str) == -1)
1608           goto error;
1609         free (str); str = NULL;
1610         break;
1611
1612       case hive_t_string:
1613       case hive_t_expand_string:
1614       case hive_t_link:
1615         str = hivex_value_string (h, values[i]);
1616         if (str == NULL) {
1617           if (errno != EILSEQ && errno != EINVAL) {
1618             ret = skip_bad ? 0 : -1;
1619             goto error;
1620           }
1621           if (vtor->value_string_invalid_utf16) {
1622             str = hivex_value_value (h, values[i], &t, &len);
1623             if (vtor->value_string_invalid_utf16 (h, opaque, node, values[i], t, len, key, str) == -1)
1624               goto error;
1625             free (str); str = NULL;
1626           }
1627           break;
1628         }
1629         if (vtor->value_string &&
1630             vtor->value_string (h, opaque, node, values[i], t, len, key, str) == -1)
1631           goto error;
1632         free (str); str = NULL;
1633         break;
1634
1635       case hive_t_dword:
1636       case hive_t_dword_be: {
1637         int32_t i32 = hivex_value_dword (h, values[i]);
1638         if (vtor->value_dword &&
1639             vtor->value_dword (h, opaque, node, values[i], t, len, key, i32) == -1)
1640           goto error;
1641         break;
1642       }
1643
1644       case hive_t_qword: {
1645         int64_t i64 = hivex_value_qword (h, values[i]);
1646         if (vtor->value_qword &&
1647             vtor->value_qword (h, opaque, node, values[i], t, len, key, i64) == -1)
1648           goto error;
1649         break;
1650       }
1651
1652       case hive_t_binary:
1653         str = hivex_value_value (h, values[i], &t, &len);
1654         if (str == NULL) {
1655           ret = skip_bad ? 0 : -1;
1656           goto error;
1657         }
1658         if (t != hive_t_binary) {
1659           ret = skip_bad ? 0 : -1;
1660           goto error;
1661         }
1662         if (vtor->value_binary &&
1663             vtor->value_binary (h, opaque, node, values[i], t, len, key, str) == -1)
1664           goto error;
1665         free (str); str = NULL;
1666         break;
1667
1668       case hive_t_multiple_strings:
1669         strs = hivex_value_multiple_strings (h, values[i]);
1670         if (strs == NULL) {
1671           if (errno != EILSEQ && errno != EINVAL) {
1672             ret = skip_bad ? 0 : -1;
1673             goto error;
1674           }
1675           if (vtor->value_string_invalid_utf16) {
1676             str = hivex_value_value (h, values[i], &t, &len);
1677             if (vtor->value_string_invalid_utf16 (h, opaque, node, values[i], t, len, key, str) == -1)
1678               goto error;
1679             free (str); str = NULL;
1680           }
1681           break;
1682         }
1683         if (vtor->value_multiple_strings &&
1684             vtor->value_multiple_strings (h, opaque, node, values[i], t, len, key, strs) == -1)
1685           goto error;
1686         free_strings (strs); strs = NULL;
1687         break;
1688
1689       case hive_t_resource_list:
1690       case hive_t_full_resource_description:
1691       case hive_t_resource_requirements_list:
1692       default:
1693         str = hivex_value_value (h, values[i], &t, &len);
1694         if (str == NULL) {
1695           ret = skip_bad ? 0 : -1;
1696           goto error;
1697         }
1698         if (vtor->value_other &&
1699             vtor->value_other (h, opaque, node, values[i], t, len, key, str) == -1)
1700           goto error;
1701         free (str); str = NULL;
1702         break;
1703       }
1704     }
1705
1706     free (key); key = NULL;
1707   }
1708
1709   children = hivex_node_children (h, node);
1710   if (children == NULL) {
1711     ret = skip_bad ? 0 : -1;
1712     goto error;
1713   }
1714
1715   for (i = 0; children[i] != 0; ++i) {
1716     if (h->msglvl >= 2)
1717       fprintf (stderr, "hivex__visit_node: %s: visiting subkey %d (0x%zx)\n",
1718                name, i, children[i]);
1719
1720     if (hivex__visit_node (h, children[i], vtor, unvisited, opaque, flags) == -1)
1721       goto error;
1722   }
1723
1724   if (vtor->node_end && vtor->node_end (h, opaque, node, name) == -1)
1725     goto error;
1726
1727   ret = 0;
1728
1729  error:
1730   free (name);
1731   free (values);
1732   free (children);
1733   free (key);
1734   free (str);
1735   free_strings (strs);
1736   return ret;
1737 }
1738
1739 /*----------------------------------------------------------------------
1740  * Writing.
1741  */
1742
1743 /* Allocate an hbin (page), extending the malloc'd space if necessary,
1744  * and updating the hive handle fields (but NOT the hive disk header
1745  * -- the hive disk header is updated when we commit).  This function
1746  * also extends the bitmap if necessary.
1747  *
1748  * 'allocation_hint' is the size of the block allocation we would like
1749  * to make.  Normally registry blocks are very small (avg 50 bytes)
1750  * and are contained in standard-sized pages (4KB), but the registry
1751  * can support blocks which are larger than a standard page, in which
1752  * case it creates a page of 8KB, 12KB etc.
1753  *
1754  * Returns:
1755  * > 0 : offset of first usable byte of new page (after page header)
1756  * 0   : error (errno set)
1757  */
1758 static size_t
1759 allocate_page (hive_h *h, size_t allocation_hint)
1760 {
1761   /* In almost all cases this will be 1. */
1762   size_t nr_4k_pages =
1763     1 + (allocation_hint + sizeof (struct ntreg_hbin_page) - 1) / 4096;
1764   assert (nr_4k_pages >= 1);
1765
1766   /* 'extend' is the number of bytes to extend the file by.  Note that
1767    * hives found in the wild often contain slack between 'endpages'
1768    * and the actual end of the file, so we don't always need to make
1769    * the file larger.
1770    */
1771   ssize_t extend = h->endpages + nr_4k_pages * 4096 - h->size;
1772
1773   if (h->msglvl >= 2) {
1774     fprintf (stderr, "allocate_page: current endpages = 0x%zx, current size = 0x%zx\n",
1775              h->endpages, h->size);
1776     fprintf (stderr, "allocate_page: extending file by %zd bytes (<= 0 if no extension)\n",
1777              extend);
1778   }
1779
1780   if (extend > 0) {
1781     size_t oldsize = h->size;
1782     size_t newsize = h->size + extend;
1783     char *newaddr = realloc (h->addr, newsize);
1784     if (newaddr == NULL)
1785       return 0;
1786
1787     size_t oldbitmapsize = 1 + oldsize / 32;
1788     size_t newbitmapsize = 1 + newsize / 32;
1789     char *newbitmap = realloc (h->bitmap, newbitmapsize);
1790     if (newbitmap == NULL) {
1791       free (newaddr);
1792       return 0;
1793     }
1794
1795     h->addr = newaddr;
1796     h->size = newsize;
1797     h->bitmap = newbitmap;
1798
1799     memset (h->addr + oldsize, 0, newsize - oldsize);
1800     memset (h->bitmap + oldbitmapsize, 0, newbitmapsize - oldbitmapsize);
1801   }
1802
1803   size_t offset = h->endpages;
1804   h->endpages += nr_4k_pages * 4096;
1805
1806   if (h->msglvl >= 2)
1807     fprintf (stderr, "allocate_page: new endpages = 0x%zx, new size = 0x%zx\n",
1808              h->endpages, h->size);
1809
1810   /* Write the hbin header. */
1811   struct ntreg_hbin_page *page =
1812     (struct ntreg_hbin_page *) (h->addr + offset);
1813   page->magic[0] = 'h';
1814   page->magic[1] = 'b';
1815   page->magic[2] = 'i';
1816   page->magic[3] = 'n';
1817   page->offset_first = htole32 (offset - 0x1000);
1818   page->page_size = htole32 (nr_4k_pages * 4096);
1819   memset (page->unknown, 0, sizeof (page->unknown));
1820
1821   if (h->msglvl >= 2)
1822     fprintf (stderr, "allocate_page: new page at 0x%zx\n", offset);
1823
1824   /* Offset of first usable byte after the header. */
1825   return offset + sizeof (struct ntreg_hbin_page);
1826 }
1827
1828 /* Allocate a single block, first allocating an hbin (page) at the end
1829  * of the current file if necessary.  NB. To keep the implementation
1830  * simple and more likely to be correct, we do not reuse existing free
1831  * blocks.
1832  *
1833  * seg_len is the size of the block (this INCLUDES the block header).
1834  * The header of the block is initialized to -seg_len (negative to
1835  * indicate used).  id[2] is the block ID (type), eg. "nk" for nk-
1836  * record.  The block bitmap is updated to show this block as valid.
1837  * The rest of the contents of the block will be zero.
1838  *
1839  * **NB** Because allocate_block may reallocate the memory, all
1840  * pointers into the memory become potentially invalid.  I really
1841  * love writing in C, can't you tell?
1842  *
1843  * Returns:
1844  * > 0 : offset of new block
1845  * 0   : error (errno set)
1846  */
1847 static size_t
1848 allocate_block (hive_h *h, size_t seg_len, const char id[2])
1849 {
1850   if (!h->writable) {
1851     errno = EROFS;
1852     return 0;
1853   }
1854
1855   if (seg_len < 4) {
1856     /* The caller probably forgot to include the header.  Note that
1857      * value lists have no ID field, so seg_len == 4 would be possible
1858      * for them, albeit unusual.
1859      */
1860     if (h->msglvl >= 2)
1861       fprintf (stderr, "allocate_block: refusing too small allocation (%zu), returning ERANGE\n",
1862                seg_len);
1863     errno = ERANGE;
1864     return 0;
1865   }
1866
1867   /* Refuse really large allocations. */
1868   if (seg_len > HIVEX_MAX_ALLOCATION) {
1869     if (h->msglvl >= 2)
1870       fprintf (stderr, "allocate_block: refusing large allocation (%zu), returning ERANGE\n",
1871                seg_len);
1872     errno = ERANGE;
1873     return 0;
1874   }
1875
1876   /* Round up allocation to multiple of 8 bytes.  All blocks must be
1877    * on an 8 byte boundary.
1878    */
1879   seg_len = (seg_len + 7) & ~7;
1880
1881   /* Allocate a new page if necessary. */
1882   if (h->endblocks == 0 || h->endblocks + seg_len > h->endpages) {
1883     size_t newendblocks = allocate_page (h, seg_len);
1884     if (newendblocks == 0)
1885       return 0;
1886     h->endblocks = newendblocks;
1887   }
1888
1889   size_t offset = h->endblocks;
1890
1891   if (h->msglvl >= 2)
1892     fprintf (stderr, "allocate_block: new block at 0x%zx, size %zu\n",
1893              offset, seg_len);
1894
1895   struct ntreg_hbin_block *blockhdr =
1896     (struct ntreg_hbin_block *) (h->addr + offset);
1897
1898   memset (blockhdr, 0, seg_len);
1899
1900   blockhdr->seg_len = htole32 (- (int32_t) seg_len);
1901   if (id[0] && id[1] && seg_len >= sizeof (struct ntreg_hbin_block)) {
1902     blockhdr->id[0] = id[0];
1903     blockhdr->id[1] = id[1];
1904   }
1905
1906   BITMAP_SET (h->bitmap, offset);
1907
1908   h->endblocks += seg_len;
1909
1910   /* If there is space after the last block in the last page, then we
1911    * have to put a dummy free block header here to mark the rest of
1912    * the page as free.
1913    */
1914   ssize_t rem = h->endpages - h->endblocks;
1915   if (rem > 0) {
1916     if (h->msglvl >= 2)
1917       fprintf (stderr, "allocate_block: marking remainder of page free starting at 0x%zx, size %zd\n",
1918                h->endblocks, rem);
1919
1920     assert (rem >= 4);
1921
1922     blockhdr = (struct ntreg_hbin_block *) (h->addr + h->endblocks);
1923     blockhdr->seg_len = htole32 ((int32_t) rem);
1924   }
1925
1926   return offset;
1927 }
1928
1929 /* 'offset' must point to a valid, used block.  This function marks
1930  * the block unused (by updating the seg_len field) and invalidates
1931  * the bitmap.  It does NOT do this recursively, so to avoid creating
1932  * unreachable used blocks, callers may have to recurse over the hive
1933  * structures.  Also callers must ensure there are no references to
1934  * this block from other parts of the hive.
1935  */
1936 static void
1937 mark_block_unused (hive_h *h, size_t offset)
1938 {
1939   assert (h->writable);
1940   assert (IS_VALID_BLOCK (h, offset));
1941
1942   if (h->msglvl >= 2)
1943     fprintf (stderr, "mark_block_unused: marking 0x%zx unused\n", offset);
1944
1945   struct ntreg_hbin_block *blockhdr =
1946     (struct ntreg_hbin_block *) (h->addr + offset);
1947
1948   size_t seg_len = block_len (h, offset, NULL);
1949   blockhdr->seg_len = htole32 (seg_len);
1950
1951   BITMAP_CLR (h->bitmap, offset);
1952 }
1953
1954 /* Delete all existing values at this node. */
1955 static int
1956 delete_values (hive_h *h, hive_node_h node)
1957 {
1958   assert (h->writable);
1959
1960   hive_value_h *values;
1961   size_t *blocks;
1962   if (get_values (h, node, &values, &blocks) == -1)
1963     return -1;
1964
1965   size_t i;
1966   for (i = 0; blocks[i] != 0; ++i)
1967     mark_block_unused (h, blocks[i]);
1968
1969   free (blocks);
1970
1971   for (i = 0; values[i] != 0; ++i) {
1972     struct ntreg_vk_record *vk =
1973       (struct ntreg_vk_record *) (h->addr + values[i]);
1974
1975     size_t len;
1976     int is_inline;
1977     len = le32toh (vk->data_len);
1978     is_inline = !!(len & 0x80000000); /* top bit indicates is inline */
1979     len &= 0x7fffffff;
1980
1981     if (!is_inline) {           /* non-inline, so remove data block */
1982       size_t data_offset = le32toh (vk->data_offset);
1983       data_offset += 0x1000;
1984       mark_block_unused (h, data_offset);
1985     }
1986
1987     /* remove vk record */
1988     mark_block_unused (h, values[i]);
1989   }
1990
1991   free (values);
1992
1993   struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
1994   nk->nr_values = htole32 (0);
1995   nk->vallist = htole32 (0xffffffff);
1996
1997   return 0;
1998 }
1999
2000 int
2001 hivex_commit (hive_h *h, const char *filename, int flags)
2002 {
2003   if (flags != 0) {
2004     errno = EINVAL;
2005     return -1;
2006   }
2007
2008   if (!h->writable) {
2009     errno = EROFS;
2010     return -1;
2011   }
2012
2013   filename = filename ? : h->filename;
2014   int fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
2015   if (fd == -1)
2016     return -1;
2017
2018   /* Update the header fields. */
2019   uint32_t sequence = le32toh (h->hdr->sequence1);
2020   sequence++;
2021   h->hdr->sequence1 = htole32 (sequence);
2022   h->hdr->sequence2 = htole32 (sequence);
2023   /* XXX Ought to update h->hdr->last_modified. */
2024   h->hdr->blocks = htole32 (h->endpages - 0x1000);
2025
2026   /* Recompute header checksum. */
2027   uint32_t sum = header_checksum (h);
2028   h->hdr->csum = htole32 (sum);
2029
2030   if (h->msglvl >= 2)
2031     fprintf (stderr, "hivex_commit: new header checksum: 0x%x\n", sum);
2032
2033   if (full_write (fd, h->addr, h->size) != h->size) {
2034     int err = errno;
2035     close (fd);
2036     errno = err;
2037     return -1;
2038   }
2039
2040   if (close (fd) == -1)
2041     return -1;
2042
2043   return 0;
2044 }
2045
2046 /* Calculate the hash for a lf or lh record offset.
2047  */
2048 static void
2049 calc_hash (const char *type, const char *name, char *ret)
2050 {
2051   size_t len = strlen (name);
2052
2053   if (STRPREFIX (type, "lf"))
2054     /* Old-style, not used in current registries. */
2055     memcpy (ret, name, len < 4 ? len : 4);
2056   else {
2057     /* New-style for lh-records. */
2058     size_t i, c;
2059     uint32_t h = 0;
2060     for (i = 0; i < len; ++i) {
2061       c = c_toupper (name[i]);
2062       h *= 37;
2063       h += c;
2064     }
2065     *((uint32_t *) ret) = htole32 (h);
2066   }
2067 }
2068
2069 /* Create a completely new lh-record containing just the single node. */
2070 static size_t
2071 new_lh_record (hive_h *h, const char *name, hive_node_h node)
2072 {
2073   static const char id[2] = { 'l', 'h' };
2074   size_t seg_len = sizeof (struct ntreg_lf_record);
2075   size_t offset = allocate_block (h, seg_len, id);
2076   if (offset == 0)
2077     return 0;
2078
2079   struct ntreg_lf_record *lh = (struct ntreg_lf_record *) (h->addr + offset);
2080   lh->nr_keys = htole16 (1);
2081   lh->keys[0].offset = htole32 (node - 0x1000);
2082   calc_hash ("lh", name, lh->keys[0].hash);
2083
2084   return offset;
2085 }
2086
2087 /* Insert node into existing lf/lh-record at position.
2088  * This allocates a new record and marks the old one as unused.
2089  */
2090 static size_t
2091 insert_lf_record (hive_h *h, size_t old_offs, size_t posn,
2092                   const char *name, hive_node_h node)
2093 {
2094   assert (IS_VALID_BLOCK (h, old_offs));
2095
2096   /* Work around C stupidity.
2097    * http://www.redhat.com/archives/libguestfs/2010-February/msg00056.html
2098    */
2099   int test = BLOCK_ID_EQ (h, old_offs, "lf") || BLOCK_ID_EQ (h, old_offs, "lh");
2100   assert (test);
2101
2102   struct ntreg_lf_record *old_lf =
2103     (struct ntreg_lf_record *) (h->addr + old_offs);
2104   size_t nr_keys = le16toh (old_lf->nr_keys);
2105
2106   nr_keys++; /* in new record ... */
2107
2108   size_t seg_len = sizeof (struct ntreg_lf_record) + (nr_keys-1) * 8;
2109
2110   /* Copy the old_lf->id in case it moves during allocate_block. */
2111   char id[2];
2112   memcpy (id, old_lf->id, sizeof id);
2113
2114   size_t new_offs = allocate_block (h, seg_len, id);
2115   if (new_offs == 0)
2116     return 0;
2117
2118   /* old_lf could have been invalidated by allocate_block. */
2119   old_lf = (struct ntreg_lf_record *) (h->addr + old_offs);
2120
2121   struct ntreg_lf_record *new_lf =
2122     (struct ntreg_lf_record *) (h->addr + new_offs);
2123   new_lf->nr_keys = htole16 (nr_keys);
2124
2125   /* Copy the keys until we reach posn, insert the new key there, then
2126    * copy the remaining keys.
2127    */
2128   size_t i;
2129   for (i = 0; i < posn; ++i)
2130     new_lf->keys[i] = old_lf->keys[i];
2131
2132   new_lf->keys[i].offset = htole32 (node - 0x1000);
2133   calc_hash (new_lf->id, name, new_lf->keys[i].hash);
2134
2135   for (i = posn+1; i < nr_keys; ++i)
2136     new_lf->keys[i] = old_lf->keys[i-1];
2137
2138   /* Old block is unused, return new block. */
2139   mark_block_unused (h, old_offs);
2140   return new_offs;
2141 }
2142
2143 /* Compare name with name in nk-record. */
2144 static int
2145 compare_name_with_nk_name (hive_h *h, const char *name, hive_node_h nk_offs)
2146 {
2147   assert (IS_VALID_BLOCK (h, nk_offs));
2148   assert (BLOCK_ID_EQ (h, nk_offs, "nk"));
2149
2150   /* Name in nk is not necessarily nul-terminated. */
2151   char *nname = hivex_node_name (h, nk_offs);
2152
2153   /* Unfortunately we don't have a way to return errors here. */
2154   if (!nname) {
2155     perror ("compare_name_with_nk_name");
2156     return 0;
2157   }
2158
2159   int r = strcasecmp (name, nname);
2160   free (nname);
2161
2162   return r;
2163 }
2164
2165 hive_node_h
2166 hivex_node_add_child (hive_h *h, hive_node_h parent, const char *name)
2167 {
2168   if (!h->writable) {
2169     errno = EROFS;
2170     return 0;
2171   }
2172
2173   if (!IS_VALID_BLOCK (h, parent) || !BLOCK_ID_EQ (h, parent, "nk")) {
2174     errno = EINVAL;
2175     return 0;
2176   }
2177
2178   if (name == NULL || strlen (name) == 0) {
2179     errno = EINVAL;
2180     return 0;
2181   }
2182
2183   if (hivex_node_get_child (h, parent, name) != 0) {
2184     errno = EEXIST;
2185     return 0;
2186   }
2187
2188   /* Create the new nk-record. */
2189   static const char nk_id[2] = { 'n', 'k' };
2190   size_t seg_len = sizeof (struct ntreg_nk_record) + strlen (name);
2191   hive_node_h node = allocate_block (h, seg_len, nk_id);
2192   if (node == 0)
2193     return 0;
2194
2195   if (h->msglvl >= 2)
2196     fprintf (stderr, "hivex_node_add_child: allocated new nk-record for child at 0x%zx\n", node);
2197
2198   struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
2199   nk->flags = htole16 (0x0020); /* key is ASCII. */
2200   nk->parent = htole32 (parent - 0x1000);
2201   nk->subkey_lf = htole32 (0xffffffff);
2202   nk->subkey_lf_volatile = htole32 (0xffffffff);
2203   nk->vallist = htole32 (0xffffffff);
2204   nk->classname = htole32 (0xffffffff);
2205   nk->name_len = htole16 (strlen (name));
2206   strcpy (nk->name, name);
2207
2208   /* Inherit parent sk. */
2209   struct ntreg_nk_record *parent_nk =
2210     (struct ntreg_nk_record *) (h->addr + parent);
2211   size_t parent_sk_offset = le32toh (parent_nk->sk);
2212   parent_sk_offset += 0x1000;
2213   if (!IS_VALID_BLOCK (h, parent_sk_offset) ||
2214       !BLOCK_ID_EQ (h, parent_sk_offset, "sk")) {
2215     if (h->msglvl >= 2)
2216       fprintf (stderr, "hivex_node_add_child: returning EFAULT because parent sk is not a valid block (%zu)\n",
2217                parent_sk_offset);
2218     errno = EFAULT;
2219     return 0;
2220   }
2221   struct ntreg_sk_record *sk =
2222     (struct ntreg_sk_record *) (h->addr + parent_sk_offset);
2223   sk->refcount = htole32 (le32toh (sk->refcount) + 1);
2224   nk->sk = htole32 (parent_sk_offset - 0x1000);
2225
2226   /* Inherit parent timestamp. */
2227   memcpy (nk->timestamp, parent_nk->timestamp, sizeof (parent_nk->timestamp));
2228
2229   /* What I found out the hard way (not documented anywhere): the
2230    * subkeys in lh-records must be kept sorted.  If you just add a
2231    * subkey in a non-sorted position (eg. just add it at the end) then
2232    * Windows won't see the subkey _and_ Windows will corrupt the hive
2233    * itself when it modifies or saves it.
2234    *
2235    * So use get_children() to get a list of intermediate
2236    * lf/lh-records.  get_children() returns these in reading order
2237    * (which is sorted), so we look for the lf/lh-records in sequence
2238    * until we find the key name just after the one we are inserting,
2239    * and we insert the subkey just before it.
2240    *
2241    * The only other case is the no-subkeys case, where we have to
2242    * create a brand new lh-record.
2243    */
2244   hive_node_h *unused;
2245   size_t *blocks;
2246
2247   if (get_children (h, parent, &unused, &blocks, 0) == -1)
2248     return 0;
2249   free (unused);
2250
2251   size_t i, j;
2252   size_t nr_subkeys_in_parent_nk = le32toh (parent_nk->nr_subkeys);
2253   if (nr_subkeys_in_parent_nk == 0) { /* No subkeys case. */
2254     /* Free up any existing intermediate blocks. */
2255     for (i = 0; blocks[i] != 0; ++i)
2256       mark_block_unused (h, blocks[i]);
2257     size_t lh_offs = new_lh_record (h, name, node);
2258     if (lh_offs == 0) {
2259       free (blocks);
2260       return 0;
2261     }
2262
2263     /* Recalculate pointers that could have been invalidated by
2264      * previous call to allocate_block (via new_lh_record).
2265      */
2266     nk = (struct ntreg_nk_record *) (h->addr + node);
2267     parent_nk = (struct ntreg_nk_record *) (h->addr + parent);
2268
2269     if (h->msglvl >= 2)
2270       fprintf (stderr, "hivex_node_add_child: no keys, allocated new lh-record at 0x%zx\n", lh_offs);
2271
2272     parent_nk->subkey_lf = htole32 (lh_offs - 0x1000);
2273   }
2274   else {                        /* Insert subkeys case. */
2275     size_t old_offs = 0, new_offs = 0;
2276     struct ntreg_lf_record *old_lf = NULL;
2277
2278     /* Find lf/lh key name just after the one we are inserting. */
2279     for (i = 0; blocks[i] != 0; ++i) {
2280       if (BLOCK_ID_EQ (h, blocks[i], "lf") ||
2281           BLOCK_ID_EQ (h, blocks[i], "lh")) {
2282         old_offs = blocks[i];
2283         old_lf = (struct ntreg_lf_record *) (h->addr + old_offs);
2284         for (j = 0; j < le16toh (old_lf->nr_keys); ++j) {
2285           hive_node_h nk_offs = le32toh (old_lf->keys[j].offset);
2286           nk_offs += 0x1000;
2287           if (compare_name_with_nk_name (h, name, nk_offs) < 0)
2288             goto insert_it;
2289         }
2290       }
2291     }
2292
2293     /* Insert it at the end.
2294      * old_offs points to the last lf record, set j.
2295      */
2296     assert (old_offs != 0);   /* should never happen if nr_subkeys > 0 */
2297     j = le16toh (old_lf->nr_keys);
2298
2299     /* Insert it. */
2300   insert_it:
2301     if (h->msglvl >= 2)
2302       fprintf (stderr, "hivex_node_add_child: insert key in existing lh-record at 0x%zx, posn %zu\n", old_offs, j);
2303
2304     new_offs = insert_lf_record (h, old_offs, j, name, node);
2305     if (new_offs == 0) {
2306       free (blocks);
2307       return 0;
2308     }
2309
2310     /* Recalculate pointers that could have been invalidated by
2311      * previous call to allocate_block (via insert_lf_record).
2312      */
2313     nk = (struct ntreg_nk_record *) (h->addr + node);
2314     parent_nk = (struct ntreg_nk_record *) (h->addr + parent);
2315
2316     if (h->msglvl >= 2)
2317       fprintf (stderr, "hivex_node_add_child: new lh-record at 0x%zx\n",
2318                new_offs);
2319
2320     /* If the lf/lh-record was directly referenced by the parent nk,
2321      * then update the parent nk.
2322      */
2323     if (le32toh (parent_nk->subkey_lf) + 0x1000 == old_offs)
2324       parent_nk->subkey_lf = htole32 (new_offs - 0x1000);
2325     /* Else we have to look for the intermediate ri-record and update
2326      * that in-place.
2327      */
2328     else {
2329       for (i = 0; blocks[i] != 0; ++i) {
2330         if (BLOCK_ID_EQ (h, blocks[i], "ri")) {
2331           struct ntreg_ri_record *ri =
2332             (struct ntreg_ri_record *) (h->addr + blocks[i]);
2333           for (j = 0; j < le16toh (ri->nr_offsets); ++j)
2334             if (le32toh (ri->offset[j] + 0x1000) == old_offs) {
2335               ri->offset[j] = htole32 (new_offs - 0x1000);
2336               goto found_it;
2337             }
2338         }
2339       }
2340
2341       /* Not found ..  This is an internal error. */
2342       if (h->msglvl >= 2)
2343         fprintf (stderr, "hivex_node_add_child: returning ENOTSUP because could not find ri->lf link\n");
2344       errno = ENOTSUP;
2345       free (blocks);
2346       return 0;
2347
2348     found_it:
2349       ;
2350     }
2351   }
2352
2353   free (blocks);
2354
2355   /* Update nr_subkeys in parent nk. */
2356   nr_subkeys_in_parent_nk++;
2357   parent_nk->nr_subkeys = htole32 (nr_subkeys_in_parent_nk);
2358
2359   /* Update max_subkey_name_len in parent nk. */
2360   uint16_t max = le16toh (parent_nk->max_subkey_name_len);
2361   if (max < strlen (name) * 2)  /* *2 because "recoded" in UTF16-LE. */
2362     parent_nk->max_subkey_name_len = htole16 (strlen (name) * 2);
2363
2364   return node;
2365 }
2366
2367 /* Decrement the refcount of an sk-record, and if it reaches zero,
2368  * unlink it from the chain and delete it.
2369  */
2370 static int
2371 delete_sk (hive_h *h, size_t sk_offset)
2372 {
2373   if (!IS_VALID_BLOCK (h, sk_offset) || !BLOCK_ID_EQ (h, sk_offset, "sk")) {
2374     if (h->msglvl >= 2)
2375       fprintf (stderr, "delete_sk: not an sk record: 0x%zx\n", sk_offset);
2376     errno = EFAULT;
2377     return -1;
2378   }
2379
2380   struct ntreg_sk_record *sk = (struct ntreg_sk_record *) (h->addr + sk_offset);
2381
2382   if (sk->refcount == 0) {
2383     if (h->msglvl >= 2)
2384       fprintf (stderr, "delete_sk: sk record already has refcount 0: 0x%zx\n",
2385                sk_offset);
2386     errno = EINVAL;
2387     return -1;
2388   }
2389
2390   sk->refcount--;
2391
2392   if (sk->refcount == 0) {
2393     size_t sk_prev_offset = sk->sk_prev;
2394     sk_prev_offset += 0x1000;
2395
2396     size_t sk_next_offset = sk->sk_next;
2397     sk_next_offset += 0x1000;
2398
2399     /* Update sk_prev/sk_next SKs, unless they both point back to this
2400      * cell in which case we are deleting the last SK.
2401      */
2402     if (sk_prev_offset != sk_offset && sk_next_offset != sk_offset) {
2403       struct ntreg_sk_record *sk_prev =
2404         (struct ntreg_sk_record *) (h->addr + sk_prev_offset);
2405       struct ntreg_sk_record *sk_next =
2406         (struct ntreg_sk_record *) (h->addr + sk_next_offset);
2407
2408       sk_prev->sk_next = htole32 (sk_next_offset - 0x1000);
2409       sk_next->sk_prev = htole32 (sk_prev_offset - 0x1000);
2410     }
2411
2412     /* Refcount is zero so really delete this block. */
2413     mark_block_unused (h, sk_offset);
2414   }
2415
2416   return 0;
2417 }
2418
2419 /* Callback from hivex_node_delete_child which is called to delete a
2420  * node AFTER its subnodes have been visited.  The subnodes have been
2421  * deleted but we still have to delete any lf/lh/li/ri records and the
2422  * value list block and values, followed by deleting the node itself.
2423  */
2424 static int
2425 delete_node (hive_h *h, void *opaque, hive_node_h node, const char *name)
2426 {
2427   /* Get the intermediate blocks.  The subkeys have already been
2428    * deleted by this point, so tell get_children() not to check for
2429    * validity of the nk-records.
2430    */
2431   hive_node_h *unused;
2432   size_t *blocks;
2433   if (get_children (h, node, &unused, &blocks, GET_CHILDREN_NO_CHECK_NK) == -1)
2434     return -1;
2435   free (unused);
2436
2437   /* We don't care what's in these intermediate blocks, so we can just
2438    * delete them unconditionally.
2439    */
2440   size_t i;
2441   for (i = 0; blocks[i] != 0; ++i)
2442     mark_block_unused (h, blocks[i]);
2443
2444   free (blocks);
2445
2446   /* Delete the values in the node. */
2447   if (delete_values (h, node) == -1)
2448     return -1;
2449
2450   struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
2451
2452   /* If the NK references an SK, delete it. */
2453   size_t sk_offs = le32toh (nk->sk);
2454   if (sk_offs != 0xffffffff) {
2455     sk_offs += 0x1000;
2456     if (delete_sk (h, sk_offs) == -1)
2457       return -1;
2458     nk->sk = htole32 (0xffffffff);
2459   }
2460
2461   /* If the NK references a classname, delete it. */
2462   size_t cl_offs = le32toh (nk->classname);
2463   if (cl_offs != 0xffffffff) {
2464     cl_offs += 0x1000;
2465     mark_block_unused (h, cl_offs);
2466     nk->classname = htole32 (0xffffffff);
2467   }
2468
2469   /* Delete the node itself. */
2470   mark_block_unused (h, node);
2471
2472   return 0;
2473 }
2474
2475 int
2476 hivex_node_delete_child (hive_h *h, hive_node_h node)
2477 {
2478   if (!h->writable) {
2479     errno = EROFS;
2480     return -1;
2481   }
2482
2483   if (!IS_VALID_BLOCK (h, node) || !BLOCK_ID_EQ (h, node, "nk")) {
2484     errno = EINVAL;
2485     return -1;
2486   }
2487
2488   if (node == hivex_root (h)) {
2489     if (h->msglvl >= 2)
2490       fprintf (stderr, "hivex_node_delete_child: cannot delete root node\n");
2491     errno = EINVAL;
2492     return -1;
2493   }
2494
2495   hive_node_h parent = hivex_node_parent (h, node);
2496   if (parent == 0)
2497     return -1;
2498
2499   /* Delete node and all its children and values recursively. */
2500   static const struct hivex_visitor visitor = { .node_end = delete_node };
2501   if (hivex_visit_node (h, node, &visitor, sizeof visitor, NULL, 0) == -1)
2502     return -1;
2503
2504   /* Delete the link from parent to child.  We need to find the lf/lh
2505    * record which contains the offset and remove the offset from that
2506    * record, then decrement the element count in that record, and
2507    * decrement the overall number of subkeys stored in the parent
2508    * node.
2509    */
2510   hive_node_h *unused;
2511   size_t *blocks;
2512   if (get_children (h, parent, &unused, &blocks, GET_CHILDREN_NO_CHECK_NK)== -1)
2513     return -1;
2514   free (unused);
2515
2516   size_t i, j;
2517   for (i = 0; blocks[i] != 0; ++i) {
2518     struct ntreg_hbin_block *block =
2519       (struct ntreg_hbin_block *) (h->addr + blocks[i]);
2520
2521     if (block->id[0] == 'l' && (block->id[1] == 'f' || block->id[1] == 'h')) {
2522       struct ntreg_lf_record *lf = (struct ntreg_lf_record *) block;
2523
2524       size_t nr_subkeys_in_lf = le16toh (lf->nr_keys);
2525
2526       for (j = 0; j < nr_subkeys_in_lf; ++j)
2527         if (le32toh (lf->keys[j].offset) + 0x1000 == node) {
2528           for (; j < nr_subkeys_in_lf - 1; ++j)
2529             memcpy (&lf->keys[j], &lf->keys[j+1], sizeof (lf->keys[j]));
2530           lf->nr_keys = htole16 (nr_subkeys_in_lf - 1);
2531           goto found;
2532         }
2533     }
2534   }
2535   if (h->msglvl >= 2)
2536     fprintf (stderr, "hivex_node_delete_child: could not find parent to child link\n");
2537   errno = ENOTSUP;
2538   return -1;
2539
2540  found:;
2541   struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + parent);
2542   size_t nr_subkeys_in_nk = le32toh (nk->nr_subkeys);
2543   nk->nr_subkeys = htole32 (nr_subkeys_in_nk - 1);
2544
2545   if (h->msglvl >= 2)
2546     fprintf (stderr, "hivex_node_delete_child: updating nr_subkeys in parent 0x%zx to %zu\n",
2547              parent, nr_subkeys_in_nk);
2548
2549   return 0;
2550 }
2551
2552 int
2553 hivex_node_set_values (hive_h *h, hive_node_h node,
2554                        size_t nr_values, const hive_set_value *values,
2555                        int flags)
2556 {
2557   if (!h->writable) {
2558     errno = EROFS;
2559     return -1;
2560   }
2561
2562   if (!IS_VALID_BLOCK (h, node) || !BLOCK_ID_EQ (h, node, "nk")) {
2563     errno = EINVAL;
2564     return -1;
2565   }
2566
2567   /* Delete all existing values. */
2568   if (delete_values (h, node) == -1)
2569     return -1;
2570
2571   if (nr_values == 0)
2572     return 0;
2573
2574   /* Allocate value list node.  Value lists have no id field. */
2575   static const char nul_id[2] = { 0, 0 };
2576   size_t seg_len =
2577     sizeof (struct ntreg_value_list) + (nr_values - 1) * sizeof (uint32_t);
2578   size_t vallist_offs = allocate_block (h, seg_len, nul_id);
2579   if (vallist_offs == 0)
2580     return -1;
2581
2582   struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
2583   nk->nr_values = htole32 (nr_values);
2584   nk->vallist = htole32 (vallist_offs - 0x1000);
2585
2586   struct ntreg_value_list *vallist =
2587     (struct ntreg_value_list *) (h->addr + vallist_offs);
2588
2589   size_t i;
2590   for (i = 0; i < nr_values; ++i) {
2591     /* Allocate vk record to store this (key, value) pair. */
2592     static const char vk_id[2] = { 'v', 'k' };
2593     seg_len = sizeof (struct ntreg_vk_record) + strlen (values[i].key);
2594     size_t vk_offs = allocate_block (h, seg_len, vk_id);
2595     if (vk_offs == 0)
2596       return -1;
2597
2598     /* Recalculate pointers that could have been invalidated by
2599      * previous call to allocate_block.
2600      */
2601     nk = (struct ntreg_nk_record *) (h->addr + node);
2602     vallist = (struct ntreg_value_list *) (h->addr + vallist_offs);
2603
2604     vallist->offset[i] = htole32 (vk_offs - 0x1000);
2605
2606     struct ntreg_vk_record *vk = (struct ntreg_vk_record *) (h->addr + vk_offs);
2607     size_t name_len = strlen (values[i].key);
2608     vk->name_len = htole16 (name_len);
2609     strcpy (vk->name, values[i].key);
2610     vk->data_type = htole32 (values[i].t);
2611     uint32_t len = values[i].len;
2612     if (len <= 4)               /* store it inline => set MSB flag */
2613       len |= 0x80000000;
2614     vk->data_len = htole32 (len);
2615     vk->flags = name_len == 0 ? 0 : 1;
2616
2617     if (values[i].len <= 4)     /* store it inline */
2618       memcpy (&vk->data_offset, values[i].value, values[i].len);
2619     else {
2620       size_t offs = allocate_block (h, values[i].len + 4, nul_id);
2621       if (offs == 0)
2622         return -1;
2623
2624       /* Recalculate pointers that could have been invalidated by
2625        * previous call to allocate_block.
2626        */
2627       nk = (struct ntreg_nk_record *) (h->addr + node);
2628       vallist = (struct ntreg_value_list *) (h->addr + vallist_offs);
2629       vk = (struct ntreg_vk_record *) (h->addr + vk_offs);
2630
2631       memcpy (h->addr + offs + 4, values[i].value, values[i].len);
2632       vk->data_offset = htole32 (offs - 0x1000);
2633     }
2634
2635     if (name_len * 2 > le32toh (nk->max_vk_name_len))
2636       /* * 2 for UTF16-LE "reencoding" */
2637       nk->max_vk_name_len = htole32 (name_len * 2);
2638     if (values[i].len > le32toh (nk->max_vk_data_len))
2639       nk->max_vk_data_len = htole32 (values[i].len);
2640   }
2641
2642   return 0;
2643 }
2644
2645 int
2646 hivex_node_set_value (hive_h *h, hive_node_h node,
2647                       const hive_set_value *val, int flags)
2648 {
2649   hive_value_h *prev_values = hivex_node_values (h, node);
2650   if (prev_values == NULL)
2651     return -1;
2652
2653   int retval = -1;
2654
2655   size_t nr_values = 0;
2656   for (hive_value_h *itr = prev_values; *itr != 0; ++itr)
2657     ++nr_values;
2658
2659   hive_set_value *values = malloc ((nr_values + 1) * (sizeof (hive_set_value)));
2660   if (values == NULL)
2661     goto leave_prev_values;
2662
2663   int alloc_ct = 0;
2664   int idx_of_val = -1;
2665   hive_value_h *prev_val;
2666   for (prev_val = prev_values; *prev_val != 0; ++prev_val) {
2667     size_t len;
2668     hive_type t;
2669
2670     hive_set_value *value = &values[prev_val - prev_values];
2671
2672     char *valval = hivex_value_value (h, *prev_val, &t, &len);
2673     if (valval == NULL) goto leave_partial;
2674
2675     ++alloc_ct;
2676     value->value = valval;
2677     value->t = t;
2678     value->len = len;
2679
2680     char *valkey = hivex_value_key (h, *prev_val);
2681     if (valkey == NULL) goto leave_partial;
2682
2683     ++alloc_ct;
2684     value->key = valkey;
2685
2686     if (STRCASEEQ (valkey, val->key))
2687       idx_of_val = prev_val - prev_values;
2688   }
2689
2690   if (idx_of_val > -1) {
2691     free (values[idx_of_val].key);
2692     free (values[idx_of_val].value);
2693   } else {
2694     idx_of_val = nr_values;
2695     ++nr_values;
2696   }
2697
2698   hive_set_value *value = &values[idx_of_val];
2699   *value = (hive_set_value){
2700     .key = strdup (val->key),
2701     .value = malloc (val->len),
2702     .len = val->len,
2703     .t = val->t
2704   };
2705
2706   if (value->key == NULL || value->value == NULL) goto leave_partial;
2707   memcpy (value->value, val->value, val->len);
2708
2709   retval = hivex_node_set_values (h, node, nr_values, values, 0);
2710
2711  leave_partial:
2712   for (int i = 0; i < alloc_ct; i += 2) {
2713     if (values[i / 2].value != NULL)
2714       free (values[i / 2].value);
2715     if (i + 1 < alloc_ct && values[i / 2].key != NULL)
2716       free (values[i / 2].key);
2717   }
2718   free (values);
2719
2720  leave_prev_values:
2721   free (prev_values);
2722   return retval;
2723 }