format_msg.c 17.6 KB
Newer Older
Dave Pickles's avatar
Dave Pickles committed
1 2 3 4
/*
 * FormatMessage implementation
 *
 * Copyright 1996 Marcus Meissner
5
 * Copyright 2009 Alexandre Julliard
6 7 8 9 10 11 12 13 14 15 16 17 18
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * 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
Dave Pickles's avatar
Dave Pickles committed
20 21 22 23
 */

#include "config.h"

24
#include <stdarg.h>
Dave Pickles's avatar
Dave Pickles committed
25 26 27
#include <stdio.h>
#include <string.h>

28
#include "ntstatus.h"
29
#define WIN32_NO_STATUS
Dave Pickles's avatar
Dave Pickles committed
30 31 32
#include "windef.h"
#include "winbase.h"
#include "winerror.h"
33
#include "winternl.h"
34
#include "winuser.h"
Dave Pickles's avatar
Dave Pickles committed
35
#include "winnls.h"
36
#include "wine/unicode.h"
37
#include "kernel_private.h"
38
#include "wine/debug.h"
Dave Pickles's avatar
Dave Pickles committed
39

40
WINE_DEFAULT_DEBUG_CHANNEL(resource);
Dave Pickles's avatar
Dave Pickles committed
41

42 43 44 45 46 47
struct format_args
{
    ULONG_PTR    *args;
    __ms_va_list *list;
    int           last;
};
Dave Pickles's avatar
Dave Pickles committed
48

49
/* Messages used by FormatMessage
50
 *
Dave Pickles's avatar
Dave Pickles committed
51 52
 * They can be specified either directly or using a message ID and
 * loading them from the resource.
53
 *
Dave Pickles's avatar
Dave Pickles committed
54 55 56 57 58 59 60 61 62
 * The resourcedata has following format:
 * start:
 * 0: DWORD nrofentries
 * nrofentries * subentry:
 *	0: DWORD firstentry
 *	4: DWORD lastentry
 *      8: DWORD offset from start to the stringentries
 *
 * (lastentry-firstentry) * stringentry:
63
 * 0: WORD len (0 marks end)	[ includes the 4 byte header length ]
Dave Pickles's avatar
Dave Pickles committed
64 65 66 67 68 69 70
 * 2: WORD flags
 * 4: CHAR[len-4]
 * 	(stringentry i of a subentry refers to the ID 'firstentry+i')
 *
 * Yes, ANSI strings in win32 resources. Go figure.
 */

71 72
static const WCHAR PCNTFMTWSTR[] = { '%','%','%','s',0 };
static const WCHAR FMTWSTR[] = { '%','s',0 };
73

Dave Pickles's avatar
Dave Pickles committed
74
/**********************************************************************
75
 *	load_message    (internal)
Dave Pickles's avatar
Dave Pickles committed
76
 */
77
static LPWSTR load_message( HMODULE module, UINT id, WORD lang )
Dave Pickles's avatar
Dave Pickles committed
78
{
79
    const MESSAGE_RESOURCE_ENTRY *mre;
80
    WCHAR *buffer;
81
    NTSTATUS status;
Dave Pickles's avatar
Dave Pickles committed
82

83
    TRACE("module = %p, id = %08x\n", module, id );
Dave Pickles's avatar
Dave Pickles committed
84

85
    if (!module) module = GetModuleHandleW( NULL );
86 87 88 89 90
    if ((status = RtlFindMessage( module, RT_MESSAGETABLE, lang, id, &mre )) != STATUS_SUCCESS)
    {
        SetLastError( RtlNtStatusToDosError(status) );
        return NULL;
    }
91

92
    if (mre->Flags & MESSAGE_RESOURCE_UNICODE)
93 94 95 96 97
    {
        int len = (strlenW( (const WCHAR *)mre->Text ) + 1) * sizeof(WCHAR);
        if (!(buffer = HeapAlloc( GetProcessHeap(), 0, len ))) return NULL;
        memcpy( buffer, mre->Text, len );
    }
98
    else
99
    {
Mike McCormack's avatar
Mike McCormack committed
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;
Mike McCormack's avatar
Mike McCormack committed
102
        MultiByteToWideChar( CP_ACP, 0, (const char*)mre->Text, -1, buffer, len );
Dave Pickles's avatar
Dave Pickles committed
103
    }
104 105
    TRACE("returning %s\n", wine_dbgstr_w(buffer));
    return buffer;
Dave Pickles's avatar
Dave Pickles committed
106 107
}

108 109 110
/**********************************************************************
 *	get_arg    (internal)
 */
