xref: /aosp_15_r20/external/flac/src/share/win_utf8_io/win_utf8_io.c (revision 600f14f40d737144c998e2ec7a483122d3776fbc)
1 /* libFLAC - Free Lossless Audio Codec library
2  * Copyright (C) 2013-2023  Xiph.Org Foundation
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * - Redistributions of source code must retain the above copyright
9  * notice, this list of conditions and the following disclaimer.
10  *
11  * - Redistributions in binary form must reproduce the above copyright
12  * notice, this list of conditions and the following disclaimer in the
13  * documentation and/or other materials provided with the distribution.
14  *
15  * - Neither the name of the Xiph.org Foundation nor the names of its
16  * contributors may be used to endorse or promote products derived from
17  * this software without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22  * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  */
31 
32 #ifdef HAVE_CONFIG_H
33 #  include <config.h>
34 #endif
35 
36 #include <io.h>
37 #include <windows.h>
38 #include "share/win_utf8_io.h"
39 
40 #define UTF8_BUFFER_SIZE 32768
41 
42 /* detect whether it is Windows APP (UWP) or standard Win32 envionment */
43 #ifdef WINAPI_FAMILY_PARTITION
44 	#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) && !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
45 		#define FLAC_WINDOWS_APP 1
46 	#else
47 		#define FLAC_WINDOWS_APP 0
48 	#endif
49 #else
50 	#define FLAC_WINDOWS_APP 0
51 #endif
52 
local_vsnprintf(char * str,size_t size,const char * fmt,va_list va)53 static int local_vsnprintf(char *str, size_t size, const char *fmt, va_list va)
54 {
55 	int rc;
56 
57 #if defined _MSC_VER
58 	if (size == 0)
59 		return 1024;
60 	rc = vsnprintf_s(str, size, _TRUNCATE, fmt, va);
61 	if (rc < 0)
62 		rc = size - 1;
63 #elif defined __MINGW32__
64 	rc = __mingw_vsnprintf(str, size, fmt, va);
65 #else
66 	rc = vsnprintf(str, size, fmt, va);
67 #endif
68 
69 	return rc;
70 }
71 
72 /* convert WCHAR stored Unicode string to UTF-8. Caller is responsible for freeing memory */
utf8_from_wchar(const wchar_t * wstr)73 static char *utf8_from_wchar(const wchar_t *wstr)
74 {
75 	char *utf8str;
76 	int len;
77 
78 	if (!wstr)
79 		return NULL;
80 	if ((len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL)) == 0)
81 		return NULL;
82 	if ((utf8str = (char *)malloc(len)) == NULL)
83 		return NULL;
84 	if (WideCharToMultiByte(CP_UTF8, 0, wstr, -1, utf8str, len, NULL, NULL) == 0) {
85 		free(utf8str);
86 		utf8str = NULL;
87 	}
88 
89 	return utf8str;
90 }
91 
92 /* convert UTF-8 back to WCHAR. Caller is responsible for freeing memory */
wchar_from_utf8(const char * str)93 static wchar_t *wchar_from_utf8(const char *str)
94 {
95 	wchar_t *widestr;
96 	int len;
97 
98 	if (!str)
99 		return NULL;
100 	if ((len = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0)) == 0)
101 		return NULL;
102 	if ((widestr = (wchar_t *)malloc(len*sizeof(wchar_t))) == NULL)
103 		return NULL;
104 	if (MultiByteToWideChar(CP_UTF8, 0, str, -1, widestr, len) == 0) {
105 		free(widestr);
106 		widestr = NULL;
107 	}
108 
109 	return widestr;
110 }
111 
112 /* retrieve WCHAR commandline, expand wildcards and convert everything to UTF-8 */
get_utf8_argv(int * argc,char *** argv)113 int get_utf8_argv(int *argc, char ***argv)
114 {
115 #if !FLAC_WINDOWS_APP
116 	typedef int (__cdecl *wgetmainargs_t)(int*, wchar_t***, wchar_t***, int, int*);
117 	wgetmainargs_t wgetmainargs;
118 	HMODULE handle;
119 #endif // !FLAC_WINDOWS_APP
120 	int wargc;
121 	wchar_t **wargv;
122 	wchar_t **wenv;
123 	char **utf8argv;
124 	int ret, i;
125 
126 #if FLAC_WINDOWS_APP
127 	wargc = __argc;
128 	wargv = __wargv;
129 	wenv = _wenviron;
130 #else // !FLAC_WINDOWS_APP
131 	if ((handle = LoadLibraryW(L"msvcrt.dll")) == NULL) return 1;
132 	if ((wgetmainargs = (wgetmainargs_t)GetProcAddress(handle, "__wgetmainargs")) == NULL) {
133 		FreeLibrary(handle);
134 		return 1;
135 	}
136 	i = 0;
137 	/* when the 4th argument is 1,  __wgetmainargs expands wildcards but also erroneously converts \\?\c:\path\to\file.flac to \\file.flac */
138 	if (wgetmainargs(&wargc, &wargv, &wenv, 1, &i) != 0) {
139 		FreeLibrary(handle);
140 		return 1;
141 	}
142 #endif // !FLAC_WINDOWS_APP
143 	if ((utf8argv = (char **)calloc(wargc, sizeof(char*))) == NULL) {
144 	#if !FLAC_WINDOWS_APP
145 		FreeLibrary(handle);
146 	#endif // !FLAC_WINDOWS_APP
147 		return 1;
148 	}
149 
150 	ret = 0;
151 	for (i=0; i<wargc; i++) {
152 		if ((utf8argv[i] = utf8_from_wchar(wargv[i])) == NULL) {
153 			ret = 1;
154 			break;
155 		}
156 	}
157 
158 #if !FLAC_WINDOWS_APP
159 	FreeLibrary(handle); /* do not free it when wargv or wenv are still in use */
160 #endif // !FLAC_WINDOWS_APP
161 
162 	if (ret == 0) {
163 		*argc = wargc;
164 		*argv = utf8argv;
165 	} else {
166 		for (i=0; i<wargc; i++)
167 			free(utf8argv[i]);
168 		free(utf8argv);
169 	}
170 
171 	return ret;
172 }
173 
174 /* similar to CreateFileW but accepts UTF-8 encoded lpFileName */
CreateFile_utf8(const char * lpFileName,DWORD dwDesiredAccess,DWORD dwShareMode,LPSECURITY_ATTRIBUTES lpSecurityAttributes,DWORD dwCreationDisposition,DWORD dwFlagsAndAttributes,HANDLE hTemplateFile)175 HANDLE WINAPI CreateFile_utf8(const char *lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile)
176 {
177 	wchar_t *wname;
178 	HANDLE handle = INVALID_HANDLE_VALUE;
179 
180 	if ((wname = wchar_from_utf8(lpFileName)) != NULL) {
181 #if !FLAC_WINDOWS_APP
182 		handle = CreateFileW(wname, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile);
183 #else // FLAC_WINDOWS_APP
184 		CREATEFILE2_EXTENDED_PARAMETERS params;
185 		params.dwSize = sizeof(params);
186 		params.dwFileAttributes = dwFlagsAndAttributes & 0xFFFF;
187 		params.dwFileFlags = dwFlagsAndAttributes & 0xFFF00000;
188 		params.dwSecurityQosFlags = dwFlagsAndAttributes & 0x000F0000;
189 		params.lpSecurityAttributes = lpSecurityAttributes;
190 		params.hTemplateFile = hTemplateFile;
191 		handle = CreateFile2(wname, dwDesiredAccess, dwShareMode, dwCreationDisposition, &params);
192 #endif // FLAC_WINDOWS_APP
193 		free(wname);
194 	}
195 
196 	return handle;
197 }
198 
199 /* return number of characters in the UTF-8 string */
strlen_utf8(const char * str)200 size_t strlen_utf8(const char *str)
201 {
202 	size_t len;
203 	len = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0); /* includes terminating null */
204 	if (len != 0)
205 		return len-1;
206 	else
207 		return strlen(str);
208 }
209 
210 /* get the console width in characters */
win_get_console_width(void)211 int win_get_console_width(void)
212 {
213 	int width = 80;
214 #if !FLAC_WINDOWS_APP
215 	CONSOLE_SCREEN_BUFFER_INFO csbi;
216 	HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
217 	if(hOut != INVALID_HANDLE_VALUE && hOut != NULL)
218 		if (GetConsoleScreenBufferInfo(hOut, &csbi) != 0)
219 			width = csbi.dwSize.X;
220 #endif // !FLAC_WINDOWS_APP
221 	return width;
222 }
223 
224 /* print functions */
225 
226 #if !FLAC_WINDOWS_APP
wprint_console(FILE * stream,const wchar_t * text,size_t len)227 static int wprint_console(FILE *stream, const wchar_t *text, size_t len)
228 {
229 	DWORD out;
230 	int ret;
231 
232 	do {
233 		if (stream == stdout) {
234 			HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
235 			if (hOut == INVALID_HANDLE_VALUE || hOut == NULL || GetFileType(hOut) != FILE_TYPE_CHAR)
236 				break;
237 			if (WriteConsoleW(hOut, text, len, &out, NULL) == 0)
238 				return -1;
239 			return out;
240 		}
241 		if (stream == stderr) {
242 			HANDLE hErr = GetStdHandle(STD_ERROR_HANDLE);
243 			if (hErr == INVALID_HANDLE_VALUE || hErr == NULL || GetFileType(hErr) != FILE_TYPE_CHAR)
244 				break;
245 			if (WriteConsoleW(hErr, text, len, &out, NULL) == 0)
246 				return -1;
247 			return out;
248 		}
249 	} while(0);
250 
251 	ret = fputws(text, stream);
252 	if (ret < 0)
253 		return ret;
254 	return len;
255 }
256 #endif // !FLAC_WINDOWS_APP
257 
printf_utf8(const char * format,...)258 int printf_utf8(const char *format, ...)
259 {
260 	int ret;
261 	va_list argptr;
262 	va_start(argptr, format);
263 
264 	ret = vfprintf_utf8(stdout, format, argptr);
265 
266 	va_end(argptr);
267 
268 	return ret;
269 }
270 
fprintf_utf8(FILE * stream,const char * format,...)271 int fprintf_utf8(FILE *stream, const char *format, ...)
272 {
273 	int ret;
274 	va_list argptr;
275 	va_start(argptr, format);
276 
277 	ret = vfprintf_utf8(stream, format, argptr);
278 
279 	va_end(argptr);
280 
281 	return ret;
282 }
283 
vfprintf_utf8(FILE * stream,const char * format,va_list argptr)284 int vfprintf_utf8(FILE *stream, const char *format, va_list argptr)
285 {
286 	char *utmp = NULL;
287 	wchar_t *wout = NULL;
288 	int ret = -1;
289 
290 	do {
291 		if (!(utmp = (char *)malloc(UTF8_BUFFER_SIZE))) break;
292 		if ((ret = local_vsnprintf(utmp, UTF8_BUFFER_SIZE, format, argptr)) <= 0) break;
293 		if (!(wout = wchar_from_utf8(utmp))) {
294 			ret = -1;
295 			break;
296 		}
297 #if !FLAC_WINDOWS_APP
298 		ret = wprint_console(stream, wout, wcslen(wout));
299 #else // FLAC_WINDOWS_APP
300 		OutputDebugStringW(wout);
301 		ret = 0;
302 #endif // FLAC_WINDOWS_APP
303 	} while(0);
304 
305 	free(utmp);
306 	free(wout);
307 
308 	return ret;
309 }
310 
311 /* file functions */
312 
fopen_utf8(const char * filename,const char * mode)313 FILE* fopen_utf8(const char *filename, const char *mode)
314 {
315 	wchar_t *wname = NULL;
316 	wchar_t *wmode = NULL;
317 	FILE *f = NULL;
318 
319 	do {
320 		if (!(wname = wchar_from_utf8(filename))) break;
321 		if (!(wmode = wchar_from_utf8(mode))) break;
322 		f = _wfopen(wname, wmode);
323 	} while(0);
324 
325 	free(wname);
326 	free(wmode);
327 
328 	return f;
329 }
330 
stat64_utf8(const char * path,struct __stat64 * buffer)331 int stat64_utf8(const char *path, struct __stat64 *buffer)
332 {
333 	wchar_t *wpath;
334 	int ret;
335 
336 	if (!(wpath = wchar_from_utf8(path))) return -1;
337 	ret = _wstat64(wpath, buffer);
338 	free(wpath);
339 
340 	return ret;
341 }
342 
chmod_utf8(const char * filename,int pmode)343 int chmod_utf8(const char *filename, int pmode)
344 {
345 	wchar_t *wname;
346 	int ret;
347 
348 	if (!(wname = wchar_from_utf8(filename))) return -1;
349 	ret = _wchmod(wname, pmode);
350 	free(wname);
351 
352 	return ret;
353 }
354 
utime_utf8(const char * filename,struct utimbuf * times)355 int utime_utf8(const char *filename, struct utimbuf *times)
356 {
357 	wchar_t *wname;
358 	struct __utimbuf64 ut;
359 	int ret;
360 
361 	if (!(wname = wchar_from_utf8(filename))) return -1;
362 	ut.actime = times->actime;
363 	ut.modtime = times->modtime;
364 	ret = _wutime64(wname, &ut);
365 	free(wname);
366 
367 	return ret;
368 }
369 
unlink_utf8(const char * filename)370 int unlink_utf8(const char *filename)
371 {
372 	wchar_t *wname;
373 	int ret;
374 
375 	if (!(wname = wchar_from_utf8(filename))) return -1;
376 	ret = _wunlink(wname);
377 	free(wname);
378 
379 	return ret;
380 }
381 
rename_utf8(const char * oldname,const char * newname)382 int rename_utf8(const char *oldname, const char *newname)
383 {
384 	wchar_t *wold = NULL;
385 	wchar_t *wnew = NULL;
386 	int ret = -1;
387 
388 	do {
389 		if (!(wold = wchar_from_utf8(oldname))) break;
390 		if (!(wnew = wchar_from_utf8(newname))) break;
391 		ret = _wrename(wold, wnew);
392 	} while(0);
393 
394 	free(wold);
395 	free(wnew);
396 
397 	return ret;
398 }
399