Removed HEAP_strdupA.
[wine] / dlls / kernel / format_msg.c
1 /*
2  * FormatMessage implementation
3  *
4  * Copyright 1996 Marcus Meissner
5  */
6
7 #include "config.h"
8
9 #include <stdio.h>
10 #include <string.h>
11
12 #include "windef.h"
13 #include "winbase.h"
14 #include "winerror.h"
15 #include "winnls.h"
16 #include "wine/unicode.h"
17
18 #include "heap.h"
19 #include "debugtools.h"
20
21 DEFAULT_DEBUG_CHANNEL(resource);
22
23
24 /* Messages...used by FormatMessage32* (KERNEL32.something)
25  * 
26  * They can be specified either directly or using a message ID and
27  * loading them from the resource.
28  * 
29  * The resourcedata has following format:
30  * start:
31  * 0: DWORD nrofentries
32  * nrofentries * subentry:
33  *      0: DWORD firstentry
34  *      4: DWORD lastentry
35  *      8: DWORD offset from start to the stringentries
36  *
37  * (lastentry-firstentry) * stringentry:
38  * 0: WORD len (0 marks end)    [ includes the 4 byte header length ]
39  * 2: WORD flags
40  * 4: CHAR[len-4]
41  *      (stringentry i of a subentry refers to the ID 'firstentry+i')
42  *
43  * Yes, ANSI strings in win32 resources. Go figure.
44  */
45
46 /**********************************************************************
47  *      load_messageA           (internal)
48  */
49 static INT load_messageA( HMODULE instance, UINT id, WORD lang,
50                           LPSTR buffer, INT buflen )
51 {
52     HGLOBAL     hmem;
53     HRSRC       hrsrc;
54     PMESSAGE_RESOURCE_DATA      mrd;
55     PMESSAGE_RESOURCE_BLOCK     mrb;
56     PMESSAGE_RESOURCE_ENTRY     mre;
57     int         i,slen;
58
59     TRACE("instance = %08lx, id = %08lx, buffer = %p, length = %ld\n", (DWORD)instance, (DWORD)id, buffer, (DWORD)buflen);
60
61     /*FIXME: I am not sure about the '1' ... But I've only seen those entries*/
62     hrsrc = FindResourceExW(instance,RT_MESSAGELISTW,(LPWSTR)1,lang);
63     if (!hrsrc) return 0;
64     hmem = LoadResource( instance, hrsrc );
65     if (!hmem) return 0;
66     
67     mrd = (PMESSAGE_RESOURCE_DATA)LockResource(hmem);
68     mre = NULL;
69     mrb = &(mrd->Blocks[0]);
70     for (i=mrd->NumberOfBlocks;i--;) {
71         if ((id>=mrb->LowId) && (id<=mrb->HighId)) {
72             mre = (PMESSAGE_RESOURCE_ENTRY)(((char*)mrd)+mrb->OffsetToEntries);
73             id  -= mrb->LowId;
74             break;
75         }
76         mrb++;
77     }
78     if (!mre)
79         return 0;
80     for (i=id;i--;) {
81         if (!mre->Length)
82                 return 0;
83         mre = (PMESSAGE_RESOURCE_ENTRY)(((char*)mre)+mre->Length);
84     }
85     slen=mre->Length;
86     TRACE("     - strlen=%d\n",slen);
87     i = min(buflen - 1, slen);
88     if (buffer == NULL)
89         return slen;
90     if (i>0) {
91         if (mre->Flags & MESSAGE_RESOURCE_UNICODE)
92             WideCharToMultiByte( CP_ACP, 0, (LPWSTR)mre->Text, -1, buffer, i, NULL, NULL );
93         else
94             lstrcpynA(buffer, (LPSTR)mre->Text, i);
95         buffer[i]=0;
96     } else {
97         if (buflen>1) {
98             buffer[0]=0;
99             return 0;
100         }
101     }
102     if (buffer)
103             TRACE("'%s' copied !\n", buffer);
104     return i;
105 }
106
107 #if 0  /* FIXME */
108 /**********************************************************************
109  *      load_messageW   (internal)
110  */
111 static INT load_messageW( HMODULE instance, UINT id, WORD lang,
112                           LPWSTR buffer, INT buflen )
113 {
114     INT retval;
115     LPSTR buffer2 = NULL;
116     if (buffer && buflen)
117         buffer2 = HeapAlloc( GetProcessHeap(), 0, buflen );
118     retval = load_messageA(instance,id,lang,buffer2,buflen);
119     if (buffer)
120     {
121         if (retval) {
122             lstrcpynAtoW( buffer, buffer2, buflen );
123             retval = strlenW( buffer );
124         }
125         HeapFree( GetProcessHeap(), 0, buffer2 );
126     }
127     return retval;
128 }
129 #endif
130
131
132 /***********************************************************************
133  *           FormatMessageA   (KERNEL32.@)
134  * FIXME: missing wrap,
135  */
136 DWORD WINAPI FormatMessageA(
137         DWORD   dwFlags,
138         LPCVOID lpSource,
139         DWORD   dwMessageId,
140         DWORD   dwLanguageId,
141         LPSTR   lpBuffer,
142         DWORD   nSize,
143         va_list* _args )
144 {
145     LPDWORD args=(LPDWORD)_args;
146 #ifdef __i386__
147 /* This implementation is completely dependant on the format of the va_list on x86 CPUs */
148     LPSTR       target,t;
149     DWORD       talloced;
150     LPSTR       from,f;
151     DWORD       width = dwFlags & FORMAT_MESSAGE_MAX_WIDTH_MASK;
152     BOOL    eos = FALSE;
153     INT bufsize;
154     HMODULE     hmodule = (HMODULE)lpSource;
155     CHAR        ch;
156
157     TRACE("(0x%lx,%p,%ld,0x%lx,%p,%ld,%p)\n",
158           dwFlags,lpSource,dwMessageId,dwLanguageId,lpBuffer,nSize,args);
159     if ((dwFlags & FORMAT_MESSAGE_FROM_SYSTEM)
160         && (dwFlags & FORMAT_MESSAGE_FROM_HMODULE)) return 0;
161     if ((dwFlags & FORMAT_MESSAGE_FROM_STRING)
162         &&((dwFlags & FORMAT_MESSAGE_FROM_SYSTEM)
163            || (dwFlags & FORMAT_MESSAGE_FROM_HMODULE))) return 0;
164
165     if (width && width != FORMAT_MESSAGE_MAX_WIDTH_MASK) 
166         FIXME("line wrapping (%lu) not supported.\n", width);
167     from = NULL;
168     if (dwFlags & FORMAT_MESSAGE_FROM_STRING)
169     {
170         from = HeapAlloc( GetProcessHeap(), 0, strlen((LPSTR)lpSource)+1 );
171         strcpy( from, (LPSTR)lpSource );
172     }
173     else {
174         if (dwFlags & FORMAT_MESSAGE_FROM_SYSTEM)
175             hmodule = GetModuleHandleA("kernel32");
176         bufsize=load_messageA(hmodule,dwMessageId,dwLanguageId,NULL,100);
177         if (!bufsize) {
178             if (dwLanguageId) {
179                 SetLastError (ERROR_RESOURCE_LANG_NOT_FOUND);
180                 return 0;
181             }
182             bufsize=load_messageA(hmodule,dwMessageId,
183                                   MAKELANGID(LANG_NEUTRAL,SUBLANG_NEUTRAL),NULL,100);
184             if (!bufsize) bufsize=load_messageA(hmodule,dwMessageId,
185                                                 MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT),NULL,100);
186             if (!bufsize) bufsize=load_messageA(hmodule,dwMessageId,
187                                                 MAKELANGID(LANG_NEUTRAL,SUBLANG_SYS_DEFAULT),NULL,100);
188             if (!bufsize) bufsize=load_messageA(hmodule,dwMessageId,
189                                                 MAKELANGID(LANG_NEUTRAL,SUBLANG_SYS_DEFAULT),NULL,100);
190             if (!bufsize) bufsize=load_messageA(hmodule,dwMessageId,
191                                                 MAKELANGID(LANG_ENGLISH,SUBLANG_ENGLISH_US),NULL,100);
192             if (!bufsize) {
193                 SetLastError (ERROR_RESOURCE_LANG_NOT_FOUND);
194                 return 0;
195             }
196         }
197         from = HeapAlloc( GetProcessHeap(), 0, bufsize + 1 );
198         load_messageA(hmodule,dwMessageId,dwLanguageId,from,bufsize+1);
199     }
200     target      = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, 100);
201     t   = target;
202     talloced= 100;
203
204 #define ADD_TO_T(c) do { \
205         *t++=c;\
206         if (t-target == talloced) {\
207             target = (char*)HeapReAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,target,talloced*2);\
208             t = target+talloced;\
209             talloced*=2;\
210       }\
211 } while (0)
212
213     if (from) {
214         f=from;
215         if (dwFlags & FORMAT_MESSAGE_IGNORE_INSERTS) {
216             while (*f && !eos)
217                 ADD_TO_T(*f++);
218         }
219         else {
220             while (*f && !eos) {
221                 if (*f=='%') {
222                     int insertnr;
223                     char *fmtstr,*x,*lastf;
224                     DWORD *argliststart;
225
226                     fmtstr = NULL;
227                     lastf = f;
228                     f++;
229                     if (!*f) {
230                         ADD_TO_T('%');
231                         continue;
232                     }
233                     switch (*f) {
234                     case '1':case '2':case '3':case '4':case '5':
235                     case '6':case '7':case '8':case '9':
236                         insertnr=*f-'0';
237                         switch (f[1]) {
238                         case '0':case '1':case '2':case '3':
239                         case '4':case '5':case '6':case '7':
240                         case '8':case '9':
241                             f++;
242                             insertnr=insertnr*10+*f-'0';
243                             f++;
244                             break;
245                         default:
246                             f++;
247                             break;
248                         }
249                         if (*f=='!') {
250                             f++;
251                             if (NULL!=(x=strchr(f,'!'))) {
252                                 *x='\0';
253                                 fmtstr=HeapAlloc(GetProcessHeap(),0,strlen(f)+2);
254                                 sprintf(fmtstr,"%%%s",f);
255                                 f=x+1;
256                             } else {
257                                 fmtstr=HeapAlloc(GetProcessHeap(),0,strlen(f)+2);
258                                 sprintf(fmtstr,"%%%s",f);
259                                 f+=strlen(f); /*at \0*/
260                             }
261                         } else {
262                             if(!args) break;
263                             fmtstr = HeapAlloc(GetProcessHeap(),0,3);
264                             strcpy( fmtstr, "%s" );
265                         }
266                         if (args) {
267                             int sz;
268                             LPSTR b;
269
270                             if (dwFlags & FORMAT_MESSAGE_ARGUMENT_ARRAY)
271                                 argliststart=args+insertnr-1;
272                             else
273                                 argliststart=(*(DWORD**)args)+insertnr-1;
274
275                                 /* FIXME: precision and width components are not handled correctly */
276                             if (strcmp(fmtstr, "%ls") == 0) {
277                                 sz = WideCharToMultiByte( CP_ACP, 0, *(WCHAR**)argliststart, -1, NULL, 0, NULL, NULL);
278                                 b = HeapAlloc(GetProcessHeap(), 0, sz);
279                                 WideCharToMultiByte( CP_ACP, 0, *(WCHAR**)argliststart, -1, b, sz, NULL, NULL);
280                             } else {
281                                 b = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sz = 100);
282                                 /* CMF - This makes a BIG assumption about va_list */
283                                 TRACE("A BIG assumption\n");
284                                 while (vsnprintf(b, sz, fmtstr, (va_list) argliststart) < 0) {
285                                     b = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, b, sz += 100);
286                                 }
287                             }
288                             for (x=b; *x; x++) ADD_TO_T(*x);
289
290                             HeapFree(GetProcessHeap(),0,b);
291                         } else {
292                                 /* NULL args - copy formatstr 
293                                  * (probably wrong)
294                                  */
295                             while ((lastf<f)&&(*lastf)) {
296                                 ADD_TO_T(*lastf++);
297                             }
298                         }
299                         HeapFree(GetProcessHeap(),0,fmtstr);
300                         break;
301                     case 'n':
302                         ADD_TO_T('\r');
303                         ADD_TO_T('\n');
304                         f++;
305                         break;
306                     case '0':
307                         eos = TRUE;
308                         f++;
309                         break;
310                     default:
311                         ADD_TO_T(*f++);
312                         break;
313                     }
314                 } else {
315                     ch = *f;
316                     f++;
317                     if (ch == '\r') {
318                         if (*f == '\n')
319                             f++;
320                         ADD_TO_T(' ');
321                     } else {
322                         if (ch == '\n')
323                         {
324                             ADD_TO_T('\r');
325                             ADD_TO_T('\n');
326                         }
327                         else
328                             ADD_TO_T(ch);
329                     }
330                 }
331             }
332         }
333         *t='\0';
334     }
335     talloced = strlen(target)+1;
336     if (nSize && talloced<nSize) {
337         target = (char*)HeapReAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,target,nSize);
338     }
339     TRACE("-- %s\n",debugstr_a(target));
340     if (dwFlags & FORMAT_MESSAGE_ALLOCATE_BUFFER) {
341         *((LPVOID*)lpBuffer) = (LPVOID)LocalAlloc(GMEM_ZEROINIT,max(nSize, talloced));
342         memcpy(*(LPSTR*)lpBuffer,target,talloced);
343     } else {
344         lstrcpynA(lpBuffer,target,nSize);
345     }
346     HeapFree(GetProcessHeap(),0,target);
347     if (from) HeapFree(GetProcessHeap(),0,from);
348     TRACE("-- returning %d\n", (dwFlags & FORMAT_MESSAGE_ALLOCATE_BUFFER) ?  strlen(*(LPSTR*)lpBuffer):strlen(lpBuffer));
349     return (dwFlags & FORMAT_MESSAGE_ALLOCATE_BUFFER) ?
350         strlen(*(LPSTR*)lpBuffer):
351             strlen(lpBuffer);
352 #else
353     return 0;
354 #endif /* __i386__ */
355 }
356 #undef ADD_TO_T
357
358
359 /***********************************************************************
360  *           FormatMessageW   (KERNEL32.@)
361  */
362 DWORD WINAPI FormatMessageW(
363         DWORD   dwFlags,
364         LPCVOID lpSource,
365         DWORD   dwMessageId,
366         DWORD   dwLanguageId,
367         LPWSTR  lpBuffer,
368         DWORD   nSize,
369         va_list* _args )
370 {
371     LPDWORD args=(LPDWORD)_args;
372 #ifdef __i386__
373 /* This implementation is completely dependant on the format of the va_list on x86 CPUs */
374     LPSTR target,t;
375     DWORD talloced;
376     LPSTR from,f;
377     DWORD width = dwFlags & FORMAT_MESSAGE_MAX_WIDTH_MASK;
378     BOOL eos = FALSE;
379     INT bufsize;
380     HMODULE hmodule = (HMODULE)lpSource;
381     CHAR ch;
382
383     TRACE("(0x%lx,%p,%ld,0x%lx,%p,%ld,%p)\n",
384           dwFlags,lpSource,dwMessageId,dwLanguageId,lpBuffer,nSize,args);
385     if ((dwFlags & FORMAT_MESSAGE_FROM_SYSTEM)
386         && (dwFlags & FORMAT_MESSAGE_FROM_HMODULE)) return 0;
387     if ((dwFlags & FORMAT_MESSAGE_FROM_STRING)
388         &&((dwFlags & FORMAT_MESSAGE_FROM_SYSTEM)
389            || (dwFlags & FORMAT_MESSAGE_FROM_HMODULE))) return 0;
390
391     if (width && width != FORMAT_MESSAGE_MAX_WIDTH_MASK)
392         FIXME("line wrapping not supported.\n");
393     from = NULL;
394     if (dwFlags & FORMAT_MESSAGE_FROM_STRING) {
395         from = HEAP_strdupWtoA(GetProcessHeap(),0,(LPWSTR)lpSource);
396     }
397     else {
398         if (dwFlags & FORMAT_MESSAGE_FROM_SYSTEM)
399             hmodule = GetModuleHandleA("kernel32");
400         bufsize=load_messageA(hmodule,dwMessageId,dwLanguageId,NULL,100);
401         if (!bufsize) {
402             if (dwLanguageId) {
403                 SetLastError (ERROR_RESOURCE_LANG_NOT_FOUND);
404                 return 0;
405             }
406             bufsize=load_messageA(hmodule,dwMessageId,
407                                   MAKELANGID(LANG_NEUTRAL,SUBLANG_NEUTRAL),NULL,100);
408             if (!bufsize) bufsize=load_messageA(hmodule,dwMessageId,
409                                                 MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT),NULL,100);
410             if (!bufsize) bufsize=load_messageA(hmodule,dwMessageId,
411                                                 MAKELANGID(LANG_NEUTRAL,SUBLANG_SYS_DEFAULT),NULL,100);
412             if (!bufsize) bufsize=load_messageA(hmodule,dwMessageId,
413                                                 MAKELANGID(LANG_NEUTRAL,SUBLANG_SYS_DEFAULT),NULL,100);
414             if (!bufsize) bufsize=load_messageA(hmodule,dwMessageId,
415                                                 MAKELANGID(LANG_ENGLISH,SUBLANG_ENGLISH_US),NULL,100);
416             if (!bufsize) {
417                 SetLastError (ERROR_RESOURCE_LANG_NOT_FOUND);
418                 return 0;
419             }
420         }
421         from = HeapAlloc( GetProcessHeap(), 0, bufsize + 1 );
422         load_messageA(hmodule,dwMessageId,dwLanguageId,from,bufsize+1);
423     }
424     target = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, 100 );
425     t = target;
426     talloced= 100;
427
428 #define ADD_TO_T(c)  do {\
429     *t++=c;\
430     if (t-target == talloced) {\
431         target = (char*)HeapReAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,target,talloced*2);\
432         t = target+talloced;\
433         talloced*=2;\
434     } \
435 } while (0)
436
437     if (from) {
438         f=from;
439         if (dwFlags & FORMAT_MESSAGE_IGNORE_INSERTS) {
440             while (*f && !eos)
441                 ADD_TO_T(*f++);
442         }
443         else {
444             while (*f && !eos) {
445                 if (*f=='%') {
446                     int insertnr;
447                     char *fmtstr,*sprintfbuf,*x;
448                     DWORD *argliststart;
449
450                     fmtstr = NULL;
451                     f++;
452                     if (!*f) {
453                         ADD_TO_T('%');
454                         continue;
455                     }
456
457                     switch (*f) {
458                     case '1':case '2':case '3':case '4':case '5':
459                     case '6':case '7':case '8':case '9':
460                         insertnr=*f-'0';
461                         switch (f[1]) {
462                         case '0':case '1':case '2':case '3':
463                         case '4':case '5':case '6':case '7':
464                         case '8':case '9':
465                             f++;
466                             insertnr=insertnr*10+*f-'0';
467                             f++;
468                             break;
469                         default:
470                             f++;
471                             break;
472                         }
473                         if (*f=='!') {
474                             f++;
475                             if (NULL!=(x=strchr(f,'!'))) {
476                                 *x='\0';
477                                 fmtstr=HeapAlloc( GetProcessHeap(), 0, strlen(f)+2);
478                                 sprintf(fmtstr,"%%%s",f);
479                                 f=x+1;
480                             } else {
481                                 fmtstr=HeapAlloc(GetProcessHeap(),0,strlen(f));
482                                 sprintf(fmtstr,"%%%s",f);
483                                 f+=strlen(f); /*at \0*/
484                             }
485                         } else {
486                             if(!args) break;
487                             fmtstr = HeapAlloc( GetProcessHeap(),0,3);
488                             strcpy( fmtstr, "%s" );
489                         }
490                         if (dwFlags & FORMAT_MESSAGE_ARGUMENT_ARRAY)
491                             argliststart=args+insertnr-1;
492                         else
493                             argliststart=(*(DWORD**)args)+insertnr-1;
494
495                         if (fmtstr[strlen(fmtstr)-1]=='s' && argliststart[0]) {
496                             DWORD xarr[3];
497
498                             xarr[0]=(DWORD)HEAP_strdupWtoA(GetProcessHeap(),0,(LPWSTR)(*(argliststart+0)));
499                             /* possible invalid pointers */
500                             xarr[1]=*(argliststart+1);
501                             xarr[2]=*(argliststart+2);
502                             sprintfbuf=HeapAlloc(GetProcessHeap(),0,strlenW((LPWSTR)argliststart[0])*2+1);
503
504                             /* CMF - This makes a BIG assumption about va_list */
505                             vsprintf(sprintfbuf, fmtstr, (va_list) xarr);
506                         } else {
507                             sprintfbuf=HeapAlloc(GetProcessHeap(),0,100);
508
509                             /* CMF - This makes a BIG assumption about va_list */
510                             vsprintf(sprintfbuf, fmtstr, (va_list) argliststart);
511                         }
512                         x=sprintfbuf;
513                         while (*x) {
514                             ADD_TO_T(*x++);
515                         }
516                         HeapFree(GetProcessHeap(),0,sprintfbuf);
517                         HeapFree(GetProcessHeap(),0,fmtstr);
518                         break;
519                     case 'n':
520                         ADD_TO_T('\r');
521                         ADD_TO_T('\n');
522                         f++;
523                         break;
524                     case '0':
525                         eos = TRUE;
526                         f++;
527                         break;
528                     default:
529                         ADD_TO_T(*f++);
530                         break;
531                     }
532                 } else {
533                     ch = *f;
534                     f++;
535                     if (ch == '\r') {
536                         if (*f == '\n')
537                             f++;
538                         ADD_TO_T(' ');
539                     } else {
540                         if (ch == '\n')
541                         {
542                             ADD_TO_T('\r');
543                             ADD_TO_T('\n');
544                         }
545                         else
546                             ADD_TO_T(ch);
547                     }
548                 }
549             }
550         }
551         *t='\0';
552     }
553     talloced = strlen(target)+1;
554     if (nSize && talloced<nSize)
555         target = (char*)HeapReAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,target,nSize);
556     if (dwFlags & FORMAT_MESSAGE_ALLOCATE_BUFFER) {
557         /* nSize is the MINIMUM size */
558         DWORD len = MultiByteToWideChar( CP_ACP, 0, target, -1, NULL, 0 );
559         *((LPVOID*)lpBuffer) = (LPVOID)LocalAlloc(GMEM_ZEROINIT,len*sizeof(WCHAR));
560         MultiByteToWideChar( CP_ACP, 0, target, -1, *(LPWSTR*)lpBuffer, len );
561     }
562     else
563     {
564         if (nSize > 0 && !MultiByteToWideChar( CP_ACP, 0, target, -1, lpBuffer, nSize ))
565             lpBuffer[nSize-1] = 0;
566     }
567     HeapFree(GetProcessHeap(),0,target);
568     if (from) HeapFree(GetProcessHeap(),0,from);
569     return (dwFlags & FORMAT_MESSAGE_ALLOCATE_BUFFER) ?
570         strlenW(*(LPWSTR*)lpBuffer):
571             strlenW(lpBuffer);
572 #else
573     return 0;
574 #endif /* __i386__ */
575 }
576 #undef ADD_TO_T