111
static ULONG_PTR get_arg( int nr, DWORD flags, struct format_args *args )
112
{
113 114 115 116 117 118 119 120 121
    if (nr == -1) nr = args->last + 1;
    if (args->list)
    {
        if (!args->args) args->args = HeapAlloc( GetProcessHeap(), 0, 99 * sizeof(ULONG_PTR) );
        while (nr > args->last)
            args->args[args->last++] = va_arg( *args->list, ULONG_PTR );
    }
    if (nr > args->last) args->last = nr;
    return args->args[nr - 1];
122 123 124
}

/**********************************************************************
125
 *	format_insert    (internal)
126
 */
127 128 129
static LPCWSTR format_insert( BOOL unicode_caller, int insert, LPCWSTR format,
                              DWORD flags, struct format_args *args,
                              LPWSTR *result )
130
{
131 132
    static const WCHAR fmt_lu[] = {'%','l','u',0};
    WCHAR *wstring = NULL, *p, fmt[256];
133 134 135 136 137
    ULONG_PTR arg;
    int size;

    if (*format != '!')  /* simple string */
    {
138 139
        arg = get_arg( insert, flags, args );
        if (unicode_caller)
140
        {
141 142 143
            WCHAR *str = (WCHAR *)arg;
            *result = HeapAlloc( GetProcessHeap(), 0, (strlenW(str) + 1) * sizeof(WCHAR) );
            strcpyW( *result, str );
144 145 146
        }
        else
        {
147
            char *str = (char *)arg;
148 149 150
            DWORD length = MultiByteToWideChar( CP_ACP, 0, str, -1, NULL, 0 );
            *result = HeapAlloc( GetProcessHeap(), 0, length * sizeof(WCHAR) );
            MultiByteToWideChar( CP_ACP, 0, str, -1, *result, length );
151
        }
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
        return format;
    }

    format++;
    p = fmt;
    *p++ = '%';

    while (*format == '0' ||
           *format == '+' ||
           *format == '-' ||
           *format == ' ' ||
           *format == '*' ||
           *format == '#')
    {
        if (*format == '*')
        {
            p += sprintfW( p, fmt_lu, get_arg( insert, flags, args ));
169
            insert = -1;
170 171 172 173 174 175 176 177 178 179 180 181
            format++;
        }
        else *p++ = *format++;
    }
    while (isdigitW(*format)) *p++ = *format++;

    if (*format == '.')
    {
        *p++ = *format++;
        if (*format == '*')
        {
            p += sprintfW( p, fmt_lu, get_arg( insert, flags, args ));
182
            insert = -1;
183 184 185 186 187 188
            format++;
        }
        else
            while (isdigitW(*format)) *p++ = *format++;
    }

189 190
    /* replicate MS bug: drop an argument when using va_list with width/precision */
    if (insert == -1 && args->list) args->last--;
191 192 193 194 195
    arg = get_arg( insert, flags, args );

    /* check for ascii string format */
    if ((format[0] == 'h' && format[1] == 's') ||
        (format[0] == 'h' && format[1] == 'S') ||
196 197
        (unicode_caller && format[0] == 'S') ||
        (!unicode_caller && format[0] == 's'))
198
    {
199
        DWORD len = MultiByteToWideChar( CP_ACP, 0, (char *)arg, -1, NULL, 0 );
200 201 202 203 204 205 206 207
        wstring = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
        MultiByteToWideChar( CP_ACP, 0, (char *)arg, -1, wstring, len );
        arg = (ULONG_PTR)wstring;
        *p++ = 's';
    }
    /* check for ascii character format */
    else if ((format[0] == 'h' && format[1] == 'c') ||
             (format[0] == 'h' && format[1] == 'C') ||
208 209
             (unicode_caller && format[0] == 'C') ||
             (!unicode_caller && format[0] == 'c'))
210 211
    {
        char ch = arg;
212
        wstring = HeapAlloc( GetProcessHeap(), 0, 2 * sizeof(WCHAR) );
213 214 215 216 217 218 219 220
        MultiByteToWideChar( CP_ACP, 0, &ch, 1, wstring, 1 );
        wstring[1] = 0;
        arg = (ULONG_PTR)wstring;
        *p++ = 's';
    }
    /* check for wide string format */
    else if ((format[0] == 'l' && format[1] == 's') ||
             (format[0] == 'l' && format[1] == 'S') ||
221 222
             (format[0] == 'w' && format[1] == 's') ||
             (!unicode_caller && format[0] == 'S'))
223 224 225 226 227 228
    {
        *p++ = 's';
    }
    /* check for wide character format */
    else if ((format[0] == 'l' && format[1] == 'c') ||
             (format[0] == 'l' && format[1] == 'C') ||
229 230
             (format[0] == 'w' && format[1] == 'c') ||
             (!unicode_caller && format[0] == 'C'))
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
    {
        *p++ = 'c';
    }
    /* FIXME: handle I64 etc. */
    else while (*format && *format != '!') *p++ = *format++;

    *p = 0;
    size = 256;
    for (;;)
    {
        WCHAR *ret = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) );
        int needed = snprintfW( ret, size, fmt, arg );
        if (needed == -1 || needed >= size)
        {
            HeapFree( GetProcessHeap(), 0, ret );
            size = max( needed + 1, size * 2 );
        }
        else
        {
            *result = ret;
            break;
        }
    }

    while (*format && *format != '!') format++;
    if (*format == '!') format++;

    HeapFree( GetProcessHeap(), 0, wstring );
    return format;
}

