GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: usr.bin/vi/build/../ex/ex_source.c Lines: 0 25 0.0 %
Date: 2017-11-07 Branches: 0 16 0.0 %

Line Branch Exec Source
1
/*	$OpenBSD: ex_source.c,v 1.10 2015/12/07 20:39:19 mmcc 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
#include <sys/types.h>
15
#include <sys/queue.h>
16
#include <sys/stat.h>
17
18
#include <bitstring.h>
19
#include <errno.h>
20
#include <fcntl.h>
21
#include <limits.h>
22
#include <stdio.h>
23
#include <stdlib.h>
24
#include <string.h>
25
#include <unistd.h>
26
27
#include "../common/common.h"
28
29
/*
30
 * ex_sourcefd -- :source already opened file
31
 *	Execute ex commands from the given file descriptor
32
 *
33
 * PUBLIC: int ex_sourcefd(SCR *, EXCMD *, int);
34
 */
35
int
36
ex_sourcefd(SCR *sp, EXCMD *cmdp, int fd)
37
{
38
	struct stat sb;
39
	int len;
40
	char *bp, *name;
41
42
	name = cmdp->argv[0]->bp;
43
	if (fstat(fd, &sb))
44
		goto err;
45
46
	/*
47
	 * XXX
48
	 * I'd like to test to see if the file is too large to malloc.  Since
49
	 * we don't know what size or type off_t's or size_t's are, what the
50
	 * largest unsigned integral type is, or what random insanity the local
51
	 * C compiler will perpetrate, doing the comparison in a portable way
52
	 * is flatly impossible.  So, put an fairly unreasonable limit on it,
53
	 * I don't want to be dropping core here.
54
	 */
55
#define	MEGABYTE	1048576
56
	if (sb.st_size > MEGABYTE) {
57
		errno = ENOMEM;
58
		goto err;
59
	}
60
61
	MALLOC(sp, bp, (size_t)sb.st_size + 1);
62
	if (bp == NULL) {
63
		(void)close(fd);
64
		return (1);
65
	}
66
	bp[sb.st_size] = '\0';
67
68
	/* Read the file into memory. */
69
	len = read(fd, bp, (int)sb.st_size);
70
	(void)close(fd);
71
	if (len == -1 || len != sb.st_size) {
72
		if (len != sb.st_size)
73
			errno = EIO;
74
		free(bp);
75
err:		msgq_str(sp, M_SYSERR, name, "%s");
76
		return (1);
77
	}
78
79
	/* Put it on the ex queue. */
80
	return (ex_run_str(sp, name, bp, (size_t)sb.st_size, 1, 1));
81
}
82
83
/*
84
 * ex_source -- :source file
85
 *	Execute ex commands from a file.
86
 *
87
 * PUBLIC: int ex_source(SCR *, EXCMD *);
88
 */
89
int
90
ex_source(SCR *sp, EXCMD *cmdp)
91
{
92
	char *name;
93
	int fd;
94
95
	name = cmdp->argv[0]->bp;
96
	if ((fd = open(name, O_RDONLY, 0)) >= 0)
97
		return (ex_sourcefd(sp, cmdp, fd));
98
99
	msgq_str(sp, M_SYSERR, name, "%s");
100
	return (1);
101
}