- BuildCommDCB16() uses int instead of BOOL
[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.265)
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         from = HEAP_strdupA( GetProcessHeap(), 0, (LPSTR)lpSource);
170     }
171     else {
172         if (dwFlags & FORMAT_MESSAGE_FROM_SYSTEM)
173             hmodule = GetModuleHandleA("kernel32");
174         bufsize=load_messageA(hmodule,dwMessageId,dwLanguageId,NULL,100);
175         if (!bufsize) {
176             if (dwLanguageId) {
177                 SetLastError (ERROR_RESOURCE_LANG_NOT_FOUND);
178                 return 0;
179             }
180             bufsize=load_messageA(hmodule,dwMessageId,
181                                   MAKELANGID(LANG_NEUTRAL,SUBLANG_NEUTRAL),NULL,100);
182             if (!bufsize) bufsize=load_messageA(hmodule,dwMessageId,
183                                                 MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT),NULL,100);
184             if (!bufsize) bufsize=load_messageA(hmodule,dwMessageId,
185                                                 MAKELANGID(LANG_NEUTRAL,SUBLANG_SYS_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_ENGLISH,SUBLANG_ENGLISH_US),NULL,100);
190             if (!bufsize) {
191                 SetLastError (ERROR_RESOURCE_LANG_NOT_FOUND);
192                 return 0;
193             }
194         }
195         from = HeapAlloc( GetProcessHeap(), 0, bufsize + 1 );
196         load_messageA(hmodule,dwMessageId,dwLanguageId,from,bufsize+1);
197     }
198     target      = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, 100);
199     t   = target;
200     talloced= 100;
201
202 #define ADD_TO_T(c) do { \
203         *t++=c;\
204         if (t-target == talloced) {\
205             target = (char*)HeapReAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,target,talloced*2);\
206             t = target+talloced;\
207             talloced*=2;\
208       }\
209 } while (0)
210
211     if (from) {
212         f=from;
213         if (dwFlags & FORMAT_MESSAGE_IGNORE_INSERTS) {
214             while (*f && !eos)
215                 ADD_TO_T(*f++);
216         }
217         else {
218             while (*f && !eos) {
219                 if (*f=='%') {
220                     int insertnr;
221                     char *fmtstr,*x,*lastf;
222                     DWORD *argliststart;
223
224                     fmtstr = NULL;
225                     lastf = f;
226                     f++;
227                     if (!*f) {
228                         ADD_TO_T('%');
229                         continue;
230                     }
231                     switch (*f) {
232                     case '1':case '2':case '3':case '4':case '5':
233                     case '6':case '7':case '8':case '9':
234                         insertnr=*f-'0';
235                         switch (f[1]) {
236                         case '0':case '1':case '2':case '3':
237                         case '4':case '5':case '6':case '7':
238                         case '8':case '9':
239                             f++;
240                             insertnr=insertnr*10+*f-'0';
241                             f++;
242                             break;
243                         default:
244                             f++;
245                             break;
246                         }
247                         if (*f=='!') {
248                             f++;
249                             if (NULL!=(x=strchr(f,'!'))) {
250                                 *x='\0';
251                                 fmtstr=HeapAlloc(GetProcessHeap(),0,strlen(f)+2);
252                                 sprintf(fmtstr,"%%%s",f);
253                                 f=x+1;
254                             } else {
255                                 fmtstr=HeapAlloc(GetProcessHeap(),0,strlen(f)+2);
256                                 sprintf(fmtstr,"%%%s",f);
257                                 f+=strlen(f); /*at \0*/
258                             }
259                         } else {
260                             if(!args)
261                                 break;
262                             else
263                                 fmtstr=HEAP_strdupA(GetProcessHeap(),0,"%s");
264                         }
265                         if (args) {
266                             int sz;
267                             LPSTR b;
268
269                             if (dwFlags & FORMAT_MESSAGE_ARGUMENT_ARRAY)
270                                 argliststart=args+insertnr-1;
271                             else
272                                 argliststart=(*(DWORD**)args)+insertnr-1;
273
274                                 /* FIXME: precision and width components are not handled correctly */
275                             if (strcmp(fmtstr, "%ls") == 0) {
276                                 sz = WideCharToMultiByte( CP_ACP, 0, *(WCHAR**)argliststart, -1, NULL, 0, NULL, NULL);
277                                 b = HeapAlloc(GetProcessHeap(), 0, sz);
278                                 WideCharToMultiByte( CP_ACP, 0, *(WCHAR**)argliststart, -1, b, sz, NULL, NULL);
279                             } else {
280                                 b = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sz = 100);
281                                 /* CMF - This makes a BIG assumption about va_list */
282                                 TRACE("A BIG assumption\n");
283                                 while (vsnprintf(b, sz, fmtstr, (va_list) argliststart) < 0) {
284                                     b = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, b, sz += 100);
285                                 }
286                             }
287                             for (x=b; *x; x++) ADD_TO_T(*x);
288
289                             HeapFree(GetProcessHeap(),0,b);
290                         } else {
291                                 /* NULL args - copy formatstr 
292                                  * (probably wrong)
293                                  */
294                             while ((lastf<f)&&(*lastf)) {
295                                 ADD_TO_T(*lastf++);
296                             }
297                         }
298                         HeapFree(GetProcessHeap(),0,fmtstr);
299                         break;
300                     case 'n':
301                         ADD_TO_T('\r');
302                         ADD_TO_T('\n');
303                         f++;
304                         break;
305                     case '0':
306                         eos = TRUE;
307                         f++;
308                         break;
309                     default:
310                         ADD_TO_T(*f++);
311                         break;
312                     }
313                 } else {
314                     ch = *f;
315                     f++;
316                     if (ch == '\r') {
317                         if (*f == '\n')
318                             f++;
319                         ADD_TO_T(' ');
320                     } else {
321                         if (ch == '\n')
322                         {
323                             ADD_TO_T('\r');
324                             ADD_TO_T('\n');
325                         }
326                         else
327                             ADD_TO_T(ch);
328                     }
329                 }
330             }
331         }
332         *t='\0';
333     }
334     talloced = strlen(target)+1;
335     if (nSize && talloced<nSize) {
336         target = (char*)HeapReAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,target,nSize);
337     }
338     TRACE("-- %s\n",debugstr_a(target));
339     if (dwFlags & FORMAT_MESSAGE_ALLOCATE_BUFFER) {
340         *((LPVOID*)lpBuffer) = (LPVOID)LocalAlloc(GMEM_ZEROINIT,max(nSize, talloced));
341         memcpy(*(LPSTR*)lpBuffer,target,talloced);
342     } else {
343         lstrcpynA(lpBuffer,target,nSize);
344     }
345     HeapFree(GetProcessHeap(),0,target);
346     if (from) HeapFree(GetProcessHeap(),0,from);
347     TRACE("-- returning %d\n", (dwFlags & FORMAT_MESSAGE_ALLOCATE_BUFFER) ?  strlen(*(LPSTR*)lpBuffer):strlen(lpBuffer));
348     return (dwFlags & FORMAT_MESSAGE_ALLOCATE_BUFFER) ?
349         strlen(*(LPSTR*)lpBuffer):
350             strlen(lpBuffer);
351 #else
352     return 0;
353 #endif /* __i386__ */
354 }
355 #undef ADD_TO_T
356
357
358 /***********************************************************************
359  *           FormatMessageW   (KERNEL32.266)
360  */
361 DWORD WINAPI FormatMessageW(
362         DWORD   dwFlags,
363         LPCVOID lpSource,
364         DWORD   dwMessageId,
365         DWORD   dwLanguageId,
366         LPWSTR  lpBuffer,
367         DWORD   nSize,
368         va_list* _args )
369 {
370     LPDWORD args=(LPDWORD)_args;
371 #ifdef __i386__
372 /* This implementation is completely dependant on the format of the va_list on x86 CPUs */
373     LPSTR target,t;
374     DWORD talloced;
375     LPSTR from,f;
376     DWORD width = dwFlags & FORMAT_MESSAGE_MAX_WIDTH_MASK;
377     BOOL eos = FALSE;
378     INT bufsize;
379     HMODULE hmodule = (HMODULE)lpSource;
380     CHAR ch;
381
382     TRACE("(0x%lx,%p,%ld,0x%lx,%p,%ld,%p)\n",
383           dwFlags,lpSource,dwMessageId,dwLanguageId,lpBuffer,nSize,args);
384     if ((dwFlags & FORMAT_MESSAGE_FROM_SYSTEM)
385         && (dwFlags & FORMAT_MESSAGE_FROM_HMODULE)) return 0;
386     if ((dwFlags & FORMAT_MESSAGE_FROM_STRING)
387         &&((dwFlags & FORMAT_MESSAGE_FROM_SYSTEM)
388            || (dwFlags & FORMAT_MESSAGE_FROM_HMODULE))) return 0;
389
390     if (width && width != FORMAT_MESSAGE_MAX_WIDTH_MASK)
391         FIXME("line wrapping not supported.\n");
392     from = NULL;
393     if (dwFlags & FORMAT_MESSAGE_FROM_STRING) {
394         from = HEAP_strdupWtoA(GetProcessHeap(),0,(LPWSTR)lpSource);
395     }
396     else {
397         if (dwFlags & FORMAT_MESSAGE_FROM_SYSTEM)
398             hmodule = GetModuleHandleA("kernel32");
399         bufsize=load_messageA(hmodule,dwMessageId,dwLanguageId,NULL,100);
400         if (!bufsize) {
401             if (dwLanguageId) {
402                 SetLastError (ERROR_RESOURCE_LANG_NOT_FOUND);
403                 return 0;
404             }
405             bufsize=load_messageA(hmodule,dwMessageId,
406                                   MAKELANGID(LANG_NEUTRAL,SUBLANG_NEUTRAL),NULL,100);
407             if (!bufsize) bufsize=load_messageA(hmodule,dwMessageId,
408                                                 MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT),NULL,100);
409             if (!bufsize) bufsize=load_messageA(hmodule,dwMessageId,
410                                                 MAKELANGID(LANG_NEUTRAL,SUBLANG_SYS_DEFAULT),NULL,100);
411             if (!bufsize) bufsize=load_messageA(hmodule,dwMessageId,
412                                                 MAKELANGID(LANG_NEUTRAL,SUBLANG_SYS_DEFAULT),NULL,100);
413             if (!bufsize) bufsize=load_messageA(hmodule,dwMessageId,
414                                                 MAKELANGID(LANG_ENGLISH,SUBLANG_ENGLISH_US),NULL,100);
415             if (!bufsize) {
416                 SetLastError (ERROR_RESOURCE_LANG_NOT_FOUND);
417                 return 0;
418             }
419         }
420         from = HeapAlloc( GetProcessHeap(), 0, bufsize + 1 );
421         load_messageA(hmodule,dwMessageId,dwLanguageId,from,bufsize+1);
422     }
423     target = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, 100 );
424     t = target;
425     talloced= 100;
426
427 #define ADD_TO_T(c)  do {\
428     *t++=c;\
429     if (t-target == talloced) {\
430         target = (char*)HeapReAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,target,talloced*2);\
431         t = target+talloced;\
432         talloced*=2;\
433     } \
434 } while (0)
435
436     if (from) {
437         f=from;
438         if (dwFlags & FORMAT_MESSAGE_IGNORE_INSERTS) {
439             while (*f && !eos)
440                 ADD_TO_T(*f++);
441         }
442         else {
443             while (*f && !eos) {
444                 if (*f=='%') {
445                     int insertnr;
446                     char *fmtstr,*sprintfbuf,*x;
447                     DWORD *argliststart;
448
449                     fmtstr = NULL;
450                     f++;
451                     if (!*f) {
452                         ADD_TO_T('%');
453                         continue;
454                     }
455
456                     switch (*f) {
457                     case '1':case '2':case '3':case '4':case '5':
458                     case '6':case '7':case '8':case '9':
459                         insertnr=*f-'0';
460                         switch (f[1]) {
461                         case '0':case '1':case '2':case '3':
462                         case '4':case '5':case '6':case '7':
463                         case '8':case '9':
464                             f++;
465                             insertnr=insertnr*10+*f-'0';
466                             f++;
467                             break;
468                         default:
469                             f++;
470                             break;
471                         }
472                         if (*f=='!') {
473                             f++;
474                             if (NULL!=(x=strchr(f,'!'))) {
475                                 *x='\0';
476                                 fmtstr=HeapAlloc( GetProcessHeap(), 0, strlen(f)+2);
477                                 sprintf(fmtstr,"%%%s",f);
478                                 f=x+1;
479                             } else {
480                                 fmtstr=HeapAlloc(GetProcessHeap(),0,strlen(f));
481                                 sprintf(fmtstr,"%%%s",f);
482                                 f+=strlen(f); /*at \0*/
483                             }
484                         } else {
485                             if(!args)
486                                 break;
487                             else
488                                 fmtstr=HEAP_strdupA( GetProcessHeap(),0,"%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