Allow extra flags to be set for a block created by new_virt_block
[hed.git] / libhed / file.c
blob4f284b745e175f55ff2379d2ccf70802287bb899
1 /* $Id$ */
3 /*
4 * hed - Hexadecimal editor
5 * Copyright (C) 2004 Petr Baudis <pasky@ucw.cz>
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of version 2 of the GNU General Public License as
9 * published by the Free Software Foundation.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22 * There hammer on the anvil smote,
23 * There chisel clove, and graver wrote;
24 * There forged was blade, and bound was hilt;
25 * The delver mined, the mason built.
26 * There beryl, pearl, and opal pale,
27 * And metal wrought like fishes' mail,
28 * Buckler and corslet, axe and sword,
29 * And shining spears were laid in hoard.
32 /* Feature macros needed for:
33 * - memrchr
34 * - pread, pwrite
35 * - stpcpy
37 #define _GNU_SOURCE
39 #include <config.h>
41 #include <errno.h>
42 #include <fcntl.h>
43 #include <limits.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <sys/ioctl.h>
48 #include <unistd.h>
49 #include <linux/fs.h> /* BLKGETSIZE and BLKGETSIZE64 */
51 #include "file.h"
52 #include "access.h"
53 #include "cache.h"
54 #include "swap.h"
55 #include "tree.h"
56 #include "expr.h"
58 /* memrchr() might not be available */
59 #ifndef HAVE_MEMRCHR
60 # include "memrchr.c"
61 #endif /* HAVE_MEMRCHR */
64 * `Piles of jewels?' said Gandalf. `No. The Orcs have often plundered Moria;
65 * there is nothing left in the upper halls. And since the dwarves fled, no one
66 * dares to seek the shafts and treasuries down in the deep places: they are
67 * drowned in water--or in a shadow of fear.'
70 /* TODO: Currently the file blocks allocation is not very sophisticated and
71 * when the weather is bad it could probably have rather horrible results. */
73 #undef BLOCKS_DEBUG
74 #ifdef BLOCKS_DEBUG
75 #define BDEBUG(x...) fprintf(stderr, x)
76 #else
77 #define BDEBUG(x...)
78 #endif
80 /* Number of blocks in cache */
81 #define CACHE_LENGTH 64
83 /* Blocks for readahead */
84 #define FILE_READAHEAD (CACHE_LENGTH/2)
86 #define file_block hed_block
87 #define blockoff_t hed_cursor_t
89 #define block_is_dirty hed_block_is_dirty
90 #define block_set_dirty hed_block_set_dirty
91 #define block_clear_dirty hed_block_clear_dirty
92 #define block_is_inserted hed_block_is_inserted
93 #define block_set_inserted hed_block_set_inserted
94 #define block_clear_inserted hed_block_clear_inserted
95 #define block_is_excache hed_block_is_excache
96 #define block_set_excache hed_block_set_excache
97 #define block_clear_excache hed_block_clear_excache
98 #define block_is_virtual hed_block_is_virtual
99 #define block_set_virtual hed_block_set_virtual
100 #define block_clear_virtual hed_block_clear_virtual
101 #define block_is_eof hed_block_is_eof
102 #define block_set_eof hed_block_set_eof
103 #define block_clear_eof hed_block_clear_eof
104 #define block_is_inner_virtual hed_block_is_inner_virtual
106 #define block_data hed_block_data
108 #define null_block(tree) (tree_entry(null_node(tree),struct file_block,t))
110 #define first_block(tree) (tree_entry(first_in_tree(tree),struct file_block,t))
111 #define prev_block(b) (tree_entry(prev_in_tree(&(b)->t),struct file_block,t))
112 #define next_block(b) (tree_entry(next_in_tree(&(b)->t),struct file_block,t))
113 #define last_block(tree) (tree_entry(last_in_tree(tree),struct file_block,t))
115 /* false if this is not a block - out of list bounds */
116 #define is_a_block(tree,b) (&(b)->t != null_node(tree))
118 #define block_offset(tree,b) tree_block_offset((tree), &(b)->t)
120 #define recalc_block_recursive(tree,b) recalc_node_recursive((tree),&(b)->t)
122 #define chain_block(tree,b) append_to_tree((tree), &(b)->t)
123 #define recalc_chain_block(tree,b) do { \
124 chain_block((tree), (b)); \
125 recalc_block_recursive((tree), (b)); \
126 } while (0)
128 #define chain_block_after(tree,p,b) insert_into_tree((tree), &(b)->t, &(p)->t)
130 #define recalc_chain_block_after(tree,p,b) do { \
131 chain_block_after((tree), (p), (b)); \
132 recalc_block_recursive((tree), (b)); \
133 } while (0)
135 #define unchain_block(tree,b) del_from_tree((tree), &(b)->t)
136 #define recalc_unchain_block(tree,b) recalc_del_from_tree((tree), &(b)->t)
138 #define init_block_list(tree) init_tree(tree)
139 #define init_block_link(b) init_node(&(b)->t)
141 #define foreach_block(b,tree) foreach_in_tree ((b),(tree),struct file_block,t)
142 #define foreachsafe_block(b,n,tree) foreachsafe_in_tree ((b),(n),(tree),struct file_block,t)
144 #define find_block(tree,o) tree_entry(find_in_tree((tree),(o)),struct file_block,t)
146 #define file_size hed_file_size
147 #define file_blocks hed_file_blocks
149 #ifdef HED_CONFIG_SWAP
151 /* Return the swp file object */
152 static inline struct swp_file *
153 file_swp(struct hed_file *file)
155 return file->swp;
158 #else
160 /* Provide a stub for the non-swap case */
161 static inline void *
162 file_swp(struct hed_file *file)
164 return NULL;
167 #endif
169 #ifdef HED_CONFIG_READAHEAD
171 #define file_ra_none(f) ((f)->readahead == HED_RA_NONE)
172 #define file_ra_forward(f) ((f)->readahead == HED_RA_FORWARD)
173 #define file_ra_backward(f) ((f)->readahead == HED_RA_BACKWARD)
175 #else
177 #define file_ra_none(f) (1)
178 #define file_ra_forward(f) (0)
179 #define file_ra_backward(f) (0)
181 #endif /* HED_CONFIG_READAHEAD */
183 bool
184 hed_block_is_after_erase(const struct hed_tree *tree, struct hed_block *block)
186 struct hed_block *prev;
188 prev = prev_block(block);
189 if (is_a_block(tree, prev)) {
190 hed_uoff_t prevend = prev->phys_pos;
191 if (!block_is_inserted(prev))
192 prevend += prev->t.size;
193 return block->phys_pos > prevend;
194 } else
195 return block->phys_pos;
198 bool
199 hed_block_is_after_insert(const struct hed_tree *tree, struct hed_block *block)
201 struct hed_block *prev = block;
202 while (is_a_block(tree, prev = prev_block(prev)))
203 if (hed_block_size(prev)) {
204 if (block_is_inserted(prev))
205 return true;
206 break;
208 return false;
211 #ifndef BLOCKS_DEBUG
212 # define dump_blocks(file) {}
213 #else
215 static hed_uoff_t
216 block_phys_size(struct hed_file *file, struct file_block *block)
218 struct file_block *next;
220 next = next_block(block);
221 if (!is_a_block(file_blocks(file), next)) {
222 assert(block_is_virtual(block));
223 return 0;
226 return next->phys_pos - block->phys_pos;
229 static void
230 dump_block(int level, struct hed_file *file, struct hed_tree_head *node,
231 hed_uoff_t *cur_offset, hed_uoff_t *cur_poffset)
233 struct file_block *block = tree_entry(node, struct file_block, t);
234 bool virtual = block_is_virtual(block);
235 blockoff_t *cur;
236 char t[21] = " ";
238 if (is_a_node(file_blocks(file), node->left))
239 dump_block(level + 1, file, node->left, cur_offset, cur_poffset);
240 if (level < 20) t[level] = '>'; else t[19] = '.';
241 fprintf(stderr, "%s [%06llx] [%06llx] %c%c%c %05llx %05llx {%02x%02x%02x%02x} -- %p ^%p [%06llx]\n",
242 t, *cur_offset, *cur_poffset,
243 virtual ? 'v' : ' ', block_is_inserted(block) ? 'i' : ' ',
244 block_is_dirty(block) ? '*' : ' ',
245 node->size, block_phys_size(file, block),
246 !virtual && block->t.size > 0 ? block_data(block)[0] : 0,
247 !virtual && block->t.size > 1 ? block_data(block)[1] : 0,
248 !virtual && block->t.size > 2 ? block_data(block)[2] : 0,
249 !virtual && block->t.size > 3 ? block_data(block)[3] : 0,
250 node, is_a_node(file_blocks(file), node->up) ? node->up : NULL,
251 node->cover_size
253 list_for_each_entry (cur, &block->refs, list) {
254 fprintf(stderr, " <%p>: %llx->%p:%lx\n",
255 cur, cur->pos, cur->block, cur->off);
257 assert(*cur_poffset == block->phys_pos);
258 *cur_offset += node->size;
259 *cur_poffset += block_phys_size(file, block);
260 if (is_a_node(file_blocks(file), node->right))
261 dump_block(level + 1, file, node->right, cur_offset, cur_poffset);
262 assert(node->cover_size == (is_a_node(file_blocks(file), node->left) ? node->left->cover_size : 0)
263 + (is_a_node(file_blocks(file), node->right) ? node->right->cover_size : 0)
264 + node->size);
267 /* Walk the tree manually here, because foreach_block() does not provide
268 * the tree structure.
269 * TODO: Change this if you plan to debug any other block containers.
271 static void
272 dump_blocks(struct hed_file *file)
274 struct file_block *first = first_block(file_blocks(file));
275 hed_uoff_t cur_offset, cur_poffset;
277 fprintf(stderr, "-- blocks dump --\n");
278 if (is_a_block(file_blocks(file), first)) {
279 cur_offset = 0;
280 cur_poffset = first->phys_pos;
281 dump_block(0, file, file_blocks(file)->root,
282 &cur_offset, &cur_poffset);
284 fprintf(stderr, "-- blocks dump end --\n");
286 #endif
288 static void
289 get_cursor(struct hed_file *file, hed_uoff_t offset, hed_cursor_t *curs)
291 struct file_block *block;
293 block = find_block(file_blocks(file), offset);
294 assert(is_a_block(file_blocks(file), block));
295 curs->pos = offset;
296 curs->block = block;
297 curs->off = offset - block_offset(file_blocks(file), block);
298 list_add(&curs->list, &block->refs);
300 BDEBUG("Mapped %llx to %llx+%llx/%llx\n",
301 offset, offset - curs->off, curs->off, block->t.size);
304 void
305 hed_get_cursor(struct hed_file *file, hed_uoff_t offset, hed_cursor_t *curs)
307 if (hed_is_a_cursor(curs))
308 hed_put_cursor(curs);
309 get_cursor(file, offset, curs);
312 void
313 hed_put_cursor(hed_cursor_t *curs)
315 list_del(&curs->list);
318 void
319 hed_dup_cursor(const hed_cursor_t *src, hed_cursor_t *dst)
321 dst->pos = src->pos;
322 dst->block = src->block;
323 dst->off = src->off;
324 list_add_tail(&dst->list, &src->block->refs);
327 void
328 hed_dup2_cursor(const hed_cursor_t *src, hed_cursor_t *dst)
330 if (hed_is_a_cursor(dst))
331 hed_put_cursor(dst);
332 hed_dup_cursor(src, dst);
335 /* Move blockoff's from @old to @new, adding @off to their block
336 * offsets to keep them at the same position. */
337 static void
338 update_blockoffs(const struct file_block *old, struct file_block *new,
339 hed_off_t off)
341 blockoff_t *blockoff;
343 BDEBUG("Updating blockoffs from <%p> to <%p>%c%llx\n",
344 old, new, off >= 0 ? '+' : '-', off >= 0 ? off : -off);
346 list_for_each_entry(blockoff, &old->refs, list) {
347 blockoff->block = new;
348 blockoff->off += off;
352 /* Move blockoff's in the range <@start;@end> from @old to @new,
353 * adding @off to their block offset, plus moving the reference list. */
354 static void
355 move_blockoffs(const struct file_block *old, struct file_block *new,
356 hed_uoff_t start, hed_uoff_t end, hed_off_t off)
358 blockoff_t *blockoff, *nextoff;
360 BDEBUG("Moving blockoffs from <%p>:%llx:%llx to <%p>%c%llx\n",
361 old, start, end, new,
362 off >= 0 ? '+' : '-', off >= 0 ? off : -off);
364 list_for_each_entry_safe(blockoff, nextoff, &old->refs, list)
365 if (blockoff->off >= start && blockoff->off <= end) {
366 blockoff->block = new;
367 blockoff->off += off;
368 list_move(&blockoff->list, &new->refs);
372 /* Destroy blockoffs referencing @block from @start to @end */
373 static void
374 nuke_blockoffs(const struct file_block *block,
375 hed_uoff_t start, hed_uoff_t end)
377 blockoff_t *blockoff, *nextoff;
379 BDEBUG("Nuking blockoffs from <%p>:%llx:%llx\n",
380 block, start, end);
381 list_for_each_entry_safe(blockoff, nextoff, &block->refs, list)
382 if (blockoff->off >= start && blockoff->off <= end) {
383 blockoff->block = NULL;
384 list_del_init(&blockoff->list);
388 /* Update the positions of blockoffs at and after @start for all
389 * blocks starting at @block */
390 static void
391 slide_blockoffs(struct hed_file *file, const struct file_block *block,
392 hed_uoff_t start, hed_off_t off)
394 blockoff_t *blockoff;
396 BDEBUG("Sliding blockoffs >= %llx by %c%llx, starting at <%p>\n",
397 start, off >= 0 ? '+' : '-', off >= 0 ? off : -off, block);
398 while (is_a_block(file_blocks(file), block)) {
399 list_for_each_entry(blockoff, &block->refs, list)
400 if (blockoff->pos >= start)
401 blockoff->pos += off;
402 block = next_block(block);
406 static struct hed_block *
407 new_block(struct hed_file *file, long flags)
409 struct file_block *new;
411 if (! (new = swp_zalloc(file_swp(file), sizeof(struct file_block))) )
412 return NULL;
414 new->flags = flags;
415 init_block_link(new);
416 INIT_LIST_HEAD(&new->refs);
417 if (flags & HED_BLOCK_EXCACHE)
418 INIT_LIST_HEAD(&new->lru);
419 else
420 list_add_tail(&new->lru, &file->lru);
422 return new;
425 static struct hed_block *
426 new_virt_block(struct hed_file *file, hed_uoff_t pos, hed_uoff_t size,
427 long extraflags)
429 struct hed_block *new =
430 new_block(file, (HED_BLOCK_EXCACHE |
431 HED_BLOCK_VIRTUAL |
432 extraflags));
433 if (!new)
434 return NULL;
436 new->t.size = size;
437 new->phys_pos = pos;
438 BDEBUG("Spawned new virtual block [%llx] at %llx\n", size, pos);
439 return new;
442 static struct hed_block *
443 new_data_block(struct hed_file *file, hed_uoff_t pos, hed_uoff_t size,
444 struct hed_block_data *dataobj)
446 struct hed_block *new =
447 new_block(file, 0);
448 if (!new)
449 return NULL;
451 cache_get(dataobj);
452 new->dataobj = dataobj;
453 new->t.size = size;
454 new->phys_pos = pos;
455 new->dataoff = FILE_BLOCK_OFF(pos);
456 BDEBUG("Spawned new data block [%llx] at %llx\n", size, pos);
457 return new;
460 static void
461 file_free_block(struct hed_file *file, struct file_block *block)
463 if (block->dataobj)
464 cache_put(file->cache, block->dataobj);
465 list_del(&block->lru);
467 swp_free(file_swp(file), block);
470 static bool
471 kill_block_if_empty(struct hed_file *file, struct file_block *block)
473 if (!block_is_eof(block) && block->t.size == 0) {
474 /* No recalculation needed, zero size. */
475 unchain_block(file_blocks(file), block);
476 assert(list_empty(&block->refs));
477 file_free_block(file, block);
478 return true;
480 return false;
483 /* This may kill the previous block as well, if it can be merged
484 * with the next one. It will never kill anything which _follows_. */
485 static void
486 file_kill_block(struct hed_file *file, struct file_block *block)
488 hed_uoff_t phys_pos = block->phys_pos;
489 struct file_block *prev = prev_block(block);
490 struct file_block *next = next_block(block);
491 struct file_block *merger;
492 bool killprev = false;
494 /* We should never kill a dirty block! */
495 assert(!block_is_dirty(block));
496 /* We shouldn't get with an empty block here (that might
497 * need special considerations with virtualization). */
498 assert(block->t.size > 0);
500 if (is_a_block(file_blocks(file), next) &&
501 block_is_inner_virtual(next) &&
502 phys_pos + block->t.size == next->phys_pos) {
503 if (is_a_block(file_blocks(file), prev) &&
504 block_is_inner_virtual(prev) &&
505 prev->phys_pos + prev->t.size == phys_pos)
506 killprev = true;
507 merger = next;
508 merger->phys_pos -= block->t.size;
509 update_blockoffs(merger, merger, block->t.size);
510 update_blockoffs(block, merger, 0);
511 } else if (is_a_block(file_blocks(file), prev) &&
512 block_is_inner_virtual(prev) &&
513 prev->phys_pos + prev->t.size == phys_pos) {
514 merger = prev;
515 update_blockoffs(block, merger, merger->t.size);
516 } else if (!block_is_virtual(block)) {
517 /* Convert physical to virtual */
518 assert(block->dataobj);
519 cache_put(file->cache, block->dataobj);
520 block->dataobj = NULL;
522 list_del_init(&block->lru); /* unlink the block from LRU */
523 block_set_excache(block); /* say it's unlinked */
524 block_set_virtual(block);
525 return;
526 } else
527 /* Already virtual and cannot merge */
528 return;
530 list_splice(&block->refs, &merger->refs);
532 /* Messing with block sizes and unchaining is a bit tricky
533 * since unchain_block() can splay(). So we really need
534 * to recalc_block_recursive() right after we update the size.
535 * If this place turns out to be a hot-spot, we can optimize
536 * the tree operations here. */
537 merger->t.size += block->t.size;
538 recalc_block_recursive(file_blocks(file), merger);
540 /* Destroy the block */
541 recalc_unchain_block(file_blocks(file), block);
542 file_free_block(file, block);
544 if (killprev)
545 file_kill_block(file, prev);
548 static struct file_block *
549 split_block(struct hed_file *file, struct hed_block *block,
550 hed_uoff_t splitpoint)
552 struct file_block *next;
554 next = new_block(file, block->flags);
555 if (!next)
556 return NULL;
558 if ( (next->dataobj = block->dataobj) ) {
559 cache_get(next->dataobj);
560 next->dataoff = block->dataoff + splitpoint;
561 } else
562 assert(block_is_virtual(block));
564 next->t.size = block->t.size - splitpoint;
565 next->phys_pos = block->phys_pos;
566 if (!block_is_inserted(block))
567 next->phys_pos += splitpoint;
569 block->t.size = splitpoint;
570 recalc_block_recursive(file_blocks(file), block);
571 recalc_chain_block_after(file_blocks(file), block, next);
573 move_blockoffs(block, next, splitpoint, UOFF_MAX, -splitpoint);
575 return next;
578 /* Replace a chunk in @block with @newblock */
579 static int
580 replace_chunk(struct hed_file *file, struct hed_block *block,
581 hed_uoff_t offset, struct hed_block *newblock)
583 size_t len = newblock->t.size;
584 hed_uoff_t leadlen = offset + len;
586 assert(len <= block->t.size - offset);
588 /* Re-create the tail block if necessary */
589 if (block_is_eof(block) || block->t.size - offset > len) {
590 struct file_block *tail;
592 tail = new_block(file, block->flags);
593 if (!tail)
594 return -1;
595 tail->t.size = block->t.size - leadlen;
596 tail->dataobj = block->dataobj;
597 tail->dataoff = block->dataoff + leadlen;
598 tail->phys_pos = block->phys_pos + leadlen;
600 block_clear_eof(block);
601 recalc_chain_block_after(file_blocks(file), block, tail);
603 /* Move offsets to the tail */
604 move_blockoffs(block, tail, leadlen, UOFF_MAX, -leadlen);
607 /* Move pointers to the new block */
608 assert(leadlen > 0);
609 move_blockoffs(block, newblock, offset, leadlen - 1, -offset);
611 /* Shorten the leading block */
612 block->t.size = offset;
613 recalc_block_recursive(file_blocks(file), block);
615 /* Insert the new block */
616 recalc_chain_block_after(file_blocks(file), block, newblock);
618 /* Kill the leading block if possible */
619 kill_block_if_empty(file, block);
621 return 0;
624 #ifdef HED_CONFIG_SWAP
626 static char *
627 swp_filename(const char *filename)
629 size_t fnlen = strlen(filename);
630 char *swp;
631 char *file;
633 if (!(swp = malloc(fnlen + 9)) )
634 return NULL;
635 strcpy(swp, filename);
637 file = strrchr(swp, '/');
638 file = file ? file + 1 : swp;
639 *file = '.';
640 strcpy(stpcpy(file + 1, filename + (file -swp)), ".hedswp");
641 return swp;
644 static char *
645 newswp_filename(char *swpname)
647 char *ret, *p;
649 ret = swpname;
650 while (!access(ret, F_OK)) {
651 if (ret == swpname) {
652 if (! (ret = strdup(swpname)) )
653 return NULL;
654 p = ret + strlen(ret) - 1;
657 if (*p == 'a') {
658 free(ret);
659 return NULL;
661 --*p;
663 return ret;
667 hed_file_remove_swap(struct hed_file *file)
669 if (remove(file->swpname))
670 return -1;
671 if (rename(file->newswpname, file->swpname))
672 return -1;
674 free(file->newswpname);
675 file->newswpname = file->swpname;
676 return 0;
679 static inline struct hed_file *
680 file_swp_init(const char *name)
682 char *swpname, *newswpname;
683 struct swp_file *swp;
684 struct hed_file *file;
686 swpname = swp_filename(name);
687 if (!swpname)
688 goto fail;
689 newswpname = newswp_filename(swpname);
690 if (!newswpname)
691 goto fail_free_name;
692 swp = swp_init_write(newswpname);
693 if (!swp)
694 goto fail_free_newname;
696 assert(sizeof(struct swp_header) + sizeof(struct hed_file)
697 <= FILE_BLOCK_SIZE);
698 file = swp_private(swp);
699 memset(file, 0, sizeof *file);
701 file->swp = swp;
702 file->swpname = swpname;
703 file->newswpname = newswpname;
705 return file;
707 fail_free_newname:
708 free(newswpname);
709 fail_free_name:
710 if (swpname != newswpname)
711 free(swpname);
712 fail:
713 return NULL;
716 static inline void
717 file_swp_done(struct hed_file *file)
719 remove(file->newswpname);
720 if (file->newswpname != file->swpname)
721 free(file->newswpname);
722 free(file->swpname);
723 swp_done(file_swp(file));
724 /* file was de-allocated automatically with file->swp */
727 static inline void
728 init_null_block(struct hed_file *file)
730 file->null_block = null_block(file_blocks(file));
733 #else /* HED_CONFIG_SWAP */
735 static inline struct hed_file *
736 file_swp_init(const char *name)
738 return calloc(1, sizeof(struct hed_file));
741 static inline void
742 file_swp_done(struct hed_file *file)
746 #define init_null_block(f) do {} while(0)
748 #endif /* HED_CONFIG_SWAP */
750 static inline struct stat *
751 file_stat(struct hed_file *file)
753 return &file->s;
757 hed_file_update_size(struct hed_file *file)
759 hed_uoff_t oldsize = file->phys_size;
761 if(fstat(file->fd, file_stat(file)) < 0)
762 return -1;
764 if (S_ISBLK(file_stat(file)->st_mode)) {
765 if (ioctl(file->fd, BLKGETSIZE64, &file->phys_size)) {
766 unsigned long size_in_blocks;
767 if (ioctl(file->fd, BLKGETSIZE, &size_in_blocks))
768 return -1;
769 file->phys_size = (hed_uoff_t)size_in_blocks << 9;
771 } else if (S_ISREG(file_stat(file)->st_mode)) {
772 file->phys_size = file_stat(file)->st_size;
773 } else if (S_ISCHR(file_stat(file)->st_mode)) {
774 if (lseek(file->fd, 0, SEEK_SET) < 0)
775 return -1;
776 file->phys_size = OFF_MAX;
777 } else {
778 errno = EINVAL;
779 return -1;
782 file->size += file->phys_size - oldsize;
783 return 0;
786 static int
787 do_file_open(struct hed_file *file)
789 file->fd = open(file->name, O_RDONLY);
790 if (file->fd < 0) {
791 if (errno != ENOENT)
792 return errno;
793 fprintf(stderr, "Warning: File %s does not exist\n",
794 file->name);
795 memset(file_stat(file), 0, sizeof(struct stat));
797 } else if (hed_file_update_size(file)) {
798 int errsv = errno;
799 close(file->fd);
800 return errsv;
802 return 0;
805 static int
806 file_setup_blocks(struct hed_file *file)
808 hed_uoff_t phys_size = file->phys_size;
809 struct file_block *block;
810 struct file_block *vblock;
812 if (phys_size) {
813 block = new_virt_block(file, 0, phys_size, 0);
814 if (!block)
815 return -1;
816 chain_block(file_blocks(file), block);
819 vblock = new_virt_block(file, phys_size, OFF_MAX - phys_size + 1,
820 HED_BLOCK_EOF);
821 if (!vblock)
822 return -1;
823 recalc_chain_block(file_blocks(file), vblock);
825 return 0;
829 libhed_init(void)
831 return file_access_init();
834 struct hed_file *
835 hed_open(const char *name)
837 struct hed_file *file;
839 if (! (file = file_swp_init(name)) )
840 goto fail;
842 file->name = name;
844 init_block_list(file_blocks(file));
845 init_null_block(file);
847 file->cache = cache_init(CACHE_LENGTH, file_swp(file));
848 if (!file->cache)
849 goto fail_file;
850 INIT_LIST_HEAD(&file->lru);
852 if (do_file_open(file))
853 goto fail_file;
855 if (file_setup_blocks(file))
856 goto fail_file;
858 fixup_register(file);
860 return file;
862 fail_file:
863 hed_close(file);
864 fail:
865 return NULL;
868 void
869 hed_close(struct hed_file *file)
871 assert(file);
873 /* Do not check for errors:
874 * 1. This FD is read-only => no data loss possbile
875 * 2. We're about to exit anyway => no resource leak
877 if (file->fd >= 0)
878 close(file->fd);
880 fixup_deregister(file);
882 /* No need to free file blocks here, because all data is
883 * allocated either from the cache or from the swap file
884 * and both is going to be destroyed now.
887 if (file->cache)
888 cache_done(file->cache);
890 file_swp_done(file);
893 /* Adjust blockoff after off gets outside its block */
894 static void
895 fixup_blockoff_slow(blockoff_t *blockoff)
897 struct file_block *block = blockoff->block;
898 hed_uoff_t off = blockoff->off;
900 do {
901 if ((hed_off_t)off < 0) {
902 block = prev_block(block);
903 off += block->t.size;
904 } else {
905 off -= block->t.size;
906 block = next_block(block);
908 } while (off >= block->t.size);
910 blockoff->block = block;
911 blockoff->off = off;
912 list_move(&blockoff->list, &block->refs);
915 /* Adjust blockoff if off gets outside its block.
916 * This is separate from fixup_blockoff_slow, because it is supposed
917 * to be small enough to be inlined (which is a win, because most of
918 * the time no fixup has to be done, so the fast inlined path is used).
920 static inline void
921 fixup_blockoff(blockoff_t *blockoff)
923 if (blockoff->off >= blockoff->block->t.size)
924 fixup_blockoff_slow(blockoff);
927 hed_off_t
928 hed_move_relative(blockoff_t *blockoff, hed_off_t num)
930 hed_off_t newpos = blockoff->pos + num;
931 if (newpos < 0) {
932 newpos = num < 0 ? 0 : OFF_MAX;
933 num = newpos - blockoff->pos;
935 blockoff->pos = newpos;
936 blockoff->off += num;
937 fixup_blockoff(blockoff);
938 return num;
941 /* Relative move with no checking (and only by a small amount) */
942 static inline void
943 move_rel_fast(blockoff_t *blockoff, ssize_t num)
945 blockoff->off += num;
946 blockoff->pos += num;
947 fixup_blockoff(blockoff);
950 static void
951 alloc_caches(struct hed_file *file, struct hed_block_data **caches, int n)
953 struct remap_control rc;
954 int i;
956 BDEBUG("Allocate %d caches (%d free slots available)\n",
957 n, file->cache->nfree);
959 assert(n <= CACHE_LENGTH);
960 while (file->cache->nfree < n) {
961 struct file_block *block;
963 assert(!list_empty(&file->lru));
964 block = list_entry(file->lru.next, struct file_block, lru);
965 BDEBUG("Killing block at physical %llx\n", block->phys_pos);
966 file_kill_block(file, block);
969 for (i = 0; i < n; ++i) {
970 caches[i] = cache_alloc(file->cache);
971 assert(caches[i]);
974 remap_init(&rc);
975 remap_compact(&rc, file->cache, caches, n);
976 for (i = 0; i < n; ++i)
977 remap_add(&rc, caches[i]->data);
978 remap_finish(&rc);
981 static inline void
982 free_caches(struct hed_file *file, struct hed_block_data **preload, int n)
984 int i;
986 for (i = 0; i < n; ++i)
987 if (preload[i])
988 cache_put(file->cache, preload[i]);
991 static int
992 file_load_data(struct hed_file *file,
993 struct hed_block_data **caches, int n,
994 hed_uoff_t offset)
996 struct hed_block_data *dataobj = caches[0];
997 void *data = dataobj->data;
998 ssize_t rsize, total, segsize;
1000 segsize = n << FILE_BLOCK_SHIFT;
1001 for (total = 0; total < segsize; total += rsize) {
1002 rsize = pread(file->fd, data + total,
1003 segsize - total, offset + total);
1004 if (!rsize)
1005 break;
1006 if (rsize < 0) {
1007 dataobj = caches[total >> FILE_BLOCK_SHIFT];
1008 caches[total >> FILE_BLOCK_SHIFT] = NULL;
1009 data = dataobj->data;
1010 cache_put(file->cache, dataobj);
1011 total = FILE_BLOCK_ROUND(total);
1012 rsize = FILE_BLOCK_SIZE;
1013 BDEBUG("Error reading block at phys %llx: %s\n",
1014 offset + total, strerror(errno));
1018 BDEBUG("Loaded data at phys %llx up to %llx\n",
1019 offset, offset + segsize);
1020 return 0;
1023 #ifdef HED_CONFIG_MMAP
1025 static int
1026 file_load_data_mmap(struct hed_file *file,
1027 struct hed_block_data **caches, int n,
1028 hed_uoff_t offset)
1030 void *data;
1031 ssize_t segsize;
1032 int i;
1034 segsize = n << FILE_BLOCK_SHIFT;
1035 data = mmap(NULL, segsize,
1036 PROT_READ | PROT_WRITE,
1037 MAP_PRIVATE | (file->fd < 0 ? MAP_ANONYMOUS : 0),
1038 file->fd, offset);
1040 if (data == MAP_FAILED) {
1041 BDEBUG("mmap failed at %llx: fail over to traditional read\n",
1042 offset);
1044 data = mmap(NULL, segsize,
1045 PROT_READ | PROT_WRITE,
1046 MAP_PRIVATE | MAP_ANONYMOUS,
1047 0, 0);
1048 if (data == MAP_FAILED)
1049 return -1;
1051 for (i = 0; i < n; ++i)
1052 caches[i]->data = data + (i << FILE_BLOCK_SHIFT);
1053 return file_load_data(file, caches, n, offset);
1056 for (i = 0; i < n; ++i)
1057 caches[i]->data = data + (i << FILE_BLOCK_SHIFT);
1059 BDEBUG("Loaded data at phys %llx up to %llx\n",
1060 offset, offset + segsize);
1061 return 0;
1063 # define file_load_data file_load_data_mmap
1065 #endif
1067 static int
1068 load_blocks(struct hed_file *file, const blockoff_t *from)
1070 hed_uoff_t physpos, segstart;
1071 struct hed_block_data *preload[FILE_READAHEAD];
1072 size_t ra_bkw, ra_fwd, ra_off;
1073 hed_cursor_t pos;
1074 int nblocks;
1076 segstart = hed_cursor_phys_pos(from);
1077 ra_bkw = FILE_BLOCK_OFF(segstart);
1078 ra_fwd = FILE_BLOCK_SIZE - ra_bkw;
1080 if (file_ra_forward(file))
1081 ra_fwd += (FILE_READAHEAD - 1) << FILE_BLOCK_SHIFT;
1082 else if (file_ra_backward(file))
1083 ra_bkw += (FILE_READAHEAD - 1) << FILE_BLOCK_SHIFT;
1085 if (ra_bkw > segstart)
1086 ra_bkw = segstart;
1087 if (ra_fwd > file->phys_size - segstart)
1088 ra_fwd = file->phys_size - segstart;
1090 segstart -= ra_bkw;
1091 ra_fwd += ra_bkw;
1092 pos.block = from->block;
1093 while (pos.block->phys_pos > segstart)
1094 pos.block = prev_block(pos.block);
1095 pos.off = segstart - pos.block->phys_pos;
1097 list_add(&pos.list, &pos.block->refs);
1098 nblocks = ((ra_fwd - 1) >> FILE_BLOCK_SHIFT) + 1;
1099 alloc_caches(file, preload, nblocks);
1100 hed_put_cursor(&pos);
1102 if (file_load_data(file, preload, nblocks, segstart)) {
1103 free_caches(file, preload, nblocks);
1104 return -1;
1107 while (physpos = hed_cursor_phys_pos(&pos),
1108 ra_off = physpos - segstart,
1109 ra_off < ra_fwd) {
1110 struct hed_block_data *dataobj;
1111 struct hed_block *newblock;
1112 size_t datalen;
1114 if (!block_is_virtual(pos.block)) {
1115 pos.block = next_block(pos.block);
1116 pos.off = 0;
1117 continue;
1120 datalen = FILE_BLOCK_SIZE - FILE_BLOCK_OFF(physpos);
1121 if (datalen > hed_block_size(pos.block) - pos.off)
1122 datalen = hed_block_size(pos.block) - pos.off;
1124 dataobj = preload[ra_off >> FILE_BLOCK_SHIFT];
1125 newblock = dataobj
1126 ? new_data_block(file, physpos, datalen, dataobj)
1127 : new_virt_block(file, physpos, datalen, 0);
1129 /* Punch the new block */
1130 BDEBUG("Add %s block at %llx, length %lx\n",
1131 hed_block_is_virtual(newblock) ? "error" : "physical",
1132 newblock->phys_pos, newblock->t.size);
1133 if (replace_chunk(file, pos.block, pos.off, newblock)) {
1134 file_free_block(file, newblock);
1135 free_caches(file, preload, nblocks);
1136 return -1;
1139 pos.block = next_block(newblock);
1140 pos.off = 0;
1143 /* All cache objects now have an extra reference from the
1144 * allocation. Drop it. */
1145 free_caches(file, preload, nblocks);
1147 dump_blocks(file);
1148 return -hed_block_is_virtual(from->block);
1151 /* Shorten a block at beginning and enlarge the preceding block.
1153 * Re-allocate at most @len bytes from the beginning of @block to the
1154 * end of the preceding block.
1155 * If @block is virtual, this will effectively devirtualize the range.
1156 * If @block is not virtual, this will change the backing store of
1157 * the bytes in the range.
1158 * Returns: the number of bytes actually moved.
1160 static size_t
1161 shrink_at_begin(struct hed_file *file, struct file_block *block,
1162 size_t len, long state)
1164 struct file_block *prev = prev_block(block);
1165 size_t maxgrow;
1167 /* Basic assumptions */
1168 assert(!(state & HED_BLOCK_VIRTUAL));
1170 /* The previous block must exist: */
1171 if (!is_a_block(file_blocks(file), prev))
1172 return 0;
1174 /* The block flags must match the requested @state: */
1175 if ((prev->flags & HED_BLOCK_STATEMASK) != state)
1176 return 0;
1178 /* No deletions at end, or similar: */
1179 if (prev->phys_pos + prev->t.size != block->phys_pos)
1180 return 0;
1182 /* Append less bytes than requested if not all are available */
1183 assert(prev->t.size <= prev->dataobj->size);
1184 maxgrow = prev->dataobj->size - prev->dataoff - prev->t.size;
1185 if (len > maxgrow)
1186 len = maxgrow;
1187 if (!len)
1188 return 0;
1190 BDEBUG("Appending 0:%lx to the previous block\n", len);
1192 /* Move blockoffs away from the to-be-chopped beginning */
1193 move_blockoffs(block, prev, 0, len - 1, prev->t.size);
1195 /* Enlarge the previous block */
1196 prev->t.size += len;
1197 recalc_block_recursive(file_blocks(file), prev);
1199 /* Shorten the original block */
1200 block->t.size -= len;
1201 block->dataoff += len;
1202 block->phys_pos += len;
1203 recalc_block_recursive(file_blocks(file), block);
1204 return len;
1207 /* Shorten a block at end and enlarge the following block.
1209 * Re-allocate at most @len bytes from the end of @block to the
1210 * beginning of the following block.
1211 * If @block is virtual, this will effectively devirtualize the range.
1212 * If @block is not virtual, this will change the backing store of
1213 * the bytes in the range.
1214 * Returns: the number of bytes actually moved.
1216 static size_t
1217 shrink_at_end(struct hed_file *file, struct file_block *block,
1218 size_t len, long state)
1220 struct file_block *next = next_block(block);
1221 hed_uoff_t off;
1223 /* Basic assumptions */
1224 assert(!(state & HED_BLOCK_VIRTUAL));
1226 /* The next block must exist: */
1227 if (!is_a_block(file_blocks(file), next))
1228 return 0;
1230 /* The block flags must match the requested @state: */
1231 if ((next->flags & HED_BLOCK_STATEMASK) != state)
1232 return 0;
1234 /* No deletions at end, or similar: */
1235 if (block->phys_pos + block->t.size != next->phys_pos)
1236 return 0;
1238 /* Prepend less bytes than requested if not all are available */
1239 if (len > next->dataoff)
1240 len = next->dataoff;
1241 if (!len)
1242 return 0;
1243 off = block->t.size - len;
1245 BDEBUG("Prepending %llx:%lx to the next block\n", off, len);
1247 /* Shift blockoffs in the new physical block */
1248 update_blockoffs(next, next, len);
1250 /* Move blockoffs away from the to-be-chopped end */
1251 move_blockoffs(block, next, off, UOFF_MAX, -off);
1253 /* Enlarge the next block */
1254 next->dataoff -= len;
1255 next->phys_pos -= len;
1256 next->t.size += len;
1257 recalc_block_recursive(file_blocks(file), next);
1259 /* Shorten the original block */
1260 block->t.size -= len;
1261 recalc_block_recursive(file_blocks(file), block);
1262 return len;
1265 /* Search for an existing data object within the same physical block
1266 * as @curs, and having the given @state flags.
1268 static struct hed_block_data *
1269 search_data(struct hed_file *file, const hed_cursor_t *curs, long state)
1271 struct file_block *block;
1272 hed_uoff_t physpos;
1274 physpos = FILE_BLOCK_ROUND(curs->block->phys_pos + curs->off);
1275 BDEBUG("Search for already loaded data at %llx starting at %llx...",
1276 physpos, curs->block->phys_pos);
1278 /* Search backwards */
1279 block = prev_block(curs->block);
1280 while (is_a_block(file_blocks(file), block) &&
1281 block->phys_pos >= physpos) {
1282 if ((block->flags & HED_BLOCK_STATEMASK) == state) {
1283 BDEBUG(" found at %llx\n", block->phys_pos);
1284 assert(block->dataobj);
1285 return block->dataobj;
1287 block = prev_block(block);
1290 /* Search forwards */
1291 block = next_block(curs->block);
1292 while (is_a_block(file_blocks(file), block) &&
1293 block->phys_pos < physpos + FILE_BLOCK_SIZE) {
1294 if ((block->flags & HED_BLOCK_STATEMASK) == state) {
1295 BDEBUG(" found at %llx\n", block->phys_pos);
1296 assert(block->dataobj);
1297 return block->dataobj;
1299 block = next_block(block);
1302 BDEBUG(" not found\n");
1303 return NULL;
1306 static int
1307 reuse_loaded_data(struct hed_file *file, const blockoff_t *blockoff,
1308 struct hed_block_data *data)
1310 struct file_block *physblock;
1311 struct file_block *block = blockoff->block;
1312 hed_uoff_t block_offset = blockoff->off;
1313 hed_uoff_t physpos = block->phys_pos + block_offset;
1314 size_t part = FILE_BLOCK_OFF(physpos);
1315 size_t len =
1316 FILE_BLOCK_SIZE - part <= block->t.size - block_offset
1317 ? FILE_BLOCK_SIZE - part
1318 : block->t.size - block_offset;
1320 if (block->phys_pos <= physpos - part) {
1321 physpos -= part;
1322 len += part;
1323 } else {
1324 physpos -= block_offset;
1325 len += block_offset;
1328 if (! (physblock = new_data_block(file, physpos, len, data)) )
1329 return -1;
1331 BDEBUG("Add physical block at %llx, length %lx\n",
1332 physblock->phys_pos, physblock->t.size);
1333 if (replace_chunk(file, block, block_offset, physblock)) {
1334 file_free_block(file, physblock);
1335 return -1;
1338 dump_blocks(file);
1339 return 0;
1342 /* Replace a part of a virtual block with content loaded
1343 * from disk. The amount of data loaded from the disk depends
1344 * on various factors with the goal to choose the most efficient
1345 * ratio. The only guarantee is that the byte at @blockoff will
1346 * be in a non-virtual block when this function returns 0.
1348 static int
1349 devirtualize_clean(struct hed_file *file, const blockoff_t *blockoff)
1351 struct file_block *block = blockoff->block;
1352 hed_uoff_t block_offset = blockoff->off;
1353 hed_uoff_t remain = block->t.size - block_offset;
1354 struct hed_block_data *data;
1356 BDEBUG("punch a clean hole at %llx into %llx:%llx\n", block_offset,
1357 block_offset(file_blocks(file), block), block->t.size);
1358 assert(block_is_virtual(block));
1360 /* Check if we can combine with a neighbouring block */
1361 if (shrink_at_begin(file, block, SIZE_MAX, 0) > block_offset ||
1362 shrink_at_end(file, block, SIZE_MAX, 0) >= remain) {
1363 kill_block_if_empty(file, block);
1364 dump_blocks(file);
1365 return 0;
1368 /* Check if the block is already loaded elsewhere */
1369 data = search_data(file, blockoff, 0);
1370 return data
1371 ? reuse_loaded_data(file, blockoff, data)
1372 : load_blocks(file, blockoff);
1375 /* Replace at most @len bytes of a virtual block with a newly
1376 * allocated out-of-cache block. The block is marked dirty
1377 * and its data is left uninitialized.
1378 * If the block at @blockoff is not virtual, make it dirty.
1379 * Note that this function may devirtualize less than @len bytes.
1380 * In the worst case only 1 byte at @blockoff will be available.
1382 static int
1383 prepare_modify(struct hed_file *file, blockoff_t *blockoff, size_t len)
1385 struct file_block *block = blockoff->block;
1386 hed_uoff_t block_offset = blockoff->off;
1387 hed_uoff_t remain = block->t.size - block_offset;
1388 struct file_block *newblock;
1390 if (block_is_dirty(block))
1391 return 0;
1393 if (len > remain)
1394 len = remain;
1396 BDEBUG("punch a dirty hole at %llx:%lx into %llx:%llx\n",
1397 block_offset, len,
1398 block_offset(file_blocks(file), block), block->t.size);
1400 /* Check if we can combine with a neighbouring block */
1401 if ((block_offset == 0 &&
1402 shrink_at_begin(file, block, len, HED_BLOCK_DIRTY)) ||
1403 (remain == len &&
1404 shrink_at_end(file, block, len, HED_BLOCK_DIRTY) >= len)) {
1405 kill_block_if_empty(file, block);
1406 dump_blocks(file);
1407 return 0;
1410 /* Initialize a new block */
1411 newblock = new_block(file, HED_BLOCK_EXCACHE | HED_BLOCK_DIRTY);
1412 if (!newblock)
1413 goto out_err;
1415 /* Allocate data */
1416 if ( (newblock->dataobj = search_data(file, blockoff,
1417 HED_BLOCK_DIRTY)) )
1418 cache_get(newblock->dataobj);
1419 else if (! (newblock->dataobj = block_data_new(file->cache,
1420 FILE_BLOCK_SIZE)) )
1421 goto out_err_free;
1423 newblock->phys_pos = block->phys_pos + block_offset;
1424 newblock->dataoff = FILE_BLOCK_OFF(newblock->phys_pos);
1425 if (len > FILE_BLOCK_SIZE - newblock->dataoff)
1426 len = FILE_BLOCK_SIZE - newblock->dataoff;
1427 newblock->t.size = len;
1429 if (replace_chunk(file, block, block_offset, newblock))
1430 goto out_err_free;
1432 dump_blocks(file);
1433 return 0;
1435 out_err_free:
1436 file_free_block(file, newblock);
1437 out_err:
1438 return -1;
1441 /* Ensure that blockoff points to an up-to-date non-virtual block.
1442 * Load the data from disk if necessary, return 0 on success. */
1443 size_t
1444 hed_prepare_read(struct hed_file *file, const hed_cursor_t *curs, size_t len)
1446 struct file_block *block = curs->block;
1447 if (block_is_virtual(block) && block->phys_pos < file->phys_size &&
1448 devirtualize_clean(file, curs) < 0)
1449 return 0;
1451 return hed_cursor_chunk_len(curs, len);
1454 /* Move the block pointer to the next block */
1455 static int
1456 blockoff_next_block(struct hed_file *file, blockoff_t *blockoff)
1458 struct file_block *block = blockoff->block;
1460 do {
1461 block = next_block(block);
1462 if (!is_a_block(file_blocks(file), block))
1463 return -1;
1464 } while (!block->t.size);
1466 blockoff->block = block;
1467 blockoff->off = 0;
1468 list_move(&blockoff->list, &block->refs);
1469 return 0;
1472 /* This is an optimized way of doing:
1474 * hed_move_relative(blockoff, blockoff->block->t.size);
1476 * for the case when blockoff->off == 0.
1478 static int
1479 move_to_next(struct hed_file *file, blockoff_t *blockoff)
1481 blockoff->pos += blockoff->block->t.size;
1482 return blockoff_next_block(file, blockoff);
1485 /* Copy in @count bytes from @pos.
1486 * Returns the number of bytes that were not read (i.e. zero on success).
1487 * The @pos blockoff is moved by the amount of data read.
1488 * CAUTION: If you read up to EOF, then @pos points to the null_block
1489 * upon return.
1491 static size_t
1492 copy_in(struct hed_file *file, void *buf, size_t count, blockoff_t *pos)
1494 size_t cpylen;
1496 assert(is_a_block(file_blocks(file), pos->block));
1498 pos->pos += count;
1499 while (count && (cpylen = hed_prepare_read(file, pos, count))) {
1500 if (block_is_virtual(pos->block))
1501 memset(buf, 0, cpylen);
1502 else
1503 memcpy(buf, block_data(pos->block) + pos->off, cpylen);
1505 buf += cpylen;
1506 count -= cpylen;
1507 if ( (pos->off += cpylen) >= hed_block_size(pos->block) )
1508 if (blockoff_next_block(file, pos))
1509 break;
1511 pos->pos -= count;
1512 return count;
1515 size_t
1516 hed_file_cpin(struct hed_file *file, void *buf, size_t count,
1517 const hed_cursor_t *pos)
1519 blockoff_t mypos;
1520 size_t ret;
1522 hed_dup_cursor(pos, &mypos);
1523 ret = copy_in(file, buf, count, &mypos);
1524 hed_put_cursor(&mypos);
1525 return ret;
1528 /* Set the modified flag */
1529 static inline void
1530 set_modified(struct hed_file *file)
1532 file->modified = true;
1535 /* Clear the modified flag */
1536 static inline void
1537 clear_modified(struct hed_file *file)
1539 file->modified = false;
1543 hed_file_set_byte(struct hed_file *file, blockoff_t *blockoff,
1544 unsigned char byte)
1546 hed_uoff_t offset = blockoff->pos;
1548 if (prepare_modify(file, blockoff, 1))
1549 return -1;
1550 set_modified(file);
1552 if (offset >= file->size)
1553 file->size = offset + 1;
1555 block_data(blockoff->block)[blockoff->off] = byte;
1556 return 0;
1559 size_t
1560 hed_file_set_block(struct hed_file *file, blockoff_t *blockoff,
1561 unsigned char *buf, size_t len)
1563 while (len) {
1564 size_t span;
1566 if (prepare_modify(file, blockoff, len))
1567 break;
1568 set_modified(file);
1570 span = hed_cursor_chunk_len(blockoff, len);
1571 memcpy(block_data(blockoff->block) + blockoff->off,
1572 buf, span);
1573 buf += span;
1574 len -= span;
1575 move_rel_fast(blockoff, span);
1577 if (blockoff->pos > file->size)
1578 file->size = blockoff->pos;
1580 return len;
1583 hed_uoff_t
1584 hed_file_set_bytes(struct hed_file *file, blockoff_t *blockoff,
1585 unsigned char byte, hed_uoff_t rep)
1587 while (rep) {
1588 size_t span;
1590 if (prepare_modify(file, blockoff, rep))
1591 break;
1592 set_modified(file);
1594 span = hed_cursor_chunk_len(blockoff, rep);
1595 memset(block_data(blockoff->block) + blockoff->off,
1596 byte, span);
1597 rep -= span;
1598 move_rel_fast(blockoff, span);
1600 if (blockoff->pos > file->size)
1601 file->size = blockoff->pos;
1603 return rep;
1606 static int
1607 file_erase_continuous(struct hed_file *file, blockoff_t *blockoff, size_t len)
1609 struct file_block *block = blockoff->block;
1610 hed_uoff_t block_offset = blockoff->off;
1611 blockoff_t *cur;
1613 /* Move to the new position, so blockoff does not get destroyed */
1614 hed_move_relative(blockoff, len);
1616 assert(len > 0);
1617 nuke_blockoffs(block, block_offset,
1618 block_offset + len - (len < block->t.size));
1620 if (!block_offset) {
1621 block->dataoff += len;
1622 if (!block_is_inserted(block))
1623 block->phys_pos += len;
1624 } else if (block_offset + len < block->t.size &&
1625 !split_block(file, block, block_offset + len))
1626 return -1;
1628 move_blockoffs(block, block, block_offset, UOFF_MAX, -(hed_uoff_t)len);
1630 block->t.size -= len;
1631 recalc_block_recursive(file_blocks(file), block);
1633 /* Move the insert point if needed */
1634 list_for_each_entry(cur, &block->refs, list)
1635 if (cur->off >= block->t.size)
1636 cur->pos -= len;
1638 kill_block_if_empty(file, block);
1639 return 0;
1642 size_t
1643 hed_file_erase_block(struct hed_file *file, blockoff_t *blockoff,
1644 hed_uoff_t len)
1646 hed_uoff_t offset;
1647 hed_uoff_t todo;
1648 struct file_block *eofblock;
1650 offset = blockoff->pos;
1651 if (offset > file_size(file))
1652 return 0;
1653 else if (len > file_size(file) - offset)
1654 len = file_size(file) - offset;
1656 todo = len;
1657 while (todo) {
1658 size_t span = hed_cursor_chunk_len(blockoff, todo);
1660 if (file_erase_continuous(file, blockoff, span))
1661 break;
1663 todo -= span;
1665 len -= todo;
1667 file->size -= len;
1668 set_modified(file);
1670 eofblock = last_block(file_blocks(file));
1671 assert(block_is_virtual(eofblock));
1672 assert(block_is_eof(eofblock));
1673 eofblock->t.size += len;
1674 recalc_block_recursive(file_blocks(file), eofblock);
1676 slide_blockoffs(file, blockoff->block, blockoff->pos, -len);
1678 return todo;
1682 hed_file_insert_begin(struct hed_file *file, const hed_cursor_t *curs,
1683 hed_cursor_t *curs_ins)
1685 struct file_block *block, *newblock;
1687 BDEBUG("Starting insert at %llx\n", curs->pos);
1689 newblock = new_block(file,
1690 HED_BLOCK_EXCACHE | HED_BLOCK_INSERTED);
1691 if (!newblock)
1692 return -1;
1694 newblock->phys_pos = hed_cursor_phys_pos(curs);
1695 newblock->dataobj = block_data_new(file->cache, FILE_BLOCK_SIZE);
1696 if (!newblock->dataobj) {
1697 file_free_block(file, newblock);
1698 return -1;
1701 if (curs->off) {
1702 if (!split_block(file, curs->block, curs->off)) {
1703 file_free_block(file, newblock);
1704 return -1;
1706 block = curs->block;
1707 } else
1708 block = prev_block(curs->block);
1710 chain_block_after(file_blocks(file), block, newblock);
1712 curs_ins->pos = curs->pos;
1713 curs_ins->off = newblock->t.size;
1714 curs_ins->block = newblock;
1715 list_add(&curs_ins->list, &newblock->refs);
1717 dump_blocks(file);
1718 return 0;
1721 void
1722 hed_file_insert_end(struct hed_file *file, blockoff_t *blockoff_ins)
1724 struct file_block *block = blockoff_ins->block;
1726 BDEBUG("End insert at %llx\n", blockoff_ins->pos);
1728 blockoff_ins->block = NULL;
1729 list_del(&blockoff_ins->list);
1730 if (!kill_block_if_empty(file, block))
1731 block_data_shrink(file->cache, block->dataobj, block->t.size);
1733 dump_blocks(file);
1736 static void
1737 insert_block(struct hed_file *file, blockoff_t *blockoff,
1738 unsigned char *buf, size_t len)
1740 struct file_block *block = blockoff->block;
1741 hed_uoff_t offset = blockoff->pos;
1743 assert(file && offset >= 0);
1745 assert(block_is_excache(block));
1746 block_set_dirty(block);
1747 set_modified(file);
1749 memcpy(block_data(block) + blockoff->off, buf, len);
1750 block->t.size += len;
1751 recalc_block_recursive(file_blocks(file), block);
1752 blockoff->off += len;
1753 blockoff->pos += len;
1755 if (blockoff->pos > file->size)
1756 file->size = blockoff->pos;
1757 else
1758 file->size += len;
1760 slide_blockoffs(file, next_block(block), offset, len);
1763 size_t
1764 hed_file_insert_block(struct hed_file *file, blockoff_t *blockoff,
1765 unsigned char *buf, size_t len)
1767 while (len) {
1768 struct file_block *block = blockoff->block;
1769 size_t remain = block->dataobj->size - blockoff->off;
1771 if (!remain) {
1772 list_del(&blockoff->list);
1773 blockoff->block = next_block(block);
1774 blockoff->off = 0;
1776 if (!hed_file_insert_begin(file, blockoff, blockoff))
1777 continue;
1779 blockoff->block = block;
1780 blockoff->off = block->t.size;
1781 list_add(&blockoff->list, &block->refs);
1782 break;
1785 if (remain > len)
1786 remain = len;
1788 BDEBUG("Append %ld bytes to the insert block\n",
1789 (long) remain);
1790 insert_block(file, blockoff, buf, remain);
1791 buf += remain;
1792 len -= remain;
1794 return len;
1798 hed_file_insert_byte(struct hed_file *file, blockoff_t *blockoff,
1799 unsigned char byte)
1801 return hed_file_insert_block(file, blockoff, &byte, 1);
1804 size_t
1805 hed_file_insert_once(struct hed_file *file, blockoff_t *blockoff,
1806 unsigned char *buf, size_t len)
1808 blockoff_t insert;
1810 if (!hed_file_insert_begin(file, blockoff, &insert)) {
1811 len = hed_file_insert_block(file, &insert, buf, len);
1812 hed_file_insert_end(file, &insert);
1814 return len;
1817 struct commit_control {
1818 struct hed_file *file;
1819 int wfd; /* file descriptor for writing */
1820 int needwrite; /* non-zero if write is needed */
1821 blockoff_t begoff, endoff;
1822 hed_off_t shift;
1823 void *partbuf; /* allocated 3*FILE_BLOCK_SIZE */
1824 void *partial; /* pointer into partbuf */
1827 /* Get the logical<->physical shift value after the specified block.
1828 * It is essential to get the value _AFTER_ the block, because the
1829 * shift value is used to decide how the current block will be handled.
1831 static hed_off_t
1832 get_shift(const blockoff_t *blockoff)
1834 struct file_block *block = blockoff->block;
1835 size_t curshift = block_is_inserted(block) ? block->t.size : 0;
1836 return curshift +
1837 blockoff->pos - blockoff->off - block->phys_pos;
1840 static void
1841 switch_partial(struct commit_control *cc)
1843 cc->partial += FILE_BLOCK_SIZE;
1844 if (cc->partial >= cc->partbuf + 3*FILE_BLOCK_SIZE)
1845 cc->partial = cc->partbuf;
1848 /* Write @writelen bytes from the partial buffer at @cc->begoff. */
1849 static int
1850 commit_block(struct commit_control *cc, size_t len)
1852 ssize_t written;
1854 assert(len > 0);
1855 BDEBUG(" -> write %lx bytes at %llx\n",
1856 (unsigned long)len, cc->begoff.pos - len);
1857 written = pwrite(cc->wfd, cc->partial, len, cc->begoff.pos - len);
1858 if (written < len)
1859 /* TODO: keep data in a new list of dirty blocks */
1860 return -1;
1861 return 0;
1864 static int
1865 commit_partial(struct commit_control *cc)
1867 size_t partoff, remain, left;
1868 size_t writelen;
1870 partoff = FILE_BLOCK_OFF(cc->begoff.pos);
1871 remain = FILE_BLOCK_SIZE - partoff;
1872 if (remain > cc->endoff.pos - cc->begoff.pos)
1873 remain = cc->endoff.pos - cc->begoff.pos;
1874 if ((writelen = partoff + remain) == 0)
1875 return 0;
1877 BDEBUG("Fill partial %llx-%llx\n",
1878 cc->begoff.pos, cc->begoff.pos + remain);
1880 left = copy_in(cc->file, cc->partial + partoff, remain, &cc->begoff);
1881 if (left) {
1882 hed_move_relative(&cc->begoff, left);
1883 return -1;
1886 if (FILE_BLOCK_OFF(cc->begoff.pos) && !block_is_eof(cc->begoff.block))
1887 return 0;
1889 return commit_block(cc, writelen);
1892 /* Commit forwards.
1893 * Beware, cc->begoff is undefined upon return!
1895 static int
1896 commit_forwards(struct commit_control *cc)
1898 hed_uoff_t endpos = cc->endoff.pos;
1899 int ret = 0;
1901 BDEBUG("Writing forwards %llx-%llx\n",
1902 cc->begoff.pos, cc->endoff.pos);
1904 if (!cc->needwrite)
1905 return 0;
1907 while (cc->begoff.pos < endpos)
1908 ret |= commit_partial(cc);
1910 return ret;
1913 /* Commit forwards.
1914 * Beware, cc->begoff is undefined upon return!
1916 static int
1917 commit_backwards(struct commit_control *cc)
1919 void *retpartial = cc->partial;
1920 hed_uoff_t begpos = cc->begoff.pos;
1921 hed_uoff_t blkpos; /* start of current partial block */
1922 int ret = 0;
1924 BDEBUG("Writing backwards %llx-%llx\n",
1925 cc->begoff.pos, cc->endoff.pos);
1927 if (!cc->needwrite)
1928 return 0;
1930 blkpos = FILE_BLOCK_ROUND(cc->endoff.pos);
1931 if (blkpos <= begpos)
1932 goto final;
1934 /* Handle the trailing partial block */
1935 hed_get_cursor(cc->file, blkpos, &cc->begoff);
1936 switch_partial(cc);
1937 ret |= commit_partial(cc);
1938 retpartial = cc->partial;
1940 /* Handle the middle part */
1941 switch_partial(cc);
1942 while ( (blkpos -= FILE_BLOCK_SIZE) > begpos) {
1943 hed_get_cursor(cc->file, blkpos, &cc->begoff);
1944 ret |= commit_partial(cc);
1946 switch_partial(cc); /* wrap around */
1948 final:
1949 /* Handle the first block (partiall or not) */
1950 hed_get_cursor(cc->file, begpos, &cc->begoff);
1951 ret |= commit_partial(cc);
1953 cc->partial = retpartial;
1954 return ret;
1957 /* Handle the partial block before a skipped one. */
1958 static int
1959 begin_skip(struct commit_control *cc)
1961 size_t minsize = FILE_BLOCK_SIZE - FILE_BLOCK_OFF(cc->endoff.pos);
1962 size_t remain;
1963 int ret = 0;
1965 /* Check if at least one complete physical block can be skipped */
1966 if (cc->endoff.block->t.size < minsize)
1967 return 0;
1969 /* Write out the partially dirty block */
1970 remain = FILE_BLOCK_OFF(minsize);
1971 hed_move_relative(&cc->endoff, remain);
1972 if (cc->shift <= 0)
1973 ret |= commit_forwards(cc);
1974 else
1975 ret |= commit_backwards(cc);
1976 hed_move_relative(&cc->endoff, -(hed_off_t)remain);
1977 hed_dup2_cursor(&cc->endoff, &cc->begoff);
1979 cc->needwrite = 0;
1980 return ret;
1983 /* Handle the last partially skipped physical block. */
1984 static int
1985 end_skip(struct commit_control *cc)
1987 size_t partlen;
1988 int ret = 0;
1990 /* Find the beginning of the physical block */
1991 hed_dup2_cursor(&cc->endoff, &cc->begoff);
1992 partlen = FILE_BLOCK_OFF(cc->begoff.pos);
1993 hed_move_relative(&cc->begoff, -(hed_off_t)partlen);
1995 /* Read the partial data before this block */
1996 if (hed_file_cpin(cc->file, cc->partial, partlen, &cc->begoff))
1997 ret = -1;
1999 cc->needwrite = 1;
2000 return ret;
2003 static void
2004 undirty_blocks(struct hed_file *file)
2006 struct file_block *block, *next;
2007 hed_uoff_t pos = 0;
2009 BDEBUG("Undirtying blocks:\n");
2010 dump_blocks(file);
2012 foreachsafe_block (block, next, file_blocks(file)) {
2013 if (kill_block_if_empty(file, block))
2014 continue;
2016 if (!block_is_virtual(block)) {
2017 cache_put(file->cache, block->dataobj);
2018 block->dataobj = NULL;
2019 list_del_init(&block->lru);
2020 block->flags = HED_BLOCK_EXCACHE | HED_BLOCK_VIRTUAL;
2023 block->phys_pos = pos;
2024 pos += block->t.size;
2027 block = first_block(file_blocks(file));
2028 while (!block_is_eof(block)) {
2029 next = next_block(block);
2030 file_kill_block(file, block);
2031 block = next;
2034 BDEBUG("After undirtying\n");
2035 dump_blocks(file);
2038 static int
2039 commit_init(struct commit_control *cc, struct hed_file *file)
2041 cc->file = file;
2043 cc->partbuf = malloc(3*FILE_BLOCK_SIZE);
2044 if (!cc->partbuf)
2045 goto err;
2047 cc->wfd = open(file->name,
2048 O_RDWR | (file->fd < 0 ? O_CREAT : 0), 0666);
2049 if (cc->wfd < 0)
2050 goto err_free;
2052 if (file->fd < 0 &&
2053 (file->fd = open(file->name, O_RDONLY)) < 0)
2054 goto err_close;
2056 return 0;
2058 err_close:
2059 close(cc->wfd);
2060 err_free:
2061 free(cc->partbuf);
2062 err:
2063 return -1;
2067 hed_file_commit(struct hed_file *file)
2069 struct commit_control cc;
2070 int ret = 0;
2072 if (commit_init(&cc, file))
2073 return -1;
2075 dump_blocks(file);
2077 cc.partial = cc.partbuf;
2078 get_cursor(file, 0,&cc.begoff);
2079 hed_dup_cursor(&cc.begoff, &cc.endoff);
2080 cc.shift = -cc.begoff.block->phys_pos;
2081 cc.needwrite = 0;
2082 while(!block_is_eof(cc.endoff.block)) {
2083 hed_off_t newshift = cc.endoff.pos < file->phys_size
2084 ? get_shift(&cc.endoff)
2085 : 0;
2087 if (cc.shift <= 0 && newshift > 0) {
2088 ret |= commit_forwards(&cc);
2089 hed_dup2_cursor(&cc.endoff, &cc.begoff);
2090 } else if (cc.shift > 0 && newshift <= 0) {
2091 ret |= commit_backwards(&cc);
2092 hed_dup2_cursor(&cc.endoff, &cc.begoff);
2094 cc.shift = newshift;
2096 if (!newshift && !block_is_dirty(cc.endoff.block)) {
2097 if (cc.needwrite)
2098 ret |= begin_skip(&cc);
2099 } else if (!cc.needwrite)
2100 ret |= end_skip(&cc);
2102 if (move_to_next(file, &cc.endoff))
2103 break;
2105 assert(cc.endoff.pos == file_size(file));
2107 if (cc.begoff.pos < file_size(file)) {
2108 if (cc.shift <= 0)
2109 ret |= commit_forwards(&cc);
2110 else
2111 ret |= commit_backwards(&cc);
2114 hed_put_cursor(&cc.begoff);
2115 hed_put_cursor(&cc.endoff);
2117 ftruncate(cc.wfd, file_size(file));
2118 file->phys_size = file_size(file);
2120 ret |= close(cc.wfd);
2121 free(cc.partbuf);
2123 undirty_blocks(file);
2125 if (!ret)
2126 clear_modified(file);
2128 return ret;
2131 #ifdef HED_CONFIG_SWAP
2133 hed_file_write_swap(struct hed_file *file)
2135 return swp_write(file_swp(file));
2138 static int
2139 do_read_swap(struct hed_file *file, struct swp_file *swp, blockoff_t *pos)
2141 struct hed_file *swpfile = swp_private(swp);
2142 struct file_block *cur, block;
2143 hed_uoff_t phys_pos;
2145 if (file_stat(swpfile)->st_size != file_stat(file)->st_size ||
2146 file_stat(swpfile)->st_mtime != file_stat(file)->st_mtime) {
2147 fprintf(stderr, "stat info mismatch (you modified the file since hed ran on it; refusing to touch it)\n");
2148 return -1;
2151 BDEBUG("Swap header match\n");
2153 phys_pos = 0;
2154 for (cur = first_block(file_blocks(swpfile));
2155 cur != swpfile->null_block; cur = next_block(&block)) {
2156 struct hed_block_data dataobj;
2157 size_t (*mergefn)(struct hed_file*, blockoff_t*,
2158 unsigned char*, size_t);
2159 void *data;
2160 size_t res;
2162 if (swp_cpin(swp, &block, cur, sizeof(struct file_block))) {
2163 perror("Cannot read block descriptor");
2164 return -1;
2166 BDEBUG("BLOCK %p: flags %02lx phys 0x%02llx size 0x%llx\n",
2167 cur, block.flags, (long long)block.phys_pos,
2168 (long long)hed_block_size(&block));
2170 if (block.phys_pos - phys_pos) {
2171 if (hed_file_erase_block(file, pos,
2172 block.phys_pos - phys_pos)) {
2173 perror("Cannot erase");
2174 return -1;
2176 phys_pos = block.phys_pos;
2179 if (!block_is_inserted(&block))
2180 phys_pos += hed_block_size(&block);
2182 if (!block_is_dirty(&block)) {
2183 hed_move_relative(pos, hed_block_size(&block));
2184 continue;
2187 if (swp_cpin(swp, &dataobj, block.dataobj,
2188 sizeof(struct hed_block_data))) {
2189 perror("Cannot read data descriptor");
2190 return -1;
2192 BDEBUG("DATA %p: size 0x%lx\n",
2193 block.dataobj, (long)dataobj.size);
2195 if (! (data = malloc(hed_block_size(&block))) ) {
2196 perror("Cannot allocate data");
2197 return -1;
2200 if (swp_cpin(swp, data, dataobj.data + block.dataoff,
2201 hed_block_size(&block))) {
2202 perror("Cannot read data");
2203 return -1;
2206 mergefn = block_is_inserted(&block)
2207 ? hed_file_insert_once
2208 : hed_file_set_block;
2209 res = mergefn(file, pos, data, hed_block_size(&block));
2210 free(data);
2211 if (res) {
2212 perror("Cannot merge data");
2213 return -1;
2217 dump_blocks(file);
2218 return 0;
2222 hed_file_read_swap(struct hed_file *file)
2224 struct swp_file *swp;
2225 blockoff_t pos;
2226 int ret;
2228 if (! (swp = swp_init_read(file->swpname)) )
2229 return -1;
2231 get_cursor(file, 0, &pos);
2232 ret = do_read_swap(file, swp, &pos);
2233 hed_put_cursor(&pos);
2235 swp_done(swp);
2236 return ret;
2239 #endif /* HED_CONFIG_SWAP */
2241 struct ffb_hookdata {
2242 struct hed_file *file;
2243 blockoff_t *pos;
2244 hed_expr_reg_cb base_ecb;
2245 void *base_ecb_data;
2248 static long
2249 eval_reg_cb(void *hookdata, char reg, hed_off_t ofs,
2250 unsigned char *scramble, size_t len)
2252 struct ffb_hookdata *data = hookdata;
2253 if (reg == '.') {
2254 blockoff_t pos;
2255 long ret = HED_AEF_DYNAMIC;
2257 hed_dup_cursor(data->pos, &pos);
2258 hed_move_relative(&pos, ofs);
2259 if (copy_in(data->file, scramble, len, &pos))
2260 ret = HED_AEF_ERROR;
2261 hed_put_cursor(&pos);
2262 return ret;
2265 return data->base_ecb(data->base_ecb_data, reg, ofs, scramble, len);
2268 static void
2269 reverse(unsigned char *p, size_t len)
2271 unsigned char *q = p + len;
2272 while (p < q) {
2273 unsigned char x = *p;
2274 *p++ = *--q;
2275 *q = x;
2279 static void
2280 compute_badchar(ssize_t *badchar, const unsigned char *s, ssize_t len)
2282 size_t i = 1;
2283 while (i < len)
2284 badchar[*s++] = i++;
2287 static void
2288 compute_sfx(ssize_t *sfx, const unsigned char *s, ssize_t len)
2290 ssize_t f, g, i;
2292 sfx[len - 1] = len;
2293 g = len - 1;
2294 for (i = len - 2; i >= 0; --i) {
2295 if (i > g && sfx[i + len - 1 - f] < i - g)
2296 sfx[i] = sfx[i + len - 1 - f];
2297 else {
2298 if (i < g)
2299 g = i;
2300 f = i;
2301 while (g >= 0 && s[g] == s[g + len - 1 - f])
2302 --g;
2303 sfx[i] = f - g;
2308 static void
2309 compute_goodsfx(ssize_t *goodsfx, const unsigned char *s, ssize_t len)
2311 ssize_t i, j, *sfx = goodsfx + len;
2313 compute_sfx(sfx, s, len);
2315 for (i = 0; i < len; ++i)
2316 goodsfx[i] = len;
2317 j = 0;
2318 for (i = len - 1; i >= 0; --i)
2319 if (sfx[i] == i + 1)
2320 for (; j < len - 1 - i; ++j)
2321 if (goodsfx[j] == len)
2322 goodsfx[j] = len - 1 - i;
2323 for (i = 0; i <= len - 2; ++i)
2324 goodsfx[len - 1 - sfx[i]] = len - 1 - i;
2327 /* Search for a constant byte string using the Boyer-Moore algorithm.
2328 * If @rev is non-zero, search backwards, otherwise search forwards.
2330 static inline unsigned char*
2331 find_bytestr_buf(unsigned char *buf, ssize_t buflen,
2332 unsigned char *needle, ssize_t maxidx,
2333 ssize_t *badchar, ssize_t *goodsfx)
2335 int rev = 0;
2336 if (buflen < 0) {
2337 if (!maxidx)
2338 return memrchr(buf - buflen + 1, *needle, buflen);
2339 rev = 1;
2340 buflen = -buflen;
2341 buf -= maxidx;
2342 } else if (!maxidx)
2343 return memchr(buf, *needle, buflen);
2345 while (buflen > maxidx) {
2346 unsigned char *p;
2347 ssize_t shift, i;
2349 if (rev) {
2350 for (p = buf, i = maxidx; i >= 0; ++p, --i)
2351 if (needle[i] != *p)
2352 break;
2353 } else {
2354 for (p = buf + maxidx, i = maxidx; i >= 0; --p, --i)
2355 if (needle[i] != *p)
2356 break;
2359 if (i < 0)
2360 return buf;
2362 shift = i + 1 - badchar[*p];
2363 if (shift < goodsfx[i])
2364 shift = goodsfx[i];
2366 buf += rev ? -shift : shift;
2367 buflen -= shift;
2369 return NULL;
2372 /* Check if the search string is all zero */
2373 static int is_allzero(unsigned char *s, size_t len)
2375 while (len--)
2376 if (*s++)
2377 return 0;
2378 return 1;
2381 /* A helper function for doing cpin forwards or backwards inside the
2382 * find_bytestr() inner loop
2384 static inline void*
2385 find_cpin(struct hed_file *file, void *buf, ssize_t len, blockoff_t *pos)
2387 if (len < 0) {
2388 move_rel_fast(pos, len + 1);
2389 if (hed_file_cpin(file, buf, -len, pos))
2390 return NULL;
2391 --pos->off;
2392 --pos->pos;
2393 return buf - len - 1;
2394 } else if (!copy_in(file, buf, len, pos))
2395 return buf;
2396 else
2397 return NULL;
2400 /* Search for a constant byte string using the Boyer-Moore algorithm. */
2401 static int
2402 find_bytestr(struct hed_file *file, blockoff_t *from, int dir,
2403 unsigned char *needle, ssize_t len)
2405 void *dynalloc;
2406 ssize_t *badchar, *goodsfx;
2407 unsigned char *readbuf;
2408 ssize_t slen;
2409 int ret;
2411 if (len > 1) {
2412 dynalloc = calloc(sizeof(ssize_t) * (256 + 2*len)
2413 + 2*(len-1), 1);
2414 if (!dynalloc)
2415 return HED_FINDOFF_ERROR;
2416 badchar = dynalloc;
2417 goodsfx = badchar + 256;
2418 readbuf = dynalloc + sizeof(ssize_t) * (256 + 2*len);
2420 if (dir < 0)
2421 reverse(needle, len);
2422 compute_badchar(badchar, needle, len);
2423 compute_goodsfx(goodsfx, needle, len);
2424 } else {
2425 dynalloc = NULL;
2426 badchar = goodsfx = NULL;
2427 readbuf = NULL;
2430 --len; /* simplify offset computing */
2431 if (dir < 0) {
2432 move_rel_fast(from, len);
2433 slen = -len;
2434 } else
2435 slen = len;
2437 ret = HED_FINDOFF_NO_MATCH;
2438 while (from->pos >= 0 && !block_is_eof(from->block)) {
2439 hed_off_t remain = hed_prepare_read(file, from, SIZE_MAX);
2441 if (!remain) {
2442 ret = HED_FINDOFF_ERROR;
2443 break;
2445 if (dir < 0)
2446 remain = -(from->off + 1);
2448 if (!block_is_virtual(from->block)) {
2449 unsigned char *p, *q;
2451 if ((dir >= 0 && remain > slen) ||
2452 (dir < 0 && remain < slen)) {
2453 p = block_data(from->block) + from->off;
2454 from->off += remain;
2455 from->pos += remain;
2456 } else {
2457 remain += slen;
2458 p = find_cpin(file, readbuf, remain, from);
2459 if (!p) {
2460 ret = HED_FINDOFF_ERROR;
2461 break;
2465 q = find_bytestr_buf(p, remain, needle, len,
2466 badchar, goodsfx);
2467 if (q) {
2468 hed_move_relative(from, q - p - remain);
2469 ret = 0;
2470 break;
2472 } else if (!is_allzero(needle, len + 1)) {
2473 from->off += remain;
2474 from->pos += remain;
2475 } else {
2476 ret = 0;
2477 break;
2480 move_rel_fast(from, -slen);
2483 if (dynalloc)
2484 free(dynalloc);
2485 return ret;
2488 static int
2489 find_expr(struct hed_file *file, blockoff_t *from, int dir,
2490 struct hed_expr *expr, struct ffb_hookdata *data)
2492 int len = hed_expr_len(expr);
2493 unsigned char *buf;
2495 assert(len > 0);
2497 if (len > file_size(file))
2498 return HED_FINDOFF_NO_MATCH;
2499 if ((hed_off_t)file_size(file) - from->pos - len < 0)
2500 hed_move_relative(from,
2501 (hed_off_t)file_size(file) - from->pos - len);
2503 for (;;) {
2504 blockoff_t match;
2505 size_t remain;
2506 unsigned char *p;
2507 int pos;
2509 buf = hed_expr_eval(expr, eval_reg_cb, NULL, data);
2510 if (!buf)
2511 return HED_FINDOFF_ERROR;
2513 hed_dup_cursor(from, &match);
2514 remain = 0;
2515 for (pos = 0; pos < len; pos++) {
2516 if (!remain) {
2517 remain = hed_prepare_read(file, &match,
2518 SIZE_MAX);
2519 if (!remain)
2520 break;
2521 p = block_data(match.block) + match.off;
2523 if (*p++ != buf[pos])
2524 break;
2525 remain--;
2527 hed_put_cursor(&match);
2529 if (pos == len)
2530 return 0;
2531 if (!remain)
2532 return HED_FINDOFF_ERROR;
2534 from->pos += dir;
2535 from->off += dir;
2536 if (0 > from->pos || from->pos > file_size(file) - len)
2537 break;
2538 fixup_blockoff(from);
2540 if (! (hed_expr_flags(expr) & HED_AEF_DYNAMIC) )
2541 return find_bytestr(file, from, dir, buf, len);
2544 return HED_FINDOFF_NO_MATCH;
2548 hed_file_find_expr(struct hed_file *file, blockoff_t *pos, int dir,
2549 struct hed_expr *expr,
2550 hed_expr_reg_cb expr_cb, void *expr_cb_data)
2552 struct ffb_hookdata data;
2553 int res;
2555 assert(dir == 1 || dir == -1);
2557 data.file = file;
2558 data.pos = pos;
2559 data.base_ecb = expr_cb;
2560 data.base_ecb_data = expr_cb_data;
2562 hed_file_set_readahead(file,
2563 dir > 0 ? HED_RA_FORWARD : HED_RA_BACKWARD);
2564 res = find_expr(file, pos, dir, expr, &data);
2565 hed_file_set_readahead(file, HED_RA_NONE);
2567 return res;