[KERNEL32]
[reactos.git] / reactos / dll / win32 / kernel32 / winnls / string / 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
24 #define NDEBUG
25 #include <debug.h>
26 DEBUG_CHANNEL(resource);
27
28 extern HMODULE kernel32_handle;
29
30 struct format_args
31 {
32 ULONG_PTR *args;
33 __ms_va_list *list;
34 int last;
35 };
36
37 /* Messages used by FormatMessage
38 *
39 * They can be specified either directly or using a message ID and
40 * loading them from the resource.
41 *
42 * The resourcedata has following format:
43 * start:
44 * 0: DWORD nrofentries
45 * nrofentries * subentry:
46 * 0: DWORD firstentry
47 * 4: DWORD lastentry
48 * 8: DWORD offset from start to the stringentries
49 *
50 * (lastentry-firstentry) * stringentry:
51 * 0: WORD len (0 marks end) [ includes the 4 byte header length ]
52 * 2: WORD flags
53 * 4: CHAR[len-4]
54 * (stringentry i of a subentry refers to the ID 'firstentry+i')
55 *
56 * Yes, ANSI strings in win32 resources. Go figure.
57 */
58
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 MESSAGE_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_u[] = {'%','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 || !arg)
127 {
128 static const WCHAR nullW[] = {'(','n','u','l','l',')',0};
129 const WCHAR *str = (const WCHAR *)arg;
130
131 if (!str) str = nullW;
132 *result = HeapAlloc( GetProcessHeap(), 0, (strlenW(str) + 1) * sizeof(WCHAR) );
133 strcpyW( *result, str );
134 }
135 else
136 {
137 const char *str = (const char *)arg;
138 DWORD length = MultiByteToWideChar( CP_ACP, 0, str, -1, NULL, 0 );
139 *result = HeapAlloc( GetProcessHeap(), 0, length * sizeof(WCHAR) );
140 MultiByteToWideChar( CP_ACP, 0, str, -1, *result, length );
141 }
142 return format;
143 }
144
145 format++;
146 p = fmt;
147 *p++ = '%';
148
149 while (*format == '0' ||
150 *format == '+' ||
151 *format == '-' ||
152 *format == ' ' ||
153 *format == '*' ||
154 *format == '#')
155 {
156 if (*format == '*')
157 {
158 p += sprintfW( p, fmt_u, get_arg( insert, flags, args ));
159 insert = -1;
160 format++;
161 }
162 else *p++ = *format++;
163 }
164 while (isdigitW(*format)) *p++ = *format++;
165
166 if (*format == '.')
167 {
168 *p++ = *format++;
169 if (*format == '*')
170 {
171 p += sprintfW( p, fmt_u, get_arg( insert, flags, args ));
172 insert = -1;
173 format++;
174 }
175 else
176 while (isdigitW(*format)) *p++ = *format++;
177 }
178
179 /* replicate MS bug: drop an argument when using va_list with width/precision */
180 if (insert == -1 && args->list) args->last--;
181 arg = get_arg( insert, flags, args );
182
183 /* check for ascii string format */
184 if ((format[0] == 'h' && format[1] == 's') ||
185 (format[0] == 'h' && format[1] == 'S') ||
186 (unicode_caller && format[0] == 'S') ||
187 (!unicode_caller && format[0] == 's'))
188 {
189 DWORD len = MultiByteToWideChar( CP_ACP, 0, (char *)arg, -1, NULL, 0 );
190 wstring = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
191 MultiByteToWideChar( CP_ACP, 0, (char *)arg, -1, wstring, len );
192 arg = (ULONG_PTR)wstring;
193 *p++ = 's';
194 }
195 /* check for ascii character format */
196 else if ((format[0] == 'h' && format[1] == 'c') ||
197 (format[0] == 'h' && format[1] == 'C') ||
198 (unicode_caller && format[0] == 'C') ||
199 (!unicode_caller && format[0] == 'c'))
200 {
201 char ch = arg;
202 wstring = HeapAlloc( GetProcessHeap(), 0, 2 * sizeof(WCHAR) );
203 MultiByteToWideChar( CP_ACP, 0, &ch, 1, wstring, 1 );
204 wstring[1] = 0;
205 arg = (ULONG_PTR)wstring;
206 *p++ = 's';
207 }
208 /* check for wide string format */
209 else if ((format[0] == 'l' && format[1] == 's') ||
210 (format[0] == 'l' && format[1] == 'S') ||
211 (format[0] == 'w' && format[1] == 's') ||
212 (!unicode_caller && format[0] == 'S'))
213 {
214 *p++ = 's';
215 }
216 /* check for wide character format */
217 else if ((format[0] == 'l' && format[1] == 'c') ||
218 (format[0] == 'l' && format[1] == 'C') ||
219 (format[0] == 'w' && format[1] == 'c') ||
220 (!unicode_caller && format[0] == 'C'))
221 {
222 *p++ = 'c';
223 }
224 /* FIXME: handle I64 etc. */
225 else while (*format && *format != '!') *p++ = *format++;
226
227 *p = 0;
228 size = 256;
229 for (;;)
230 {
231 WCHAR *ret = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) );
232 int needed = snprintfW( ret, size, fmt, arg );
233 if (needed == -1 || needed >= size)
234 {
235 HeapFree( GetProcessHeap(), 0, ret );
236 size = max( needed + 1, size * 2 );
237 }
238 else
239 {
240 *result = ret;
241 break;
242 }
243 }
244
245 while (*format && *format != '!') format++;
246 if (*format == '!') format++;
247
248 HeapFree( GetProcessHeap(), 0, wstring );
249 return format;
250 }
251
252 struct _format_message_data
253 {
254 LPWSTR formatted;
255 DWORD size;
256 LPWSTR t;
257 LPWSTR space;
258 BOOL inspace;
259 DWORD width, w;
260 };
261
262 static void format_add_char(struct _format_message_data *fmd, WCHAR c)
263 {
264 *fmd->t++ = c;
265 if (fmd->width && fmd->width != FORMAT_MESSAGE_MAX_WIDTH_MASK)
266 {
267 switch (c) {
268 case '\r':
269 case '\n':
270 fmd->space = NULL;
271 fmd->inspace = FALSE;
272 fmd->w = 0;
273 break;
274 case ' ':
275 if (!fmd->inspace)
276 fmd->space = fmd->t - 1;
277 fmd->inspace = TRUE;
278 fmd->w++;
279 break;
280 default:
281 fmd->inspace = FALSE;
282 fmd->w++;
283 }
284 if (fmd->w == fmd->width) {
285 LPWSTR notspace;
286 if (fmd->space) {
287 notspace = fmd->space;
288 while (notspace != fmd->t && *notspace == ' ')
289 notspace++;
290 } else
291 notspace = fmd->space = fmd->t;
292 fmd->w = fmd->t - notspace;
293 memmove(fmd->space+2, notspace, fmd->w * sizeof(*fmd->t));
294 *fmd->space++ = '\r';
295 *fmd->space++ = '\n';
296 fmd->t = fmd->space + fmd->w;
297 fmd->space = NULL;
298 fmd->inspace = FALSE;
299 }
300 }
301 if ((DWORD)(fmd->t - fmd->formatted) == fmd->size) {
302 DWORD_PTR ispace = fmd->space - fmd->formatted;
303 /* Allocate two extra characters so we can insert a '\r\n' in
304 * the middle of a word.
305 */
306 fmd->formatted = HeapReAlloc(GetProcessHeap(), 0, fmd->formatted, (fmd->size * 2 + 2) * sizeof(WCHAR));
307 fmd->t = fmd->formatted + fmd->size;
308 if (fmd->space)
309 fmd->space = fmd->formatted + ispace;
310 fmd->size *= 2;
311 }
312 }
313
314 /**********************************************************************
315 * format_message (internal)
316 */
317 static LPWSTR format_message( BOOL unicode_caller, DWORD dwFlags, LPCWSTR fmtstr,
318 struct format_args *format_args )
319 {
320 struct _format_message_data fmd;
321 LPCWSTR f;
322 BOOL eos = FALSE;
323
324 fmd.size = 100;
325 fmd.formatted = fmd.t = HeapAlloc( GetProcessHeap(), 0, (fmd.size + 2) * sizeof(WCHAR) );
326
327 fmd.width = dwFlags & FORMAT_MESSAGE_MAX_WIDTH_MASK;
328 fmd.w = 0;
329 fmd.inspace = FALSE;
330 fmd.space = NULL;
331 f = fmtstr;
332 while (*f && !eos) {
333 if (*f=='%') {
334 int insertnr;
335 WCHAR *str,*x;
336
337 f++;
338 switch (*f) {
339 case '1':case '2':case '3':case '4':case '5':
340 case '6':case '7':case '8':case '9':
341 if (dwFlags & FORMAT_MESSAGE_IGNORE_INSERTS)
342 goto ignore_inserts;
343 else if (((dwFlags & FORMAT_MESSAGE_ARGUMENT_ARRAY) && !format_args->args) ||
344 (!(dwFlags & FORMAT_MESSAGE_ARGUMENT_ARRAY) && !format_args->list))
345 {
346 SetLastError(ERROR_INVALID_PARAMETER);
347 HeapFree(GetProcessHeap(), 0, fmd.formatted);
348 return NULL;
349 }
350 insertnr = *f-'0';
351 switch (f[1]) {
352 case '0':case '1':case '2':case '3':
353 case '4':case '5':case '6':case '7':
354 case '8':case '9':
355 f++;
356 insertnr = insertnr*10 + *f-'0';
357 f++;
358 break;
359 default:
360 f++;
361 break;
362 }
363 f = format_insert( unicode_caller, insertnr, f, dwFlags, format_args, &str );
364 for (x = str; *x; x++) format_add_char(&fmd, *x);
365 HeapFree( GetProcessHeap(), 0, str );
366 break;
367 case 'n':
368 format_add_char(&fmd, '\r');
369 format_add_char(&fmd, '\n');
370 f++;
371 break;
372 case 'r':
373 format_add_char(&fmd, '\r');
374 f++;
375 break;
376 case 't':
377 format_add_char(&fmd, '\t');
378 f++;
379 break;
380 case '0':
381 eos = TRUE;
382 f++;
383 break;
384 case '\0':
385 SetLastError(ERROR_INVALID_PARAMETER);
386 HeapFree(GetProcessHeap(), 0, fmd.formatted);
387 return NULL;
388 ignore_inserts:
389 default:
390 if (dwFlags & FORMAT_MESSAGE_IGNORE_INSERTS)
391 format_add_char(&fmd, '%');
392 format_add_char(&fmd, *f++);
393 break;
394 }
395 } else {
396 WCHAR ch = *f;
397 f++;
398 if (ch == '\r') {
399 if (*f == '\n')
400 f++;
401 if(fmd.width)
402 format_add_char(&fmd, ' ');
403 else
404 {
405 format_add_char(&fmd, '\r');
406 format_add_char(&fmd, '\n');
407 }
408 } else {
409 if (ch == '\n')
410 {
411 if(fmd.width)
412 format_add_char(&fmd, ' ');
413 else
414 {
415 format_add_char(&fmd, '\r');
416 format_add_char(&fmd, '\n');
417 }
418 }
419 else
420 format_add_char(&fmd, ch);
421 }
422 }
423 }
424 *fmd.t = '\0';
425
426 return fmd.formatted;
427 }
428
429 /***********************************************************************
430 * FormatMessageA (KERNEL32.@)
431 */
432 DWORD WINAPI FormatMessageA(
433 DWORD dwFlags,
434 LPCVOID lpSource,
435 DWORD dwMessageId,
436 DWORD dwLanguageId,
437 LPSTR lpBuffer,
438 DWORD nSize,
439 __ms_va_list* args )
440 {
441 struct format_args format_args;
442 DWORD ret = 0;
443 LPWSTR target;
444 DWORD destlength;
445 LPWSTR from;
446
447 TRACE("(0x%x,%p,%d,0x%x,%p,%d,%p)\n",
448 dwFlags,lpSource,dwMessageId,dwLanguageId,lpBuffer,nSize,args);
449
450 if (dwFlags & FORMAT_MESSAGE_ALLOCATE_BUFFER)
451 {
452 if (!lpBuffer)
453 {
454 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
455 return 0;
456 }
457 else
458 *(LPSTR *)lpBuffer = NULL;
459 }
460
461 if (dwFlags & FORMAT_MESSAGE_ARGUMENT_ARRAY)
462 {
463 format_args.args = (ULONG_PTR *)args;
464 format_args.list = NULL;
465 format_args.last = 0;
466 }
467 else
468 {
469 format_args.args = NULL;
470 format_args.list = args;
471 format_args.last = 0;
472 }
473
474 from = NULL;
475 if (dwFlags & FORMAT_MESSAGE_FROM_STRING)
476 {
477 DWORD length = MultiByteToWideChar(CP_ACP, 0, lpSource, -1, NULL, 0);
478 from = HeapAlloc( GetProcessHeap(), 0, length * sizeof(WCHAR) );
479 MultiByteToWideChar(CP_ACP, 0, lpSource, -1, from, length);
480 }
481 else if (dwFlags & (FORMAT_MESSAGE_FROM_HMODULE | FORMAT_MESSAGE_FROM_SYSTEM))
482 {
483 if (dwFlags & FORMAT_MESSAGE_FROM_HMODULE)
484 from = load_message( (HMODULE)lpSource, dwMessageId, dwLanguageId );
485 if (!from && (dwFlags & FORMAT_MESSAGE_FROM_SYSTEM))
486 from = load_message( kernel32_handle, dwMessageId, dwLanguageId );
487 if (!from) return 0;
488 }
489 else
490 {
491 SetLastError(ERROR_INVALID_PARAMETER);
492 return 0;
493 }
494
495 target = format_message( FALSE, dwFlags, from, &format_args );
496 if (!target)
497 goto failure;
498
499 TRACE("-- %s\n", debugstr_w(target));
500
501 /* Only try writing to an output buffer if there are processed characters
502 * in the temporary output buffer. */
503 if (*target)
504 {
505 destlength = WideCharToMultiByte(CP_ACP, 0, target, -1, NULL, 0, NULL, NULL);
506 if (dwFlags & FORMAT_MESSAGE_ALLOCATE_BUFFER)
507 {
508 LPSTR buf = LocalAlloc(LMEM_ZEROINIT, max(nSize, destlength));
509 WideCharToMultiByte(CP_ACP, 0, target, -1, buf, destlength, NULL, NULL);
510 *((LPSTR*)lpBuffer) = buf;
511 }
512 else
513 {
514 if (nSize < destlength)
515 {
516 SetLastError(ERROR_INSUFFICIENT_BUFFER);
517 goto failure;
518 }
519 WideCharToMultiByte(CP_ACP, 0, target, -1, lpBuffer, destlength, NULL, NULL);
520 }
521 ret = destlength - 1; /* null terminator */
522 }
523
524 failure:
525 HeapFree(GetProcessHeap(),0,target);
526 HeapFree(GetProcessHeap(),0,from);
527 if (!(dwFlags & FORMAT_MESSAGE_ARGUMENT_ARRAY)) HeapFree( GetProcessHeap(), 0, format_args.args );
528 TRACE("-- returning %u\n", ret);
529 return ret;
530 }
531
532 /***********************************************************************
533 * FormatMessageW (KERNEL32.@)
534 */
535 DWORD WINAPI FormatMessageW(
536 DWORD dwFlags,
537 LPCVOID lpSource,
538 DWORD dwMessageId,
539 DWORD dwLanguageId,
540 LPWSTR lpBuffer,
541 DWORD nSize,
542 __ms_va_list* args )
543 {
544 struct format_args format_args;
545 DWORD ret = 0;
546 LPWSTR target;
547 DWORD talloced;
548 LPWSTR from;
549
550 TRACE("(0x%x,%p,%d,0x%x,%p,%d,%p)\n",
551 dwFlags,lpSource,dwMessageId,dwLanguageId,lpBuffer,nSize,args);
552
553 if (!lpBuffer)
554 {
555 SetLastError(ERROR_INVALID_PARAMETER);
556 return 0;
557 }
558
559 if (dwFlags & FORMAT_MESSAGE_ALLOCATE_BUFFER)
560 *(LPWSTR *)lpBuffer = NULL;
561
562 if (dwFlags & FORMAT_MESSAGE_ARGUMENT_ARRAY)
563 {
564 format_args.args = (ULONG_PTR *)args;
565 format_args.list = NULL;
566 format_args.last = 0;
567 }
568 else
569 {
570 format_args.args = NULL;
571 format_args.list = args;
572 format_args.last = 0;
573 }
574
575 from = NULL;
576 if (dwFlags & FORMAT_MESSAGE_FROM_STRING) {
577 from = HeapAlloc( GetProcessHeap(), 0, (strlenW(lpSource) + 1) *
578 sizeof(WCHAR) );
579 strcpyW( from, lpSource );
580 }
581 else if (dwFlags & (FORMAT_MESSAGE_FROM_HMODULE | FORMAT_MESSAGE_FROM_SYSTEM))
582 {
583 if (dwFlags & FORMAT_MESSAGE_FROM_HMODULE)
584 from = load_message( (HMODULE)lpSource, dwMessageId, dwLanguageId );
585 if (!from && (dwFlags & FORMAT_MESSAGE_FROM_SYSTEM))
586 from = load_message( kernel32_handle, dwMessageId, dwLanguageId );
587 if (!from) return 0;
588 }
589 else
590 {
591 SetLastError(ERROR_INVALID_PARAMETER);
592 return 0;
593 }
594
595 target = format_message( TRUE, dwFlags, from, &format_args );
596 if (!target)
597 goto failure;
598
599 talloced = strlenW(target)+1;
600 TRACE("-- %s\n",debugstr_w(target));
601
602 /* Only allocate a buffer if there are processed characters in the
603 * temporary output buffer. If a caller supplies the buffer, then
604 * a null terminator will be written to it. */
605 if (dwFlags & FORMAT_MESSAGE_ALLOCATE_BUFFER)
606 {
607 if (*target)
608 {
609 /* nSize is the MINIMUM size */
610 *((LPVOID*)lpBuffer) = LocalAlloc(LMEM_ZEROINIT, max(nSize, talloced)*sizeof(WCHAR));
611 strcpyW(*(LPWSTR*)lpBuffer, target);
612 }
613 }
614 else
615 {
616 if (nSize < talloced)
617 {
618 SetLastError(ERROR_INSUFFICIENT_BUFFER);
619 goto failure;
620 }
621 strcpyW(lpBuffer, target);
622 }
623
624 ret = talloced - 1; /* null terminator */
625 failure:
626 HeapFree(GetProcessHeap(),0,target);
627 HeapFree(GetProcessHeap(),0,from);
628 if (!(dwFlags & FORMAT_MESSAGE_ARGUMENT_ARRAY)) HeapFree( GetProcessHeap(), 0, format_args.args );
629 TRACE("-- returning %u\n", ret);
630 return ret;
631 }