262
/**********************************************************************
263
 *	format_message    (internal)
264
 */
265 266
static LPWSTR format_message( BOOL unicode_caller, DWORD dwFlags, LPCWSTR fmtstr,
                              struct format_args *format_args )
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
{
    LPWSTR target,t;
    DWORD talloced;
    LPCWSTR f;
    DWORD width = dwFlags & FORMAT_MESSAGE_MAX_WIDTH_MASK;
    BOOL eos = FALSE;
    WCHAR ch;

    target = t = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, 100 * sizeof(WCHAR) );
    talloced = 100;

#define ADD_TO_T(c)  do {\
    *t++=c;\
    if ((DWORD)(t-target) == talloced) {\
        target = HeapReAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,target,talloced*2*sizeof(WCHAR));\
        t = target+talloced;\
        talloced*=2;\
    } \
} while (0)

    f = fmtstr;
288 289 290 291 292 293 294 295 296 297 298
    while (*f && !eos) {
        if (*f=='%') {
            int insertnr;
            WCHAR *str,*x;

            f++;
            switch (*f) {
            case '1':case '2':case '3':case '4':case '5':
            case '6':case '7':case '8':case '9':
                if (dwFlags & FORMAT_MESSAGE_IGNORE_INSERTS)
                    goto ignore_inserts;
299 300 301 302 303 304 305
                else if (((dwFlags & FORMAT_MESSAGE_ARGUMENT_ARRAY) && !format_args->args) ||
                        (!(dwFlags & FORMAT_MESSAGE_ARGUMENT_ARRAY) && !format_args->list))
                {
                    SetLastError(ERROR_INVALID_PARAMETER);
                    HeapFree(GetProcessHeap(), 0, target);
                    return NULL;
                }
306 307 308 309 310
                insertnr = *f-'0';
                switch (f[1]) {
                case '0':case '1':case '2':case '3':
                case '4':case '5':case '6':case '7':
                case '8':case '9':
311
                    f++;
312
                    insertnr = insertnr*10 + *f-'0';
313 314 315
                    f++;
                    break;
                default:
316
                    f++;
317 318
                    break;
                }
319 320 321 322 323 324 325
                f = format_insert( unicode_caller, insertnr, f, dwFlags, format_args, &str );
                for (x = str; *x; x++) ADD_TO_T(*x);
                HeapFree( GetProcessHeap(), 0, str );
                break;
            case 'n':
                ADD_TO_T('\r');
                ADD_TO_T('\n');
326
                f++;
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
                break;
            case 'r':
                ADD_TO_T('\r');
                f++;
                break;
            case 't':
                ADD_TO_T('\t');
                f++;
                break;
            case '0':
                eos = TRUE;
                f++;
                break;
            case '\0':
                SetLastError(ERROR_INVALID_PARAMETER);
                HeapFree(GetProcessHeap(), 0, target);
                return NULL;
            ignore_inserts:
            default:
                if (dwFlags & FORMAT_MESSAGE_IGNORE_INSERTS)
                    ADD_TO_T('%');
                ADD_TO_T(*f++);
                break;
            }
        } else {
            ch = *f;
            f++;
            if (ch == '\r') {
                if (*f == '\n')
356
                    f++;
357 358 359 360
                if(width)
                    ADD_TO_T(' ');
                else
                {
361
                    ADD_TO_T('\r');
362
                    ADD_TO_T('\n');
363 364
                }
            } else {
365 366
                if (ch == '\n')
                {
367 368 369 370 371 372 373 374
                    if(width)
                        ADD_TO_T(' ');
                    else
                    {
                        ADD_TO_T('\r');
                        ADD_TO_T('\n');
                    }
                }
375 376
                else
                    ADD_TO_T(ch);
377 378 379 380 381 382 383 384
            }
        }
    }
    *t = '\0';

    return target;
}
#undef ADD_TO_T
385

