2 /* $OpenBSD: mmfile.c,v 1.11 2006/09/19 05:52:23 otto Exp $ */
5 * Copyright (c) 1999 James Howard and Dag-Erling Coïdan Smørgrav
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 #include <sys/param.h>
41 #define MAX_MAP_LEN 1048576
44 mmopen(char *fn
, char *mode
)
49 /* XXX ignore mode for now */
52 mmf
= grep_malloc(sizeof *mmf
);
53 if ((mmf
->fd
= open(fn
, O_RDONLY
)) == -1)
55 if (fstat(mmf
->fd
, &st
) == -1)
57 if (st
.st_size
> SIZE_T_MAX
) /* too big to mmap */
59 if (!S_ISREG(st
.st_mode
)) /* only mmap regular files */
61 mmf
->len
= (size_t)st
.st_size
;
62 mmf
->base
= mmap(NULL
, mmf
->len
, PROT_READ
, MAP_PRIVATE
, mmf
->fd
, (off_t
)0);
63 if (mmf
->base
== MAP_FAILED
)
66 mmf
->end
= mmf
->base
+ mmf
->len
;
68 madvise(mmf
->base
, mmf
->len
, MADV_SEQUENTIAL
);
82 munmap(mmf
->base
, mmf
->len
);
88 mmfgetln(mmf_t
*mmf
, size_t *l
)
91 char *start
= mmf
->ptr
; /* Remove speed bump */
92 char *end
= mmf
->end
; /* Remove speed bump */
96 for (p
= mmf
->ptr
; mmf
->ptr
< mmf
->end
; ++mmf
->ptr
)
97 if (*mmf
->ptr
== '\n')