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