[CMAKE]
[reactos.git] / dll / win32 / kernel32 / misc / format_msg.c
1 /*
2 * FormatMessage implementation
3 *
4 * Copyright 1996 Marcus Meissner
5 * Copyright 2009 Alexandre Julliard
6 *
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20 */
21
22 #include <k32.h>
23 #define NDEBUG
24 #include <debug.h>
25 static ULONG gDebugChannel = resource;
26
27 struct format_args
28 {
29 ULONG_PTR *args;
30 __ms_va_list *list;
31 int last;
32 };
33
34 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
35
36 /* Messages used by FormatMessage
37 *
38 * They can be specified either directly or using a message ID and
39 * loading them from the resource.
40 *
41 * The resourcedata has following format:
42 * start:
43 * 0: DWORD nrofentries
44 * nrofentries * subentry:
45 * 0: DWORD firstentry
46 * 4: DWORD lastentry
47 * 8: DWORD offset from start to the stringentries
48 *
49 * (lastentry-firstentry) * stringentry:
50 * 0: WORD len (0 marks end) [ includes the 4 byte header length ]
51 * 2: WORD flags
52 * 4: CHAR[len-4]
53 * (stringentry i of a subentry refers to the ID 'firstentry+i')
54 *
55 * Yes, ANSI strings in win32 resources. Go figure.
56 */
57
58 static const WCHAR PCNTFMTWSTR[] = { '%','%','%','s',0 };
59 static const WCHAR FMTWSTR[] = { '%','s',0 };
60
61 /**********************************************************************
62 * load_message (internal)
63 */
64 static LPWSTR load_message( HMODULE module, UINT id, WORD lang )
65 {
66 PMESSAGE_RESOURCE_ENTRY mre;
67 WCHAR *buffer;
68 NTSTATUS status;
69
70 TRACE("module = %p, id = %08x\n", module, id );
71
72 if (!module) module = GetModuleHandleW( NULL );
73 if ((status = RtlFindMessage( module, (ULONG)RT_MESSAGETABLE, lang, id, &mre )) != STATUS_SUCCESS)
74 {
75 SetLastError( RtlNtStatusToDosError(status) );
76 return NULL;
77 }
78
79 if (mre->Flags & MESSAGE_RESOURCE_UNICODE)
80 {
81 int len = (strlenW( (const WCHAR *)mre->Text ) + 1) * sizeof(WCHAR);
82 if (!(buffer = HeapAlloc( GetProcessHeap(), 0, len ))) return NULL;
83 memcpy( buffer, mre->Text, len );
84 }
85 else
86 {
87 int len = MultiByteToWideChar( CP_ACP, 0, (const char *)mre->Text, -1, NULL, 0 );
88 if (!(buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) ))) return NULL;
89 MultiByteToWideChar( CP_ACP, 0, (const char*)mre->Text, -1, buffer, len );
90 }
91 TRACE("returning %s\n", wine_dbgstr_w(buffer));
92 return buffer;
93 }
94
95 /**********************************************************************
96 * get_arg (internal)
97 */
98 static ULONG_PTR get_arg( int nr, DWORD flags, struct format_args *args )
99 {
100 if (nr == -1) nr = args->last + 1;
101 if (args->list)
102 {
103 if (!args->args) args->args = HeapAlloc( GetProcessHeap(), 0, 99 * sizeof(ULONG_PTR) );
104 while (nr > args->last)
105 args->args[args->last++] = va_arg( *args->list, ULONG_PTR );
106 }
107 if (nr > args->last) args->last = nr;
108 return args->args[nr - 1];
109 }
110
111 /**********************************************************************
112 * format_insert (internal)
113 */
114 static LPCWSTR format_insert( BOOL unicode_caller, int insert, LPCWSTR format,
115 DWORD flags, struct format_args *args,
116 LPWSTR *result )
117 {
118 static const WCHAR fmt_lu[] = {'%','l','u',0};
119 WCHAR *wstring = NULL, *p, fmt[256];
120 ULONG_PTR arg;
121 int size;
122
123 if (*format != '!') /* simple string */
124 {
125 arg = get_arg( insert, flags, args );
126 if (unicode_caller)
127 {
128 WCHAR *str = (WCHAR *)arg;
129 *result = HeapAlloc( GetProcessHeap(), 0, (strlenW(str) + 1) * sizeof(WCHAR) );
130 strcpyW( *result, str );
131 }
132 else
133 {
134 char *str = (char *)arg;
135 DWORD length = MultiByteToWideChar( CP_ACP, 0, str, -1, NULL, 0 );
136 *result = HeapAlloc( GetProcessHeap(), 0, length * sizeof(WCHAR) );
137 MultiByteToWideChar( CP_ACP, 0, str, -1, *result, length );
138 }
139 return format;
140 }
141
142 format++;
143 p = fmt;
144 *p++ = '%';
145
146 while (*format == '0' ||
147 *format == '+' ||
148 *format == '-' ||
149 *format == ' ' ||
150 *format == '*' ||
151 *format == '#')
152 {
153 if (*format == '*')
154 {
155 p += sprintfW( p, fmt_lu, get_arg( insert, flags, args ));
156 insert = -1;
157 format++;
158 }
159 else *p++ = *format++;
160 }
161 while (isdigitW(*format)) *p++ = *format++;
162
163 if (*format == '.')
164 {
165 *p++ = *format++;
166 if (*format == '*')
167 {
168 p += sprintfW( p, fmt_lu, get_arg( insert, flags, args ));
169 insert = -1;
170 format++;
171 }
172 else
173 while (isdigitW(*format)) *p++ = *format++;
174 }
175
176 /* replicate MS bug: drop an argument when using va_list with width/precision */
177 if (insert == -1 && args->list) args->last--;
178 arg = get_arg( insert, flags, args );
179
180 /* check for ascii string format */
181 if ((format[0] == 'h' && format[1] == 's') ||
182 (format[0] == 'h' && format[1] == 'S') ||
183 (unicode_caller && format[0] == 'S') ||
184 (!unicode_caller && format[0] == 's'))
185 {
186 DWORD len = MultiByteToWideChar( CP_ACP, 0, (char *)arg, -1, NULL, 0 );
187 wstring = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
188 MultiByteToWideChar( CP_ACP, 0, (char *)arg, -1, wstring, len );
189 arg = (ULONG_PTR)wstring;
190 *p++ = 's';
191 }
192 /* check for ascii character format */
193 else if ((format[0] == 'h' && format[1] == 'c') ||
194 (format[0] == 'h' && format[1] == 'C') ||
195 (unicode_caller && format[0] == 'C') ||
196 (!unicode_caller && format[0] == 'c'))
197 {
198 char ch = arg;
199 wstring = HeapAlloc( GetProcessHeap(), 0, 2 * sizeof(WCHAR) );
200 MultiByteToWideChar( CP_ACP, 0, &ch, 1, wstring, 1 );
201 wstring[1] = 0;
202 arg = (ULONG_PTR)wstring;
203 *p++ = 's';
204 }
205 /* check for wide string format */
206 else if ((format[0] == 'l' && format[1] == 's') ||
207 (format[0] == 'l' && format[1] == 'S') ||
208 (format[0] == 'w' && format[1] == 's') ||
209 (!unicode_caller && format[0] == 'S'))
210 {
211 *p++ = 's';
212 }
213 /* check for wide character format */
214 else if ((format[0] == 'l' && format[1] == 'c') ||
215 (format[0] == 'l' && format[1] == 'C') ||
216 (format[0] == 'w' && format[1] == 'c') ||
217 (!unicode_caller && format[0] == 'C'))
218 {
219 *p++ = 'c';
220 }
221 /* FIXME: handle I64 etc. */
222 else while (*format && *format != '!') *p++ = *format++;
223
224 *p = 0;
225 size = 256;
226 for (;;)
227 {
228 WCHAR *ret = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) );
229 int needed = snprintfW( ret, size, fmt, arg );
230 if (needed == -1 || needed >= size)
231 {
232 HeapFree( GetProcessHeap(), 0, ret );
233 size = max( needed + 1, size * 2 );
234 }
235 else
236 {
237 *result = ret;
238 break;
239 }
240 }
241
242 while (*format && *format != '!') format++;
243 if (*format == '!') format++;
244
245 HeapFree( GetProcessHeap(), 0, wstring );
246 return format;
247 }
248
249 /**********************************************************************
250 * format_message (internal)
251 */
252 static LPWSTR format_message( BOOL unicode_caller, DWORD dwFlags, LPCWSTR fmtstr,
253 struct format_args *format_args )
254 {
255 LPWSTR target,t;
256 DWORD talloced;
257 LPCWSTR f;
258 DWORD width = dwFlags & FORMAT_MESSAGE_MAX_WIDTH_MASK;
259 BOOL eos = FALSE;
260 WCHAR ch;
261
262 target = t = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, 100 * sizeof(WCHAR) );
263 talloced = 100;
264
265 #define ADD_TO_T(c) do {\
266 *t++=c;\
267 if ((DWORD)(t-target) == talloced) {\
268 target = HeapReAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,target,talloced*2*sizeof(WCHAR));\
269 t = target+talloced;\
270 talloced*=2;\
271 } \
272 } while (0)
273
274 f = fmtstr;
275 while (*f && !eos) {
276 if (*f=='%') {
277 int insertnr;
278 WCHAR *str,*x;
279
280 f++;
281 switch (*f) {
282 case '1':case '2':case '3':case '4':case '5':
283 case '6':case '7':case '8':case '9':
284 if (dwFlags & FORMAT_MESSAGE_IGNORE_INSERTS)
285 goto ignore_inserts;
286 else if (((dwFlags & FORMAT_MESSAGE_ARGUMENT_ARRAY) && !format_args->args) ||
287 (!(dwFlags & FORMAT_MESSAGE_ARGUMENT_ARRAY) && !format_args->list))
288 {
289 SetLastError(ERROR_INVALID_PARAMETER);
290 HeapFree(GetProcessHeap(), 0, target);
291 return NULL;
292 }
293 insertnr = *f-'0';
294 switch (f[1]) {
295 case '0':case '1':case '2':case '3':
296 case '4':case '5':case '6':case '7':
297 case '8':case '9':
298 f++;
299 insertnr = insertnr*10 + *f-'0';
300 f++;
301 break;
302 default:
303 f++;
304 break;
305 }
306 f = format_insert( unicode_caller, insertnr, f, dwFlags, format_args, &str );
307 for (x = str; *x; x++) ADD_TO_T(*x);
308 HeapFree( GetProcessHeap(), 0, str );
309 break;
310 case 'n':
311 ADD_TO_T('\r');
312 ADD_TO_T('\n');
313 f++;
314 break;
315 case 'r':
316 ADD_TO_T('\r');
317 f++;
318 break;
319 case 't':
320 ADD_TO_T('\t');
321 f++;
322 break;
323 case '0':
324 eos = TRUE;
325 f++;
326 break;
327 case '\0':
328 SetLastError(ERROR_INVALID_PARAMETER);
329 HeapFree(GetProcessHeap(), 0, target);
330 return NULL;
331 ignore_inserts:
332 default:
333 if (dwFlags & FORMAT_MESSAGE_IGNORE_INSERTS)
334 ADD_TO_T('%');
335 ADD_TO_T(*f++);
336 break;
337 }
338 } else {
339 ch = *f;
340 f++;
341 if (ch == '\r') {
342 if (*f == '\n')
343 f++;
344 if(width)
345 ADD_TO_T(' ');
346 else
347 {
348 ADD_TO_T('\r');
349 ADD_TO_T('\n');
350 }
351 } else {
352 if (ch == '\n')
353 {
354 if(width)
355 ADD_TO_T(' ');
356 else
357 {
358 ADD_TO_T('\r');
359 ADD_TO_T('\n');
360 }
361 }
362 else
363 ADD_TO_T(ch);
364 }
365 }
366 }
367 *t = '\0';
368
369 return target;
370 }
371 #undef ADD_TO_T
372
373 /***********************************************************************
374 * FormatMessageA (KERNEL32.@)
375 * FIXME: missing wrap,
376 */
377 DWORD WINAPI FormatMessageA(
378 DWORD dwFlags,
379 LPCVOID lpSource,
380 DWORD dwMessageId,
381 DWORD dwLanguageId,
382 LPSTR lpBuffer,
383 DWORD nSize,
384 __ms_va_list* args )
385 {
386 struct format_args format_args;
387 DWORD ret = 0;
388 LPWSTR target;
389 DWORD destlength;
390 LPWSTR from;
391 DWORD width = dwFlags & FORMAT_MESSAGE_MAX_WIDTH_MASK;
392 HMODULE kernel32_handle = GetModuleHandleW(kernel32W);
393
394 TRACE("(0x%x,%p,%d,0x%x,%p,%d,%p)\n",
395 dwFlags,lpSource,dwMessageId,dwLanguageId,lpBuffer,nSize,args);
396
397 if (dwFlags & FORMAT_MESSAGE_ALLOCATE_BUFFER)
398 {
399 if (!lpBuffer)
400 {
401 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
402 return 0;
403 }
404 else
405 *(LPSTR *)lpBuffer = NULL;
406 }
407
408 if (dwFlags & FORMAT_MESSAGE_ARGUMENT_ARRAY)
409 {
410 format_args.args = (ULONG_PTR *)args;
411 format_args.list = NULL;
412 format_args.last = 0;
413 }
414 else
415 {
416 format_args.args = NULL;
417 format_args.list = args;
418 format_args.last = 0;
419 }
420
421 if (width && width != FORMAT_MESSAGE_MAX_WIDTH_MASK)
422 FIXME("line wrapping (%u) not supported.\n", width);
423 from = NULL;
424 if (dwFlags & FORMAT_MESSAGE_FROM_STRING)
425 {
426 DWORD length = MultiByteToWideChar(CP_ACP, 0, lpSource, -1, NULL, 0);
427 from = HeapAlloc( GetProcessHeap(), 0, length * sizeof(WCHAR) );
428 MultiByteToWideChar(CP_ACP, 0, lpSource, -1, from, length);
429 }
430 else if (dwFlags & (FORMAT_MESSAGE_FROM_HMODULE | FORMAT_MESSAGE_FROM_SYSTEM))
431 {
432 if (dwFlags & FORMAT_MESSAGE_FROM_HMODULE)
433 from = load_message( (HMODULE)lpSource, dwMessageId, dwLanguageId );
434 if (!from && (dwFlags & FORMAT_MESSAGE_FROM_SYSTEM))
435 from = load_message( kernel32_handle, dwMessageId, dwLanguageId );
436 if (!from) return 0;
437 }
438 else
439 {
440 SetLastError(ERROR_INVALID_PARAMETER);
441 return 0;
442 }
443
444 target = format_message( FALSE, dwFlags, from, &format_args );
445 if (!target)
446 goto failure;
447
448 TRACE("-- %s\n", debugstr_w(target));
449
450 /* Only try writing to an output buffer if there are processed characters
451 * in the temporary output buffer. */
452 if (*target)
453 {
454 destlength = WideCharToMultiByte(CP_ACP, 0, target, -1, NULL, 0, NULL, NULL);
455 if (dwFlags & FORMAT_MESSAGE_ALLOCATE_BUFFER)
456 {
457 LPSTR buf = LocalAlloc(LMEM_ZEROINIT, max(nSize, destlength));
458 WideCharToMultiByte(CP_ACP, 0, target, -1, buf, destlength, NULL, NULL);
459 *((LPSTR*)lpBuffer) = buf;
460 }
461 else
462 {
463 if (nSize < destlength)
464 {
465 SetLastError(ERROR_INSUFFICIENT_BUFFER);
466 goto failure;
467 }
468 WideCharToMultiByte(CP_ACP, 0, target, -1, lpBuffer, destlength, NULL, NULL);
469 }
470 ret = destlength - 1; /* null terminator */
471 }
472
473 failure:
474 HeapFree(GetProcessHeap(),0,target);
475 HeapFree(GetProcessHeap(),0,from);
476 if (!(dwFlags & FORMAT_MESSAGE_ARGUMENT_ARRAY)) HeapFree( GetProcessHeap(), 0, format_args.args );
477 TRACE("-- returning %u\n", ret);
478 return ret;
479 }
480
481 /***********************************************************************
482 * FormatMessageW (KERNEL32.@)
483 */
484 DWORD WINAPI FormatMessageW(
485 DWORD dwFlags,
486 LPCVOID lpSource,
487 DWORD dwMessageId,
488 DWORD dwLanguageId,
489 LPWSTR lpBuffer,
490 DWORD nSize,
491 __ms_va_list* args )
492 {
493 struct format_args format_args;
494 DWORD ret = 0;
495 LPWSTR target;
496 DWORD talloced;
497 LPWSTR from;
498 DWORD width = dwFlags & FORMAT_MESSAGE_MAX_WIDTH_MASK;
499 HMODULE kernel32_handle = GetModuleHandleW(kernel32W);
500
501 TRACE("(0x%x,%p,%d,0x%x,%p,%d,%p)\n",
502 dwFlags,lpSource,dwMessageId,dwLanguageId,lpBuffer,nSize,args);
503
504 if (!lpBuffer)
505 {
506 SetLastError(ERROR_INVALID_PARAMETER);
507 return 0;
508 }
509
510 if (dwFlags & FORMAT_MESSAGE_ALLOCATE_BUFFER)
511 *(LPWSTR *)lpBuffer = NULL;
512
513 if (dwFlags & FORMAT_MESSAGE_ARGUMENT_ARRAY)
514 {
515 format_args.args = (ULONG_PTR *)args;
516 format_args.list = NULL;
517 format_args.last = 0;
518 }
519 else
520 {
521 format_args.args = NULL;
522 format_args.list = args;
523 format_args.last = 0;
524 }
525
526 if (width && width != FORMAT_MESSAGE_MAX_WIDTH_MASK)
527 FIXME("line wrapping not supported.\n");
528 from = NULL;
529 if (dwFlags & FORMAT_MESSAGE_FROM_STRING) {
530 from = HeapAlloc( GetProcessHeap(), 0, (strlenW(lpSource) + 1) *
531 sizeof(WCHAR) );
532 strcpyW( from, lpSource );
533 }
534 else if (dwFlags & (FORMAT_MESSAGE_FROM_HMODULE | FORMAT_MESSAGE_FROM_SYSTEM))
535 {
536 if (dwFlags & FORMAT_MESSAGE_FROM_HMODULE)
537 from = load_message( (HMODULE)lpSource, dwMessageId, dwLanguageId );
538 if (!from && (dwFlags & FORMAT_MESSAGE_FROM_SYSTEM))
539 from = load_message( kernel32_handle, dwMessageId, dwLanguageId );
540 if (!from) return 0;
541 }
542 else
543 {
544 SetLastError(ERROR_INVALID_PARAMETER);
545 return 0;
546 }
547
548 target = format_message( TRUE, dwFlags, from, &format_args );
549 if (!target)
550 goto failure;
551
552 talloced = strlenW(target)+1;
553 TRACE("-- %s\n",debugstr_w(target));
554
555 /* Only allocate a buffer if there are processed characters in the
556 * temporary output buffer. If a caller supplies the buffer, then
557 * a null terminator will be written to it. */
558 if (dwFlags & FORMAT_MESSAGE_ALLOCATE_BUFFER)
559 {
560 if (*target)
561 {
562 /* nSize is the MINIMUM size */
563 *((LPVOID*)lpBuffer) = LocalAlloc(LMEM_ZEROINIT, max(nSize, talloced)*sizeof(WCHAR));
564 strcpyW(*(LPWSTR*)lpBuffer, target);
565 }
566 }
567 else
568 {
569 if (nSize < talloced)
570 {
571 SetLastError(ERROR_INSUFFICIENT_BUFFER);
572 goto failure;
573 }
574 strcpyW(lpBuffer, target);
575 }
576
577 ret = talloced - 1; /* null terminator */
578 failure:
579 HeapFree(GetProcessHeap(),0,target);
580 HeapFree(GetProcessHeap(),0,from);
581 if (!(dwFlags & FORMAT_MESSAGE_ARGUMENT_ARRAY)) HeapFree( GetProcessHeap(), 0, format_args.args );
582 TRACE("-- returning %u\n", ret);
583 return ret;
584 }