summaryrefslogtreecommitdiff
path: root/usr/src/lib/libc/port/stdio/getline.c
blob: bb55b40159738f29dcc8b31e8d69168dc35b063a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
 */

#include "lint.h"
#include "file64.h"
#include "mtlib.h"
#include <stdio.h>
#include <errno.h>
#include <thread.h>
#include <synch.h>
#include <unistd.h>
#include <limits.h>
#include <malloc.h>
#include <sys/types.h>
#include "stdiom.h"

#define	LINESZ	128	/* initial guess for a NULL *lineptr */

ssize_t
getdelim(char **_RESTRICT_KYWD lineptr, size_t *_RESTRICT_KYWD n,
    int delimiter, FILE *_RESTRICT_KYWD iop)
{
	rmutex_t *lk;
	char *ptr;
	size_t size;
	int c;
	size_t cnt;

	if (lineptr == NULL || n == NULL ||
	    delimiter < 0 || delimiter > UCHAR_MAX) {
		errno = EINVAL;
		return (-1);
	}

	if (*lineptr == NULL || *n < LINESZ) {	/* initial allocation */
		if ((*lineptr = realloc(*lineptr, LINESZ)) == NULL) {
			errno = ENOMEM;
			return (-1);
		}
		*n = LINESZ;
	}
	ptr = *lineptr;
	size = *n;
	cnt = 0;

	FLOCKFILE(lk, iop);

	_SET_ORIENTATION_BYTE(iop);

	do {
		c = (--iop->_cnt < 0) ? __filbuf(iop) : *iop->_ptr++;
		if (c == EOF)
			break;
		*ptr++ = c;
		if (++cnt == size) {	/* must reallocate */
			if ((ptr = realloc(*lineptr, 2 * size)) == NULL) {
				FUNLOCKFILE(lk);
				ptr = *lineptr + size - 1;
				*ptr = '\0';
				errno = ENOMEM;
				return (-1);
			}
			*lineptr = ptr;
			ptr += size;
			*n = size = 2 * size;
		}
	} while (c != delimiter);

	*ptr = '\0';

	FUNLOCKFILE(lk);
	if (cnt > SSIZE_MAX) {
		errno = EOVERFLOW;
		return (-1);
	}
	return (cnt ? cnt : -1);
}

ssize_t
getline(char **_RESTRICT_KYWD lineptr, size_t *_RESTRICT_KYWD n,
    FILE *_RESTRICT_KYWD iop)
{
	return (getdelim(lineptr, n, '\n', iop));
}