1 /*
2 * CDDL HEADER START
3 *
4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
7 *
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
12 *
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
18 *
19 * CDDL HEADER END
20 */
21
22 /*
23 * Copyright 2008 Sun Microsystems, Inc. All rights reserved.
24 * Use is subject to license terms.
25 */
26
27 /* Copyright (c) 1988 AT&T */
28 /* All Rights Reserved */
29
30 /*
31 * Return file offset.
32 * Coordinates with buffering.
33 */
34 #pragma weak _ftell = ftell
35
36 #include "lint.h"
37 #include "file64.h"
38 #include "mtlib.h"
39 #include <fcntl.h>
40 #include <stdio.h>
41 #include <thread.h>
42 #include <synch.h>
43 #include <errno.h>
44 #include <unistd.h>
45 #include <stddef.h>
46 #include <limits.h>
47 #include <sys/types.h>
48 #include "stdiom.h"
49
50 off64_t
ftell_common(FILE * iop)51 ftell_common(FILE *iop)
52 {
53 ptrdiff_t adjust;
54 off64_t tres;
55 rmutex_t *lk;
56
57 FLOCKFILE(lk, iop);
58
59 /*
60 * If we're dealing with a memory stream, we need to flush the internal
61 * state before we try and determine the location. This is especially
62 * important for open_wmemstream() as it will have buffered bytes, but
63 * we need to convert that to wide characters before we proceed. If we
64 * have no file descriptor, then the units that the backing store are in
65 * can be arbitrary.
66 */
67 if (_get_fd(iop) == -1) {
68 (void) _fflush_u(iop);
69 }
70
71 if (iop->_cnt < 0)
72 iop->_cnt = 0;
73 if (iop->_flag & _IOREAD) {
74 adjust = (ptrdiff_t)-iop->_cnt;
75 } else if (iop->_flag & (_IOWRT | _IORW)) {
76 adjust = 0;
77 if (((iop->_flag & (_IOWRT | _IONBF)) == _IOWRT) &&
78 (iop->_base != 0)) {
79 adjust = iop->_ptr - iop->_base;
80 } else if ((iop->_flag & _IORW) && (iop->_base != 0)) {
81 adjust = (ptrdiff_t)-iop->_cnt;
82 }
83 } else {
84 errno = EBADF; /* file descriptor refers to no open file */
85 FUNLOCKFILE(lk);
86 return (EOF);
87 }
88
89 tres = _xseek64(iop, 0, SEEK_CUR);
90 if (tres >= 0)
91 tres += adjust;
92
93 FUNLOCKFILE(lk);
94 return (tres);
95 }
96
97 long
ftell(FILE * iop)98 ftell(FILE *iop)
99 {
100 off64_t tres;
101
102 tres = ftell_common(iop);
103 if (tres > LONG_MAX) {
104 errno = EOVERFLOW;
105 return (EOF);
106 }
107
108 return ((long)tres);
109 }
110