2 * LiZaRd -- Fast compression method based on Lempel-Ziv 77
4 * (c) 2004, Robert Spalek <robert@ucw.cz>
6 * This software may be freely distributed and used according to the terms
7 * of the GNU Lesser General Public License.
11 #include "lib/lizard.h"
21 struct lizard_buffer *
22 lizard_alloc(uns max_len)
24 struct lizard_buffer *buf = xmalloc(sizeof(struct lizard_buffer));
25 buf->len = ALIGN(max_len + 3, PAGE_SIZE); // +3 due to the unaligned access
26 buf->start = mmap(NULL, buf->len + PAGE_SIZE, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
27 if (buf->start == MAP_FAILED)
28 die("mmap(anonymous): %m");
29 if (mprotect(buf->start + buf->len, PAGE_SIZE, PROT_NONE) < 0)
31 buf->old_sigsegv_handler = xmalloc(sizeof(struct sigaction));
32 handle_signal(SIGSEGV, buf->old_sigsegv_handler);
37 lizard_free(struct lizard_buffer *buf)
39 munmap(buf->start, buf->len + PAGE_SIZE);
40 sigaction(SIGSEGV, buf->old_sigsegv_handler, NULL);
41 xfree(buf->old_sigsegv_handler);
45 static jmp_buf safe_decompress_jump;
47 sigsegv_handler(int signal UNUSED)
49 log(L_ERROR, "SIGSEGV caught in lizard_decompress()");
50 longjmp(safe_decompress_jump, 1);
55 lizard_decompress_safe(byte *in, struct lizard_buffer *buf, uns expected_length)
56 /* Decompresses into buf->ptr and returns the length of the uncompressed
57 * file. If an error has occured, -1 is returned and errno is set. SIGSEGV
58 * is caught in the case of buffer-overflow. The function is not re-entrant
59 * because of a static longjmp handler. */
61 uns lock_offset = ALIGN(expected_length + 3, PAGE_SIZE); // +3 due to the unaligned access
62 if (lock_offset > buf->len)
67 volatile sh_sighandler_t old_handler = signal_handler[SIGSEGV];
68 signal_handler[SIGSEGV] = sigsegv_handler;
70 if (!setjmp(safe_decompress_jump))
72 buf->ptr = buf->start + buf->len - lock_offset;
73 len = lizard_decompress(in, buf->ptr);
82 signal_handler[SIGSEGV] = old_handler;