xref: /openbsd-src/usr.bin/vi/ex/ex_source.c (revision 2b0358df1d88d06ef4139321dd05bd5e05d91eaf)
1 /*	$OpenBSD: ex_source.c,v 1.6 2002/02/16 21:27:57 millert Exp $	*/
2 
3 /*-
4  * Copyright (c) 1992, 1993, 1994
5  *	The Regents of the University of California.  All rights reserved.
6  * Copyright (c) 1992, 1993, 1994, 1995, 1996
7  *	Keith Bostic.  All rights reserved.
8  *
9  * See the LICENSE file for redistribution information.
10  */
11 
12 #include "config.h"
13 
14 #ifndef lint
15 static const char sccsid[] = "@(#)ex_source.c	10.12 (Berkeley) 8/10/96";
16 #endif /* not lint */
17 
18 #include <sys/types.h>
19 #include <sys/queue.h>
20 #include <sys/stat.h>
21 
22 #include <bitstring.h>
23 #include <errno.h>
24 #include <fcntl.h>
25 #include <limits.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <unistd.h>
30 
31 #include "../common/common.h"
32 
33 /*
34  * ex_source -- :source file
35  *	Execute ex commands from a file.
36  *
37  * PUBLIC: int ex_source(SCR *, EXCMD *);
38  */
39 int
40 ex_source(sp, cmdp)
41 	SCR *sp;
42 	EXCMD *cmdp;
43 {
44 	struct stat sb;
45 	int fd, len;
46 	char *bp, *name;
47 
48 	name = cmdp->argv[0]->bp;
49 	if ((fd = open(name, O_RDONLY, 0)) < 0 || fstat(fd, &sb))
50 		goto err;
51 
52 	/*
53 	 * XXX
54 	 * I'd like to test to see if the file is too large to malloc.  Since
55 	 * we don't know what size or type off_t's or size_t's are, what the
56 	 * largest unsigned integral type is, or what random insanity the local
57 	 * C compiler will perpetrate, doing the comparison in a portable way
58 	 * is flatly impossible.  So, put an fairly unreasonable limit on it,
59 	 * I don't want to be dropping core here.
60 	 */
61 #define	MEGABYTE	1048576
62 	if (sb.st_size > MEGABYTE) {
63 		errno = ENOMEM;
64 		goto err;
65 	}
66 
67 	MALLOC(sp, bp, char *, (size_t)sb.st_size + 1);
68 	if (bp == NULL) {
69 		(void)close(fd);
70 		return (1);
71 	}
72 	bp[sb.st_size] = '\0';
73 
74 	/* Read the file into memory. */
75 	len = read(fd, bp, (int)sb.st_size);
76 	(void)close(fd);
77 	if (len == -1 || len != sb.st_size) {
78 		if (len != sb.st_size)
79 			errno = EIO;
80 		free(bp);
81 err:		msgq_str(sp, M_SYSERR, name, "%s");
82 		return (1);
83 	}
84 
85 	/* Put it on the ex queue. */
86 	return (ex_run_str(sp, name, bp, (size_t)sb.st_size, 1, 1));
87 }
88