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