kernel32: Fail if a format placeholder is present without a format specifier in Forma...
[wine/hacks.git] / dlls / kernel32 / format_msg.c
blobb6ffb7f26a5e58464bbb4dd17acdb0d8289e8f90
1 /*
2 * FormatMessage implementation
4 * Copyright 1996 Marcus Meissner
5 * Copyright 2009 Alexandre Julliard
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.
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.
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
22 #include "config.h"
24 #include <stdarg.h>
25 #include <stdio.h>
26 #include <string.h>
28 #include "ntstatus.h"
29 #define WIN32_NO_STATUS
30 #include "windef.h"
31 #include "winbase.h"
32 #include "winerror.h"
33 #include "winternl.h"
34 #include "winuser.h"
35 #include "winnls.h"
36 #include "wine/unicode.h"
37 #include "kernel_private.h"
38 #include "wine/debug.h"
40 WINE_DEFAULT_DEBUG_CHANNEL(resource);
42 struct format_args
44 ULONG_PTR *args;
45 __ms_va_list *list;
46 int last;
49 /* Messages used by FormatMessage
51 * They can be specified either directly or using a message ID and
52 * loading them from the resource.
54 * The resourcedata has following format:
55 * start:
56 * 0: DWORD nrofentries
57 * nrofentries * subentry:
58 * 0: DWORD firstentry
59 * 4: DWORD lastentry
60 * 8: DWORD offset from start to the stringentries
62 * (lastentry-firstentry) * stringentry:
63 * 0: WORD len (0 marks end) [ includes the 4 byte header length ]
64 * 2: WORD flags
65 * 4: CHAR[len-4]
66 * (stringentry i of a subentry refers to the ID 'firstentry+i')
68 * Yes, ANSI strings in win32 resources. Go figure.
71 static const WCHAR PCNTFMTWSTR[] = { '%','%','%','s',0 };
72 static const WCHAR FMTWSTR[] = { '%','s',0 };
74 /**********************************************************************
75 * load_message (internal)
77 static LPWSTR load_message( HMODULE module, UINT id, WORD lang )
79 const MESSAGE_RESOURCE_ENTRY *mre;
80 WCHAR *buffer;
81 NTSTATUS status;
83 TRACE("module = %p, id = %08x\n", module, id );
85 if (!module) module = GetModuleHandleW( NULL );
86 if ((status = RtlFindMessage( module, RT_MESSAGETABLE, lang, id, &mre )) != STATUS_SUCCESS)
88 SetLastError( RtlNtStatusToDosError(status) );
89 return NULL;
92 if (mre->Flags & MESSAGE_RESOURCE_UNICODE)
94 int len = (strlenW( (const WCHAR *)mre->Text ) + 1) * sizeof(WCHAR);
95 if (!(buffer = HeapAlloc( GetProcessHeap(), 0, len ))) return NULL;
96 memcpy( buffer, mre->Text, len );
98 else
100 int len = MultiByteToWideChar( CP_ACP, 0, (const char *)mre->Text, -1, NULL, 0 );
101 if (!(buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) ))) return NULL;
102 MultiByteToWideChar( CP_ACP, 0, (const char*)mre->Text, -1, buffer, len );
104 TRACE("returning %s\n", wine_dbgstr_w(buffer));
105 return buffer;
108 /**********************************************************************
109 * get_arg (internal)
111 static ULONG_PTR get_arg( int nr, DWORD flags, struct format_args *args )
113 if (nr == -1) nr = args->last + 1;
114 if (args->list)
116 if (!args->args) args->args = HeapAlloc( GetProcessHeap(), 0, 99 * sizeof(ULONG_PTR) );
117 while (nr > args->last)
118 args->args[args->last++] = va_arg( *args->list, ULONG_PTR );
120 if (nr > args->last) args->last = nr;
121 return args->args[nr - 1];
124 /**********************************************************************
125 * format_insert (internal)
127 static LPCWSTR format_insert( BOOL unicode_caller, int insert, LPCWSTR format,
128 DWORD flags, struct format_args *args,
129 LPWSTR *result )
131 static const WCHAR fmt_lu[] = {'%','l','u',0};
132 WCHAR *wstring = NULL, *p, fmt[256];
133 ULONG_PTR arg;
134 int size;
136 if (*format != '!') /* simple string */
138 arg = get_arg( insert, flags, args );
139 if (unicode_caller)
141 WCHAR *str = (WCHAR *)arg;
142 *result = HeapAlloc( GetProcessHeap(), 0, (strlenW(str) + 1) * sizeof(WCHAR) );
143 strcpyW( *result, str );
145 else
147 char *str = (char *)get_arg( insert, flags, args );
148 DWORD length = MultiByteToWideChar( CP_ACP, 0, str, -1, NULL, 0 );
149 *result = HeapAlloc( GetProcessHeap(), 0, length * sizeof(WCHAR) );
150 MultiByteToWideChar( CP_ACP, 0, str, -1, *result, length );
152 return format;
155 format++;
156 p = fmt;
157 *p++ = '%';
159 while (*format == '0' ||
160 *format == '+' ||
161 *format == '-' ||
162 *format == ' ' ||
163 *format == '*' ||
164 *format == '#')
166 if (*format == '*')
168 p += sprintfW( p, fmt_lu, get_arg( insert, flags, args ));
169 insert = -1;
170 format++;
172 else *p++ = *format++;
174 while (isdigitW(*format)) *p++ = *format++;
176 if (*format == '.')
178 *p++ = *format++;
179 if (*format == '*')
181 p += sprintfW( p, fmt_lu, get_arg( insert, flags, args ));
182 insert = -1;
183 format++;
185 else
186 while (isdigitW(*format)) *p++ = *format++;
189 /* replicate MS bug: drop an argument when using va_list with width/precision */
190 if (insert == -1 && args->list) args->last--;
191 arg = get_arg( insert, flags, args );
193 /* check for ascii string format */
194 if ((format[0] == 'h' && format[1] == 's') ||
195 (format[0] == 'h' && format[1] == 'S') ||
196 (unicode_caller && format[0] == 'S') ||
197 (!unicode_caller && format[0] == 's'))
199 DWORD len = MultiByteToWideChar( CP_ACP, 0, (char *)arg, -1, NULL, 0 );
200 wstring = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
201 MultiByteToWideChar( CP_ACP, 0, (char *)arg, -1, wstring, len );
202 arg = (ULONG_PTR)wstring;
203 *p++ = 's';
205 /* check for ascii character format */
206 else if ((format[0] == 'h' && format[1] == 'c') ||
207 (format[0] == 'h' && format[1] == 'C') ||
208 (unicode_caller && format[0] == 'C') ||
209 (!unicode_caller && format[0] == 'c'))
211 char ch = arg;
212 wstring = HeapAlloc( GetProcessHeap(), 0, 2 * sizeof(WCHAR) );
213 MultiByteToWideChar( CP_ACP, 0, &ch, 1, wstring, 1 );
214 wstring[1] = 0;
215 arg = (ULONG_PTR)wstring;
216 *p++ = 's';
218 /* check for wide string format */
219 else if ((format[0] == 'l' && format[1] == 's') ||
220 (format[0] == 'l' && format[1] == 'S') ||
221 (format[0] == 'w' && format[1] == 's') ||
222 (!unicode_caller && format[0] == 'S'))
224 *p++ = 's';
226 /* check for wide character format */
227 else if ((format[0] == 'l' && format[1] == 'c') ||
228 (format[0] == 'l' && format[1] == 'C') ||
229 (format[0] == 'w' && format[1] == 'c') ||
230 (!unicode_caller && format[0] == 'C'))
232 *p++ = 'c';
234 /* FIXME: handle I64 etc. */
235 else while (*format && *format != '!') *p++ = *format++;
237 *p = 0;
238 size = 256;
239 for (;;)
241 WCHAR *ret = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) );
242 int needed = snprintfW( ret, size, fmt, arg );
243 if (needed == -1 || needed >= size)
245 HeapFree( GetProcessHeap(), 0, ret );
246 size = max( needed + 1, size * 2 );
248 else
250 *result = ret;
251 break;
255 while (*format && *format != '!') format++;
256 if (*format == '!') format++;
258 HeapFree( GetProcessHeap(), 0, wstring );
259 return format;
262 /**********************************************************************
263 * format_message (internal)
265 static LPWSTR format_message( BOOL unicode_caller, DWORD dwFlags, LPCWSTR fmtstr,
266 struct format_args *format_args )
268 LPWSTR target,t;
269 DWORD talloced;
270 LPCWSTR f;
271 DWORD width = dwFlags & FORMAT_MESSAGE_MAX_WIDTH_MASK;
272 BOOL eos = FALSE;
273 WCHAR ch;
275 target = t = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, 100 * sizeof(WCHAR) );
276 talloced = 100;
278 #define ADD_TO_T(c) do {\
279 *t++=c;\
280 if ((DWORD)(t-target) == talloced) {\
281 target = HeapReAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,target,talloced*2*sizeof(WCHAR));\
282 t = target+talloced;\
283 talloced*=2;\
285 } while (0)
287 f = fmtstr;
288 if (dwFlags & FORMAT_MESSAGE_IGNORE_INSERTS) {
289 while (*f && !eos)
290 ADD_TO_T(*f++);
292 else {
293 while (*f && !eos) {
294 if (*f=='%') {
295 int insertnr;
296 WCHAR *str,*x;
298 f++;
299 if (!*f) {
300 SetLastError(ERROR_INVALID_PARAMETER);
301 HeapFree(GetProcessHeap(), 0, target);
302 return NULL;
305 switch (*f) {
306 case '1':case '2':case '3':case '4':case '5':
307 case '6':case '7':case '8':case '9':
308 insertnr = *f-'0';
309 switch (f[1]) {
310 case '0':case '1':case '2':case '3':
311 case '4':case '5':case '6':case '7':
312 case '8':case '9':
313 f++;
314 insertnr = insertnr*10 + *f-'0';
315 f++;
316 break;
317 default:
318 f++;
319 break;
321 f = format_insert( unicode_caller, insertnr, f, dwFlags, format_args, &str );
322 for (x = str; *x; x++) ADD_TO_T(*x);
323 HeapFree( GetProcessHeap(), 0, str );
324 break;
325 case 'n':
326 ADD_TO_T('\r');
327 ADD_TO_T('\n');
328 f++;
329 break;
330 case '0':
331 eos = TRUE;
332 f++;
333 break;
334 default:
335 ADD_TO_T(*f++);
336 break;
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
348 ADD_TO_T('\r');
349 ADD_TO_T('\n');
351 } else {
352 if (ch == '\n')
354 if(width)
355 ADD_TO_T(' ');
356 else
358 ADD_TO_T('\r');
359 ADD_TO_T('\n');
362 else
363 ADD_TO_T(ch);
368 *t = '\0';
370 return target;
372 #undef ADD_TO_T
374 /***********************************************************************
375 * FormatMessageA (KERNEL32.@)
376 * FIXME: missing wrap,
378 DWORD WINAPI FormatMessageA(
379 DWORD dwFlags,
380 LPCVOID lpSource,
381 DWORD dwMessageId,
382 DWORD dwLanguageId,
383 LPSTR lpBuffer,
384 DWORD nSize,
385 __ms_va_list* args )
387 struct format_args format_args;
388 DWORD ret = 0;
389 LPWSTR target;
390 DWORD destlength;
391 LPWSTR from;
392 DWORD width = dwFlags & FORMAT_MESSAGE_MAX_WIDTH_MASK;
394 TRACE("(0x%x,%p,%d,0x%x,%p,%d,%p)\n",
395 dwFlags,lpSource,dwMessageId,dwLanguageId,lpBuffer,nSize,args);
396 if ((dwFlags & FORMAT_MESSAGE_FROM_STRING)
397 &&((dwFlags & FORMAT_MESSAGE_FROM_SYSTEM)
398 || (dwFlags & FORMAT_MESSAGE_FROM_HMODULE))) return 0;
400 if ((dwFlags & FORMAT_MESSAGE_ALLOCATE_BUFFER) && !lpBuffer)
402 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
403 return 0;
406 if (dwFlags & FORMAT_MESSAGE_ARGUMENT_ARRAY)
408 format_args.args = (ULONG_PTR *)args;
409 format_args.list = NULL;
410 format_args.last = 0;
412 else
414 format_args.args = NULL;
415 format_args.list = args;
416 format_args.last = 0;
419 if (width && width != FORMAT_MESSAGE_MAX_WIDTH_MASK)
420 FIXME("line wrapping (%u) not supported.\n", width);
421 from = NULL;
422 if (dwFlags & FORMAT_MESSAGE_FROM_STRING)
424 DWORD length = MultiByteToWideChar(CP_ACP, 0, lpSource, -1, NULL, 0);
425 from = HeapAlloc( GetProcessHeap(), 0, length * sizeof(WCHAR) );
426 MultiByteToWideChar(CP_ACP, 0, lpSource, -1, from, length);
428 else {
429 if (dwFlags & FORMAT_MESSAGE_FROM_HMODULE)
430 from = load_message( (HMODULE)lpSource, dwMessageId, dwLanguageId );
431 if (!from && (dwFlags & FORMAT_MESSAGE_FROM_SYSTEM))
432 from = load_message( kernel32_handle, dwMessageId, dwLanguageId );
433 if (!from) return 0;
436 target = format_message( FALSE, dwFlags, from, &format_args );
437 if (!target)
438 goto failure;
440 TRACE("-- %s\n", debugstr_w(target));
441 destlength = WideCharToMultiByte(CP_ACP, 0, target, -1, NULL, 0, NULL, NULL);
442 if (dwFlags & FORMAT_MESSAGE_ALLOCATE_BUFFER) {
443 LPSTR buf = LocalAlloc(LMEM_ZEROINIT, max(nSize, destlength));
444 WideCharToMultiByte(CP_ACP, 0, target, -1, buf, destlength, NULL, NULL);
445 *((LPSTR*)lpBuffer) = buf;
446 } else {
447 if (nSize < destlength)
449 SetLastError(ERROR_INSUFFICIENT_BUFFER);
450 goto failure;
453 WideCharToMultiByte(CP_ACP, 0, target, -1, lpBuffer, destlength, NULL, NULL);
456 ret = destlength - 1; /* null terminator */
457 failure:
458 HeapFree(GetProcessHeap(),0,target);
459 HeapFree(GetProcessHeap(),0,from);
460 if (!(dwFlags & FORMAT_MESSAGE_ARGUMENT_ARRAY)) HeapFree( GetProcessHeap(), 0, format_args.args );
461 TRACE("-- returning %u\n", ret);
462 return ret;
464 #undef ADD_TO_T
467 /***********************************************************************
468 * FormatMessageW (KERNEL32.@)
470 DWORD WINAPI FormatMessageW(
471 DWORD dwFlags,
472 LPCVOID lpSource,
473 DWORD dwMessageId,
474 DWORD dwLanguageId,
475 LPWSTR lpBuffer,
476 DWORD nSize,
477 __ms_va_list* args )
479 struct format_args format_args;
480 DWORD ret = 0;
481 LPWSTR target;
482 DWORD talloced;
483 LPWSTR from;
484 DWORD width = dwFlags & FORMAT_MESSAGE_MAX_WIDTH_MASK;
486 TRACE("(0x%x,%p,%d,0x%x,%p,%d,%p)\n",
487 dwFlags,lpSource,dwMessageId,dwLanguageId,lpBuffer,nSize,args);
488 if ((dwFlags & FORMAT_MESSAGE_FROM_STRING)
489 &&((dwFlags & FORMAT_MESSAGE_FROM_SYSTEM)
490 || (dwFlags & FORMAT_MESSAGE_FROM_HMODULE))) return 0;
492 if (!lpBuffer)
494 SetLastError(ERROR_INVALID_PARAMETER);
495 return 0;
498 if (dwFlags & FORMAT_MESSAGE_ARGUMENT_ARRAY)
500 format_args.args = (ULONG_PTR *)args;
501 format_args.list = NULL;
502 format_args.last = 0;
504 else
506 format_args.args = NULL;
507 format_args.list = args;
508 format_args.last = 0;
511 if (width && width != FORMAT_MESSAGE_MAX_WIDTH_MASK)
512 FIXME("line wrapping not supported.\n");
513 from = NULL;
514 if (dwFlags & FORMAT_MESSAGE_FROM_STRING) {
515 from = HeapAlloc( GetProcessHeap(), 0, (strlenW(lpSource) + 1) *
516 sizeof(WCHAR) );
517 strcpyW( from, lpSource );
519 else {
520 if (dwFlags & FORMAT_MESSAGE_FROM_HMODULE)
521 from = load_message( (HMODULE)lpSource, dwMessageId, dwLanguageId );
522 if (!from && (dwFlags & FORMAT_MESSAGE_FROM_SYSTEM))
523 from = load_message( kernel32_handle, dwMessageId, dwLanguageId );
524 if (!from) return 0;
527 target = format_message( TRUE, dwFlags, from, &format_args );
528 if (!target)
529 goto failure;
531 talloced = strlenW(target)+1;
532 TRACE("-- %s\n",debugstr_w(target));
533 if (dwFlags & FORMAT_MESSAGE_ALLOCATE_BUFFER) {
534 /* nSize is the MINIMUM size */
535 *((LPVOID*)lpBuffer) = LocalAlloc(LMEM_ZEROINIT, max(nSize, talloced)*sizeof(WCHAR));
536 strcpyW(*(LPWSTR*)lpBuffer, target);
538 else
540 if (nSize < talloced)
542 SetLastError(ERROR_INSUFFICIENT_BUFFER);
543 goto failure;
545 strcpyW(lpBuffer, target);
548 ret = talloced - 1; /* null terminator */
549 failure:
550 HeapFree(GetProcessHeap(),0,target);
551 HeapFree(GetProcessHeap(),0,from);
552 if (!(dwFlags & FORMAT_MESSAGE_ARGUMENT_ARRAY)) HeapFree( GetProcessHeap(), 0, format_args.args );
553 TRACE("-- returning %u\n", ret);
554 return ret;
556 #undef ADD_TO_T