xref: /openbmc/u-boot/tools/mingw_support.c (revision 7c1058fa)
1 /*
2  * Copyright 2008 Extreme Engineering Solutions, Inc.
3  *
4  * mmap/munmap implementation derived from:
5  * Clamav Native Windows Port : mmap win32 compatibility layer
6  * Copyright (c) 2005-2006 Gianluigi Tiesi <sherpya@netfarm.it>
7  * Parts by Kees Zeelenberg <kzlg@users.sourceforge.net> (LibGW32C)
8  *
9  * SPDX-License-Identifier:	LGPL-2.0+
10  */
11 
12 #include "mingw_support.h"
13 #include <stdio.h>
14 #include <stdint.h>
15 #include <string.h>
16 #include <errno.h>
17 #include <assert.h>
18 #include <io.h>
19 
20 int fsync(int fd)
21 {
22 	return _commit(fd);
23 }
24 
25 void *mmap(void *addr, size_t len, int prot, int flags, int fd, int offset)
26 {
27 	void *map = NULL;
28 	HANDLE handle = INVALID_HANDLE_VALUE;
29 	DWORD cfm_flags = 0, mvf_flags = 0;
30 
31 	switch (prot) {
32 	case PROT_READ | PROT_WRITE:
33 		cfm_flags = PAGE_READWRITE;
34 		mvf_flags = FILE_MAP_ALL_ACCESS;
35 		break;
36 	case PROT_WRITE:
37 		cfm_flags = PAGE_READWRITE;
38 		mvf_flags = FILE_MAP_WRITE;
39 		break;
40 	case PROT_READ:
41 		cfm_flags = PAGE_READONLY;
42 		mvf_flags = FILE_MAP_READ;
43 		break;
44 	default:
45 		return MAP_FAILED;
46 	}
47 
48 	handle = CreateFileMappingA((HANDLE) _get_osfhandle(fd), NULL,
49 				cfm_flags, HIDWORD(len), LODWORD(len), NULL);
50 	if (!handle)
51 		return MAP_FAILED;
52 
53 	map = MapViewOfFile(handle, mvf_flags, HIDWORD(offset),
54 			LODWORD(offset), len);
55 	CloseHandle(handle);
56 
57 	if (!map)
58 		return MAP_FAILED;
59 
60 	return map;
61 }
62 
63 int munmap(void *addr, size_t len)
64 {
65 	if (!UnmapViewOfFile(addr))
66 		return -1;
67 
68 	return 0;
69 }
70 
71 /* Reentrant string tokenizer.  Generic version.
72    Copyright (C) 1991,1996-1999,2001,2004,2007 Free Software Foundation, Inc.
73    This file is part of the GNU C Library.
74 
75   * SPDX-License-Identifier:	GPL-2.0+
76  */
77 
78 /* Parse S into tokens separated by characters in DELIM.
79    If S is NULL, the saved pointer in SAVE_PTR is used as
80    the next starting point.  For example:
81 	char s[] = "-abc-=-def";
82 	char *sp;
83 	x = strtok_r(s, "-", &sp);	// x = "abc", sp = "=-def"
84 	x = strtok_r(NULL, "-=", &sp);	// x = "def", sp = NULL
85 	x = strtok_r(NULL, "=", &sp);	// x = NULL
86 		// s = "abc\0-def\0"
87 */
88 char *strtok_r(char *s, const char *delim, char **save_ptr)
89 {
90 	char *token;
91 
92 	if (s == NULL)
93 		s = *save_ptr;
94 
95 	/* Scan leading delimiters.  */
96 	s += strspn(s, delim);
97 	if (*s == '\0') {
98 		*save_ptr = s;
99 		return NULL;
100 	}
101 
102 	/* Find the end of the token.  */
103 	token = s;
104 	s = strpbrk (token, delim);
105 	if (s == NULL) {
106 		/* This token finishes the string.  */
107 		*save_ptr = memchr(token, '\0', strlen(token));
108 	} else {
109 		/* Terminate the token and make *SAVE_PTR point past it.  */
110 		*s = '\0';
111 		*save_ptr = s + 1;
112 	}
113 	return token;
114 }
115 
116 #include "getline.c"
117