1570af302Sopenharmony_ci#include "stdio_impl.h"
2570af302Sopenharmony_ci#include <stdlib.h>
3570af302Sopenharmony_ci#ifndef __LITEOS__
4570af302Sopenharmony_ci#include <errno.h>
5570af302Sopenharmony_ci#endif
6570af302Sopenharmony_ci
7570af302Sopenharmony_cistatic void dummy(FILE *f) { }
8570af302Sopenharmony_ciweak_alias(dummy, __unlist_locked_file);
9570af302Sopenharmony_ci
10570af302Sopenharmony_ciint fclose(FILE *f)
11570af302Sopenharmony_ci{
12570af302Sopenharmony_ci	int r;
13570af302Sopenharmony_ci
14570af302Sopenharmony_ci	FLOCK(f);
15570af302Sopenharmony_ci#ifndef __LITEOS__
16570af302Sopenharmony_ci	if (!f || f->fd < 0) {
17570af302Sopenharmony_ci		errno = EBADF;
18570af302Sopenharmony_ci		FUNLOCK(f);
19570af302Sopenharmony_ci		return -EBADF;
20570af302Sopenharmony_ci	}
21570af302Sopenharmony_ci#endif
22570af302Sopenharmony_ci
23570af302Sopenharmony_ci	r = fflush(f);
24570af302Sopenharmony_ci	r |= f->close(f);
25570af302Sopenharmony_ci	FUNLOCK(f);
26570af302Sopenharmony_ci
27570af302Sopenharmony_ci	/* Past this point, f is closed and any further explict access
28570af302Sopenharmony_ci	 * to it is undefined. However, it still exists as an entry in
29570af302Sopenharmony_ci	 * the open file list and possibly in the thread's locked files
30570af302Sopenharmony_ci	 * list, if it was closed while explicitly locked. Functions
31570af302Sopenharmony_ci	 * which process these lists must tolerate dead FILE objects
32570af302Sopenharmony_ci	 * (which necessarily have inactive buffer pointers) without
33570af302Sopenharmony_ci	 * producing any side effects. */
34570af302Sopenharmony_ci
35570af302Sopenharmony_ci	if (f->flags & F_PERM) return r;
36570af302Sopenharmony_ci
37570af302Sopenharmony_ci	__unlist_locked_file(f);
38570af302Sopenharmony_ci
39570af302Sopenharmony_ci	free(f->getln_buf);
40570af302Sopenharmony_ci	/* release base instead of buf which may be modified by setvbuf
41570af302Sopenharmony_ci	 * or iniitalize by local variable */
42570af302Sopenharmony_ci	free(f->base);
43570af302Sopenharmony_ci
44570af302Sopenharmony_ci#ifndef __LITEOS__
45570af302Sopenharmony_ci	/* set file to invalid descriptor */
46570af302Sopenharmony_ci	f->fd = -EBADF;
47570af302Sopenharmony_ci#endif
48570af302Sopenharmony_ci
49570af302Sopenharmony_ci	__ofl_free(f);
50570af302Sopenharmony_ci
51570af302Sopenharmony_ci	return r;
52570af302Sopenharmony_ci}
53