Dave Pickles's avatar
Dave Pickles committed
386
/***********************************************************************
387
 *           FormatMessageA   (KERNEL32.@)
Dave Pickles's avatar
Dave Pickles committed
388 389 390 391 392 393 394 395 396
 * FIXME: missing wrap,
 */
DWORD WINAPI FormatMessageA(
	DWORD	dwFlags,
	LPCVOID	lpSource,
	DWORD	dwMessageId,
	DWORD	dwLanguageId,
	LPSTR	lpBuffer,
	DWORD	nSize,
397
	__ms_va_list* args )
398
{
399
    struct format_args format_args;
400
    DWORD ret = 0;
401 402 403
    LPWSTR	target;
    DWORD	destlength;
    LPWSTR	from;
404 405
    DWORD	width = dwFlags & FORMAT_MESSAGE_MAX_WIDTH_MASK;

406
    TRACE("(0x%x,%p,%d,0x%x,%p,%d,%p)\n",
407 408
          dwFlags,lpSource,dwMessageId,dwLanguageId,lpBuffer,nSize,args);

409
    if (dwFlags & FORMAT_MESSAGE_ALLOCATE_BUFFER)
410
    {
411 412 413 414 415 416 417
        if (!lpBuffer)
        {
            SetLastError(ERROR_NOT_ENOUGH_MEMORY);
            return 0;
        }
        else
            *(LPSTR *)lpBuffer = NULL;
418 419
    }

420 421 422 423 424 425 426 427 428 429 430 431 432
    if (dwFlags & FORMAT_MESSAGE_ARGUMENT_ARRAY)
    {
        format_args.args = (ULONG_PTR *)args;
        format_args.list = NULL;
        format_args.last = 0;
    }
    else
    {
        format_args.args = NULL;
        format_args.list = args;
        format_args.last = 0;
    }

433
    if (width && width != FORMAT_MESSAGE_MAX_WIDTH_MASK)
434
        FIXME("line wrapping (%u) not supported.\n", width);
435
    from = NULL;
436 437
    if (dwFlags & FORMAT_MESSAGE_FROM_STRING)
    {
438 439 440
        DWORD length = MultiByteToWideChar(CP_ACP, 0, lpSource, -1, NULL, 0);
        from = HeapAlloc( GetProcessHeap(), 0, length * sizeof(WCHAR) );
        MultiByteToWideChar(CP_ACP, 0, lpSource, -1, from, length);
441
    }
442 443
    else if (dwFlags & (FORMAT_MESSAGE_FROM_HMODULE | FORMAT_MESSAGE_FROM_SYSTEM))
    {
444
        if (dwFlags & FORMAT_MESSAGE_FROM_HMODULE)
445
            from = load_message( (HMODULE)lpSource, dwMessageId, dwLanguageId );
446
        if (!from && (dwFlags & FORMAT_MESSAGE_FROM_SYSTEM))
447
            from = load_message( kernel32_handle, dwMessageId, dwLanguageId );
448
        if (!from) return 0;
449
    }
450 451 452 453 454
    else
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return 0;
    }
Dave Pickles's avatar
Dave Pickles committed
455

456
    target = format_message( FALSE, dwFlags, from, &format_args );
457 458
    if (!target)
        goto failure;
459

460
    TRACE("-- %s\n", debugstr_w(target));
461 462 463 464 465 466 467

    /* Only try writing to an output buffer if there are processed characters
     * in the temporary output buffer. */
    if (*target)
    {
        destlength = WideCharToMultiByte(CP_ACP, 0, target, -1, NULL, 0, NULL, NULL);
        if (dwFlags & FORMAT_MESSAGE_ALLOCATE_BUFFER)
468
        {
469 470 471
            LPSTR buf = LocalAlloc(LMEM_ZEROINIT, max(nSize, destlength));
            WideCharToMultiByte(CP_ACP, 0, target, -1, buf, destlength, NULL, NULL);
            *((LPSTR*)lpBuffer) = buf;
472
        }
473 474 475 476 477 478 479 480 481 482
        else
        {
            if (nSize < destlength)
            {
                SetLastError(ERROR_INSUFFICIENT_BUFFER);
                goto failure;
            }
            WideCharToMultiByte(CP_ACP, 0, target, -1, lpBuffer, destlength, NULL, NULL);
        }
        ret = destlength - 1; /* null terminator */
483
    }
484 485

failure:
486
    HeapFree(GetProcessHeap(),0,target);
487
    HeapFree(GetProcessHeap(),0,from);
