]> mj.ucw.cz Git - libucw.git/blob - lib/lizard-safe.c
6bba2544915ba142371e7400ad43a55d85263e27
[libucw.git] / lib / lizard-safe.c
1 /*
2  *      LiZaRd -- Fast compression method based on Lempel-Ziv 77
3  *
4  *      (c) 2004, Robert Spalek <robert@ucw.cz>
5  *
6  *      This software may be freely distributed and used according to the terms
7  *      of the GNU Lesser General Public License.
8  */
9
10 #include "lib/lib.h"
11 #include "lib/lizard.h"
12
13 #include <stdlib.h>
14 #include <sys/mman.h>
15 #include <sys/user.h>
16 #include <fcntl.h>
17 #include <signal.h>
18 #include <setjmp.h>
19 #include <errno.h>
20
21 struct lizard_buffer *
22 lizard_alloc(uns max_len)
23 {
24   struct lizard_buffer *buf = xmalloc(sizeof(struct lizard_buffer));
25   buf->len = ALIGN(max_len, PAGE_SIZE);
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)
30     die("mprotect: %m");
31   return buf;
32 }
33
34 void
35 lizard_free(struct lizard_buffer *buf)
36 {
37   munmap(buf->start, buf->len + PAGE_SIZE);
38   xfree(buf);
39 }
40
41 static jmp_buf safe_decompress_jump;
42 static void
43 sigsegv_handler(int UNUSED whatsit)
44 {
45   log(L_ERROR, "SIGSEGV caught in lizard_decompress()");
46   longjmp(safe_decompress_jump, 1);
47 }
48
49 int
50 lizard_decompress_safe(byte *in, struct lizard_buffer *buf, uns expected_length)
51   /* Decompresses into buf->ptr and returns the length of the uncompressed
52    * file.  If an error has occured, -1 is returned and errno is set.  SIGSEGV
53    * is caught in the case of buffer-overflow.  The function is not re-entrant
54    * because of a static longjmp handler.  */
55 {
56   uns lock_offset = ALIGN(expected_length + 3, PAGE_SIZE);      // +3 due to the unaligned access
57   if (lock_offset > buf->len)
58   {
59     errno = EFBIG;
60     return -1;
61   }
62   volatile sighandler_t old_handler = signal(SIGSEGV, sigsegv_handler);
63   int len, err;
64   if (!setjmp(safe_decompress_jump))
65   {
66     buf->ptr = buf->start + buf->len - lock_offset;
67     len = lizard_decompress(in, buf->ptr);
68     err = errno;
69   }
70   else
71   {
72     buf->ptr = NULL;
73     len = -1;
74     err = EFAULT;
75   }
76   signal(SIGSEGV, old_handler);
77   errno = err;
78   return len;
79 }