488
    if (!(dwFlags & FORMAT_MESSAGE_ARGUMENT_ARRAY)) HeapFree( GetProcessHeap(), 0, format_args.args );
489
    TRACE("-- returning %u\n", ret);
490
    return ret;
Dave Pickles's avatar
Dave Pickles committed
491 492 493
}

/***********************************************************************
494
 *           FormatMessageW   (KERNEL32.@)
Dave Pickles's avatar
Dave Pickles committed
495 496 497 498 499 500 501 502
 */
DWORD WINAPI FormatMessageW(
	DWORD	dwFlags,
	LPCVOID	lpSource,
	DWORD	dwMessageId,
	DWORD	dwLanguageId,
	LPWSTR	lpBuffer,
	DWORD	nSize,
503
	__ms_va_list* args )
504
{
505
    struct format_args format_args;
506
    DWORD ret = 0;
507
    LPWSTR target;
508
    DWORD talloced;
509
    LPWSTR from;
510 511
    DWORD width = dwFlags & FORMAT_MESSAGE_MAX_WIDTH_MASK;

512
    TRACE("(0x%x,%p,%d,0x%x,%p,%d,%p)\n",
513 514
          dwFlags,lpSource,dwMessageId,dwLanguageId,lpBuffer,nSize,args);

515 516 517 518 519 520
    if (!lpBuffer)
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return 0;
    }

521 522 523
    if (dwFlags & FORMAT_MESSAGE_ALLOCATE_BUFFER)
        *(LPWSTR *)lpBuffer = NULL;

524 525 526 527 528 529 530 531 532 533 534 535 536
    if (dwFlags & FORMAT_MESSAGE_ARGUMENT_ARRAY)
    {
        format_args.args = (ULONG_PTR *)args;
        format_args.list = NULL;
        format_args.last = 0;
    }
    else
    {
        format_args.args = NULL;
        format_args.list = args;
        format_args.last = 0;
    }

537 538 539 540
    if (width && width != FORMAT_MESSAGE_MAX_WIDTH_MASK)
        FIXME("line wrapping not supported.\n");
    from = NULL;
    if (dwFlags & FORMAT_MESSAGE_FROM_STRING) {
541
        from = HeapAlloc( GetProcessHeap(), 0, (strlenW(lpSource) + 1) *
542
            sizeof(WCHAR) );
543
        strcpyW( from, lpSource );
544
    }
545 546
    else if (dwFlags & (FORMAT_MESSAGE_FROM_HMODULE | FORMAT_MESSAGE_FROM_SYSTEM))
    {
547
        if (dwFlags & FORMAT_MESSAGE_FROM_HMODULE)
548
            from = load_message( (HMODULE)lpSource, dwMessageId, dwLanguageId );
549
        if (!from && (dwFlags & FORMAT_MESSAGE_FROM_SYSTEM))
550
            from = load_message( kernel32_handle, dwMessageId, dwLanguageId );
551
        if (!from) return 0;
552
    }
553 554 555 556 557
    else
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return 0;
    }
558

559
    target = format_message( TRUE, dwFlags, from, &format_args );
560 561
    if (!target)
        goto failure;
562

563
    talloced = strlenW(target)+1;
564
    TRACE("-- %s\n",debugstr_w(target));
565 566 567 568 569 570 571 572 573 574 575 576

    /* Only allocate a buffer if there are processed characters in the
     * temporary output buffer. If a caller supplies the buffer, then
     * a null terminator will be written to it. */
    if (dwFlags & FORMAT_MESSAGE_ALLOCATE_BUFFER)
    {
        if (*target)
        {
            /* nSize is the MINIMUM size */
            *((LPVOID*)lpBuffer) = LocalAlloc(LMEM_ZEROINIT, max(nSize, talloced)*sizeof(WCHAR));
            strcpyW(*(LPWSTR*)lpBuffer, target);
        }
577
    }
578 579 580 581 582 583 584 585 586
    else
    {
        if (nSize < talloced)
        {
            SetLastError(ERROR_INSUFFICIENT_BUFFER);
            goto failure;
        }
        strcpyW(lpBuffer, target);
    }
587

588 589
    ret = talloced - 1; /* null terminator */
failure:
590
    HeapFree(GetProcessHeap(),0,target);
591
    HeapFree(GetProcessHeap(),0,from);
592
    if (!(dwFlags & FORMAT_MESSAGE_ARGUMENT_ARRAY)) HeapFree( GetProcessHeap(), 0, format_args.args );
593 594
    TRACE("-- returning %u\n", ret);
    return ret;
Dave Pickles's avatar
Dave Pickles committed
595
}