table.c 49.6 KB
Newer Older
1 2 3
/*
 * Implementation of the Microsoft Installer (msi.dll)
 *
4
 * Copyright 2002-2005 Mike McCormack for CodeWeavers
5 6 7 8 9 10 11 12 13 14 15 16 17
 *
 * 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
18
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19 20
 */

21 22 23
#include <stdarg.h>

#define COBJMACROS
24 25 26
#define NONAMELESSUNION
#define NONAMELESSSTRUCT

27 28 29 30 31 32 33 34 35 36 37 38 39
#include "windef.h"
#include "winbase.h"
#include "winerror.h"
#include "wine/debug.h"
#include "msi.h"
#include "msiquery.h"
#include "objbase.h"
#include "objidl.h"
#include "msipriv.h"
#include "winnls.h"

#include "query.h"

40
WINE_DEFAULT_DEBUG_CHANNEL(msidb);
41

42 43 44 45 46 47 48 49 50
#define MSITABLE_HASH_TABLE_SIZE 37

typedef struct tagMSICOLUMNHASHENTRY
{
    struct tagMSICOLUMNHASHENTRY *next;
    UINT value;
    UINT row;
} MSICOLUMNHASHENTRY;

51 52
typedef struct tagMSICOLUMNINFO
{
53
    LPCWSTR tablename;
54
    UINT   number;
55
    LPCWSTR colname;
56 57
    UINT   type;
    UINT   offset;
58
    MSICOLUMNHASHENTRY **hash_table;
59 60 61 62
} MSICOLUMNINFO;

struct tagMSITABLE
{
63 64
    USHORT **data;
    UINT row_count;
65
    struct list entry;
66
    WCHAR name[1];
67
};
68

69 70 71 72 73
typedef struct tagMSITRANSFORM {
    struct list entry;
    IStorage *stg;
} MSITRANSFORM;

74 75
#define MAX_STREAM_NAME 0x1f

76 77 78 79
static UINT table_get_column_info( MSIDATABASE *db, LPCWSTR name,
       MSICOLUMNINFO **pcols, UINT *pcount );
static UINT get_tablecolumns( MSIDATABASE *db, 
       LPCWSTR szTableName, MSICOLUMNINFO *colinfo, UINT *sz);
80
static void msi_free_colinfo( MSICOLUMNINFO *colinfo, UINT count );
81

82
static inline UINT bytes_per_column( const MSICOLUMNINFO *col )
83 84 85 86 87 88 89 90
{
    if( col->type & MSITYPE_STRING )
        return 2;
    if( (col->type & 0xff) > 4 )
        ERR("Invalid column size!\n");
    return col->type & 0xff;
}

91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
static int utf2mime(int x)
{
    if( (x>='0') && (x<='9') )
        return x-'0';
    if( (x>='A') && (x<='Z') )
        return x-'A'+10;
    if( (x>='a') && (x<='z') )
        return x-'a'+10+26;
    if( x=='.' )
        return 10+26+26;
    if( x=='_' )
        return 10+26+26+1;
    return -1;
}

106
static LPWSTR encode_streamname(BOOL bTable, LPCWSTR in)
107 108 109
{
    DWORD count = MAX_STREAM_NAME;
    DWORD ch, next;
110 111 112
    LPWSTR out, p;

    if( !bTable )
113
        count = lstrlenW( in )+2;
114
    out = msi_alloc( count*sizeof(WCHAR) );
115
    p = out;
116 117 118

    if( bTable )
    {
119
         *p++ = 0x4840;
120 121 122 123 124 125 126
         count --;
    }
    while( count -- ) 
    {
        ch = *in++;
        if( !ch )
        {
127 128
            *p = ch;
            return out;
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
        }
        if( ( ch < 0x80 ) && ( utf2mime(ch) >= 0 ) )
        {
            ch = utf2mime(ch) + 0x4800;
            next = *in;
            if( next && (next<0x80) )
            {
                next = utf2mime(next);
                if( next >= 0  )
                {
                     next += 0x3ffffc0;
                     ch += (next<<6);
                     in++;
                }
            }
        }
145
        *p++ = ch;
146
    }
147
    ERR("Failed to encode stream name (%s)\n",debugstr_w(in));
148
    msi_free( out );
149
    return NULL;
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
}

static int mime2utf(int x)
{
    if( x<10 )
        return x + '0';
    if( x<(10+26))
        return x - 10 + 'A';
    if( x<(10+26+26))
        return x - 10 - 26 + 'a';
    if( x == (10+26+26) )
        return '.';
    return '_';
}

static BOOL decode_streamname(LPWSTR in, LPWSTR out)
{
    WCHAR ch;
    DWORD count = 0;

    while ( (ch = *in++) )
    {
        if( (ch >= 0x3800 ) && (ch < 0x4840 ) )
        {
            if( ch >= 0x4800 )
                ch = mime2utf(ch-0x4800);
            else
            {
                ch -= 0x3800;
                *out++ = mime2utf(ch&0x3f);
                count++;
                ch = mime2utf((ch>>6)&0x3f);
            }
        }
        *out++ = ch;
        count++;
    }
    *out = 0;
    return count;
}
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210

void enum_stream_names( IStorage *stg )
{
    IEnumSTATSTG *stgenum = NULL;
    HRESULT r;
    STATSTG stat;
    ULONG n, count;
    WCHAR name[0x40];

    r = IStorage_EnumElements( stg, 0, NULL, 0, &stgenum );
    if( FAILED( r ) )
        return;

    n = 0;
    while( 1 )
    {
        count = 0;
        r = IEnumSTATSTG_Next( stgenum, 1, &stat, &count );
        if( FAILED( r ) || !count )
            break;
        decode_streamname( stat.pwcsName, name );
211 212
        TRACE("stream %2ld -> %s %s\n", n, 
              debugstr_w(stat.pwcsName), debugstr_w(name) );
213 214 215 216 217 218
        n++;
    }

    IEnumSTATSTG_Release( stgenum );
}

219
static UINT read_stream_data( IStorage *stg, LPCWSTR stname,
220
                              USHORT **pdata, UINT *psz )
221 222 223 224 225
{
    HRESULT r;
    UINT ret = ERROR_FUNCTION_FAILED;
    VOID *data;
    ULONG sz, count;
226 227
    IStream *stm = NULL;
    STATSTG stat;
228
    LPWSTR encname;
229

230
    encname = encode_streamname(TRUE, stname);
231 232

    TRACE("%s -> %s\n",debugstr_w(stname),debugstr_w(encname));
233

234
    r = IStorage_OpenStream(stg, encname, NULL, 
235
            STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &stm);
236
    msi_free( encname );
237 238
    if( FAILED( r ) )
    {
239 240
        WARN("open stream failed r = %08lx - empty table?\n",r);
        return ret;
241 242 243 244 245
    }

    r = IStream_Stat(stm, &stat, STATFLAG_NONAME );
    if( FAILED( r ) )
    {
246
        WARN("open stream failed r = %08lx!\n",r);
247 248 249 250 251
        goto end;
    }

    if( stat.cbSize.QuadPart >> 32 )
    {
252
        WARN("Too big!\n");
253 254 255 256
        goto end;
    }
        
    sz = stat.cbSize.QuadPart;
257
    data = msi_alloc( sz );
258 259
    if( !data )
    {
260
        WARN("couldn't allocate memory r=%08lx!\n",r);
261
        ret = ERROR_NOT_ENOUGH_MEMORY;
262 263 264 265
        goto end;
    }
        
    r = IStream_Read(stm, data, sz, &count );
266
    if( FAILED( r ) || ( count != sz ) )
267
    {
268
        msi_free( data );
269
        WARN("read stream failed r = %08lx!\n",r);
270 271 272
        goto end;
    }

273 274 275
    *pdata = data;
    *psz = sz;
    ret = ERROR_SUCCESS;
276 277

end:
278
    IStream_Release( stm );
279 280 281 282

    return ret;
}

283 284
UINT db_get_raw_stream( MSIDATABASE *db, LPCWSTR stname, IStream **stm )
{
285
    LPWSTR encname;
286 287
    HRESULT r;

288
    encname = encode_streamname(FALSE, stname);
289 290 291 292 293 294 295

    TRACE("%s -> %s\n",debugstr_w(stname),debugstr_w(encname));

    r = IStorage_OpenStream(db->storage, encname, NULL, 
            STGM_READ | STGM_SHARE_EXCLUSIVE, 0, stm);
    if( FAILED( r ) )
    {
296 297 298 299 300 301 302 303 304 305
        MSITRANSFORM *transform;

        LIST_FOR_EACH_ENTRY( transform, &db->transforms, MSITRANSFORM, entry )
        {
            TRACE("looking for %s in transform storage\n", debugstr_w(stname) );
            r = IStorage_OpenStream( transform->stg, encname, NULL, 
                    STGM_READ | STGM_SHARE_EXCLUSIVE, 0, stm );
            if (SUCCEEDED(r))
                break;
        }
306 307
    }

308 309 310
    msi_free( encname );

    return SUCCEEDED(r) ? ERROR_SUCCESS : ERROR_FUNCTION_FAILED;
311 312
}

313
UINT read_raw_stream_data( MSIDATABASE *db, LPCWSTR stname,
314 315 316 317 318 319 320 321 322
                              USHORT **pdata, UINT *psz )
{
    HRESULT r;
    UINT ret = ERROR_FUNCTION_FAILED;
    VOID *data;
    ULONG sz, count;
    IStream *stm = NULL;
    STATSTG stat;

323
    r = db_get_raw_stream( db, stname, &stm );
324
    if( r != ERROR_SUCCESS)
325
        return ret;
326 327 328
    r = IStream_Stat(stm, &stat, STATFLAG_NONAME );
    if( FAILED( r ) )
    {
329
        WARN("open stream failed r = %08lx!\n",r);
330 331 332 333 334
        goto end;
    }

    if( stat.cbSize.QuadPart >> 32 )
    {
335
        WARN("Too big!\n");
336 337 338 339
        goto end;
    }
        
    sz = stat.cbSize.QuadPart;
340
    data = msi_alloc( sz );
341 342
    if( !data )
    {
343
        WARN("couldn't allocate memory r=%08lx!\n",r);
344 345 346 347 348 349 350
        ret = ERROR_NOT_ENOUGH_MEMORY;
        goto end;
    }
        
    r = IStream_Read(stm, data, sz, &count );
    if( FAILED( r ) || ( count != sz ) )
    {
351
        msi_free( data );
352
        WARN("read stream failed r = %08lx!\n",r);
353 354 355 356 357 358 359 360 361 362 363 364 365
        goto end;
    }

    *pdata = data;
    *psz = sz;
    ret = ERROR_SUCCESS;

end:
    IStream_Release( stm );

    return ret;
}

366 367 368 369 370 371 372 373 374
static UINT write_stream_data( IStorage *stg, LPCWSTR stname,
                               LPVOID data, UINT sz )
{
    HRESULT r;
    UINT ret = ERROR_FUNCTION_FAILED;
    ULONG count;
    IStream *stm = NULL;
    ULARGE_INTEGER size;
    LARGE_INTEGER pos;
375
    LPWSTR encname;
376

377
    encname = encode_streamname(TRUE, stname );
378
    r = IStorage_OpenStream( stg, encname, NULL, 
379
            STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, &stm);
380 381 382 383 384
    if( FAILED(r) )
    {
        r = IStorage_CreateStream( stg, encname,
                STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, 0, &stm);
    }
385
    msi_free( encname );
386 387
    if( FAILED( r ) )
    {
388
        WARN("open stream failed r = %08lx\n",r);
389 390 391 392 393
        return ret;
    }

    size.QuadPart = sz;
    r = IStream_SetSize( stm, size );
394
    if( FAILED( r ) )
395
    {
396
        WARN("Failed to SetSize\n");
397 398 399 400 401
        goto end;
    }

    pos.QuadPart = 0;
    r = IStream_Seek( stm, pos, STREAM_SEEK_SET, NULL );
402
    if( FAILED( r ) )
403
    {
404
        WARN("Failed to Seek\n");
405 406 407 408 409 410
        goto end;
    }

    r = IStream_Write(stm, data, sz, &count );
    if( FAILED( r ) || ( count != sz ) )
    {
411
        WARN("Failed to Write\n");
412 413 414 415 416 417 418 419 420 421 422
        goto end;
    }

    ret = ERROR_SUCCESS;

end:
    IStream_Release( stm );

    return ret;
}

423 424 425 426
static void free_table( MSITABLE *table )
{
    int i;
    for( i=0; i<table->row_count; i++ )
427 428 429
        msi_free( table->data[i] );
    msi_free( table->data );
    msi_free( table );
430 431
}

432 433 434 435 436 437 438 439
static UINT msi_table_get_row_size( const MSICOLUMNINFO *cols, UINT count )
{
    const MSICOLUMNINFO *last_col = &cols[count-1];
    if (!count)
        return 0;
    return last_col->offset + bytes_per_column( last_col );
}

440 441 442
/* add this table to the list of cached tables in the database */
static MSITABLE *read_table_from_storage( IStorage *stg, LPCWSTR name,
                                    const MSICOLUMNINFO *cols, UINT num_cols )
443 444
{
    MSITABLE *t;
445
    USHORT *rawdata = NULL;
446
    UINT rawsize = 0, i, j, row_size = 0;
447

448
    TRACE("%s\n",debugstr_w(name));
449

450
    /* nonexistent tables should be interpreted as empty tables */
451
    t = msi_alloc( sizeof (MSITABLE) + lstrlenW(name)*sizeof (WCHAR) );
452
    if( !t )
Mike McCormack's avatar
Mike McCormack committed
453
        return t;
454

455
    row_size = msi_table_get_row_size( cols, num_cols );
456

457
    t->row_count = 0;
458 459 460 461
    t->data = NULL;
    lstrcpyW( t->name, name );

    /* if we can't read the table, just assume that it's empty */
462
    read_stream_data( stg, name, &rawdata, &rawsize );
463
    if( !rawdata )
Mike McCormack's avatar
Mike McCormack committed
464
        return t;
465 466 467 468 469

    TRACE("Read %d bytes\n", rawsize );

    if( rawsize % row_size )
    {
470
        WARN("Table size is invalid %d/%d\n", rawsize, row_size );
Mike McCormack's avatar
Mike McCormack committed
471
        goto err;
472 473 474
    }

    t->row_count = rawsize / row_size;
475
    t->data = msi_alloc_zero( t->row_count * sizeof (USHORT*) );
476
    if( !t->data )
477
        goto err;
478 479 480 481 482

    /* transpose all the data */
    TRACE("Transposing data from %d columns\n", t->row_count );
    for( i=0; i<t->row_count; i++ )
    {
483
        t->data[i] = msi_alloc( row_size );
484
        if( !t->data[i] )
485
            goto err;
Mike McCormack's avatar
Mike McCormack committed
486

487 488 489 490 491 492 493 494 495 496 497
        for( j=0; j<num_cols; j++ )
        {
            UINT ofs = cols[j].offset/2;
            UINT n = bytes_per_column( &cols[j] );

            switch( n )
            {
            case 2:
                t->data[i][ofs] = rawdata[ofs*t->row_count + i ];
                break;
            case 4:
498 499
                t->data[i][ofs] = rawdata[ofs*t->row_count + i*2 ];
                t->data[i][ofs+1] = rawdata[ofs*t->row_count + i*2 + 1];
500 501 502
                break;
            default:
                ERR("oops - unknown column width %d\n", n);
503
                goto err;
504 505 506 507
            }
        }
    }

508
    msi_free( rawdata );
Mike McCormack's avatar
Mike McCormack committed
509
    return t;
510
err:
511
    msi_free( rawdata );
512
    free_table( t );
Mike McCormack's avatar
Mike McCormack committed
513
    return NULL;
514 515 516 517
}

void free_cached_tables( MSIDATABASE *db )
{
518
    while( !list_empty( &db->tables ) )
519
    {
520
        MSITABLE *t = LIST_ENTRY( list_head( &db->tables ), MSITABLE, entry );
521

522
        list_remove( &t->entry );
Mike McCormack's avatar
Mike McCormack committed
523
        free_table( t );
524 525 526
    }
}

527
static MSITABLE *find_cached_table( MSIDATABASE *db, LPCWSTR name )
528 529 530
{
    MSITABLE *t;

531
    LIST_FOR_EACH_ENTRY( t, &db->tables, MSITABLE, entry )
532
        if( !lstrcmpW( name, t->name ) )
Mike McCormack's avatar
Mike McCormack committed
533
            return t;
534

Mike McCormack's avatar
Mike McCormack committed
535
    return NULL;
536 537
}

538 539
static UINT table_get_column_info( MSIDATABASE *db, LPCWSTR name, MSICOLUMNINFO **pcols, UINT *pcount )
{
540
    UINT r, column_count = 0;
541 542 543 544 545 546 547 548 549 550 551 552 553 554
    MSICOLUMNINFO *columns;

    /* get the number of columns in this table */
    column_count = 0;
    r = get_tablecolumns( db, name, NULL, &column_count );
    if( r != ERROR_SUCCESS )
        return r;

    /* if there's no columns, there's no table */
    if( column_count == 0 )
        return ERROR_INVALID_PARAMETER;

    TRACE("Table %s found\n", debugstr_w(name) );

555
    columns = msi_alloc( column_count*sizeof (MSICOLUMNINFO) );
556 557 558 559 560 561
    if( !columns )
        return ERROR_FUNCTION_FAILED;

    r = get_tablecolumns( db, name, columns, &column_count );
    if( r != ERROR_SUCCESS )
    {
562
        msi_free( columns );
563 564 565 566 567 568 569 570 571
        return ERROR_FUNCTION_FAILED;
    }

    *pcols = columns;
    *pcount = column_count;

    return r;
}

572 573
static MSITABLE *get_table( MSIDATABASE *db, LPCWSTR name,
                            const MSICOLUMNINFO *cols, UINT num_cols )
574
{
Mike McCormack's avatar
Mike McCormack committed
575
    MSITABLE *table;
576 577

    /* first, see if the table is cached */
Mike McCormack's avatar
Mike McCormack committed
578 579 580
    table = find_cached_table( db, name );
    if( table )
        return table;
581

582
    table = read_table_from_storage( db->storage, name, cols, num_cols );
Mike McCormack's avatar
Mike McCormack committed
583 584
    if( table )
        list_add_head( &db->tables, &table->entry );
585

Mike McCormack's avatar
Mike McCormack committed
586
    return table;
587 588
}

589
static UINT save_table( MSIDATABASE *db, MSITABLE *t )
590
{
591 592
    USHORT *rawdata = NULL, *p;
    UINT rawsize, r, i, j, row_size, num_cols = 0;
593
    MSICOLUMNINFO *cols = NULL;
594 595 596 597 598 599

    TRACE("Saving %s\n", debugstr_w( t->name ) );

    r = table_get_column_info( db, t->name, &cols, &num_cols );
    if( r != ERROR_SUCCESS )
        return r;
600
    
601
    row_size = msi_table_get_row_size( cols, num_cols );
602 603

    rawsize = t->row_count * row_size;
604
    rawdata = msi_alloc_zero( rawsize );
605
    if( !rawdata )
606 607 608 609
    {
        r = ERROR_NOT_ENOUGH_MEMORY;
        goto err;
    }
610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626

    p = rawdata;
    for( i=0; i<num_cols; i++ )
    {
        for( j=0; j<t->row_count; j++ )
        {
            UINT offset = cols[i].offset;

            *p++ = t->data[j][offset/2];
            if( 4 == bytes_per_column( &cols[i] ) )
                *p++ = t->data[j][offset/2+1];
        }
    }

    TRACE("writing %d bytes\n", rawsize);
    r = write_stream_data( db->storage, t->name, rawdata, rawsize );

627 628 629
err:
    msi_free_colinfo( cols, num_cols );
    msi_free( cols );
630
    msi_free( rawdata );
631 632 633 634 635 636 637

    return r;
}

HRESULT init_string_table( IStorage *stg )
{
    HRESULT r;
638
    static const WCHAR szStringData[] = {
639
        '_','S','t','r','i','n','g','D','a','t','a',0 };
640
    static const WCHAR szStringPool[] = {
641 642 643 644
        '_','S','t','r','i','n','g','P','o','o','l',0 };
    USHORT zero[2] = { 0, 0 };
    ULONG count = 0;
    IStream *stm = NULL;
645
    LPWSTR encname;
646

647
    encname = encode_streamname(TRUE, szStringPool );
648

649
    /* create the StringPool stream... add the zero string to it*/
650 651
    r = IStorage_CreateStream( stg, encname,
            STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, 0, &stm);
652
    msi_free( encname );
653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
    if( r ) 
    {
        TRACE("Failed\n");
        return r;
    }

    r = IStream_Write(stm, zero, sizeof zero, &count );
    IStream_Release( stm );

    if( FAILED( r ) || ( count != sizeof zero ) )
    {
        TRACE("Failed\n");
        return E_FAIL;
    }

668
    /* create the StringData stream... make it zero length */
669
    encname = encode_streamname(TRUE, szStringData );
670 671
    r = IStorage_CreateStream( stg, encname,
            STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, 0, &stm);
672
    msi_free( encname );
673 674 675 676 677 678 679 680
    if( r ) 
    {
        TRACE("Failed\n");
        return E_FAIL;
    }
    IStream_Release( stm );

    return r;
681 682
}

683
string_table *load_string_table( IStorage *stg )
684
{
685
    string_table *st = NULL;
686 687
    CHAR *data = NULL;
    USHORT *pool = NULL;
688
    UINT r, datasize = 0, poolsize = 0, codepage;
689
    DWORD i, count, offset, len, n;
690
    static const WCHAR szStringData[] = {
691
        '_','S','t','r','i','n','g','D','a','t','a',0 };
692
    static const WCHAR szStringPool[] = {
693 694
        '_','S','t','r','i','n','g','P','o','o','l',0 };

695
    r = read_stream_data( stg, szStringPool, &pool, &poolsize );
696 697
    if( r != ERROR_SUCCESS)
        goto end;
698
    r = read_stream_data( stg, szStringData, (USHORT**)&data, &datasize );
699 700 701
    if( r != ERROR_SUCCESS)
        goto end;

702
    count = poolsize/4;
Mike McCormack's avatar
Mike McCormack committed
703 704 705 706
    if( poolsize > 4 )
        codepage = pool[0] | ( pool[1] << 16 );
    else
        codepage = CP_ACP;
707
    st = msi_init_stringtable( count, codepage );
708 709

    offset = 0;
710
    n = 1;
711
    for( i=1; i<count; i++ )
712
    {
713
        len = pool[i*2];
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731

        /*
         * If a string is over 64k, the previous string entry is made null
         * and its the high word of the length is inserted in the null string's
         * reference count field.
         */
        if( pool[i*2-2] == 0 )
            len += pool[i*2-1] * 0x10000;

        if( (offset + len) > datasize )
        {
            ERR("string table corrupt?\n");
            break;
        }

        /* don't add the high word of a string's length as a string */
        if ( len || !pool[i*2+1] )
        {
732
            r = msi_addstring( st, n, data+offset, len, pool[i*2+1] );
733 734 735 736 737
            if( r != n )
                ERR("Failed to add string %ld\n", n );
            n++;
        }

738 739
        offset += len;
    }
740

741 742 743
    if ( datasize != offset )
        ERR("string table load failed! (%08x != %08lx)\n", datasize, offset );

744
    TRACE("Loaded %ld strings\n", count);
745 746

end:
747 748
    msi_free( pool );
    msi_free( data );
749

750
    return st;
751 752
}

753
static UINT save_string_table( MSIDATABASE *db )
754
{
Mike McCormack's avatar
Mike McCormack committed
755
    UINT i, count, datasize, poolsize, sz, used, r, codepage;
756
    UINT ret = ERROR_FUNCTION_FAILED;
757
    static const WCHAR szStringData[] = {
758
        '_','S','t','r','i','n','g','D','a','t','a',0 };
759
    static const WCHAR szStringPool[] = {
760 761 762 763
        '_','S','t','r','i','n','g','P','o','o','l',0 };
    CHAR *data = NULL;
    USHORT *pool = NULL;

764 765
    TRACE("\n");

766
    /* construct the new table in memory first */
Mike McCormack's avatar
Mike McCormack committed
767
    datasize = msi_string_totalsize( db->strings, &count );
768
    poolsize = (count + 1)*2*sizeof(USHORT);
769

770
    pool = msi_alloc( poolsize );
771
    if( ! pool )
772
    {
773
        WARN("Failed to alloc pool %d bytes\n", poolsize );
774
        goto err;
775
    }
776
    data = msi_alloc( datasize );
777
    if( ! data )
778
    {
779
        WARN("Failed to alloc data %d bytes\n", poolsize );
780
        goto err;
781
    }
782

783
    used = 0;
Mike McCormack's avatar
Mike McCormack committed
784 785 786
    codepage = msi_string_get_codepage( db->strings );
    pool[0]=codepage&0xffff;
    pool[1]=(codepage>>16);
787
    for( i=1; i<count; i++ )
788
    {
789 790
        sz = datasize - used;
        r = msi_id2stringA( db->strings, i, data+used, &sz );
791
        if( r != ERROR_SUCCESS )
792
        {
793
            ERR("failed to fetch string\n");
794 795
            sz = 0;
        }
Mike McCormack's avatar
Mike McCormack committed
796
        if( sz && (sz < (datasize - used ) ) )
797
            sz--;
798
        TRACE("adding %u bytes %s\n", sz, debugstr_a(data+used) );
799 800
        pool[ i*2 ] = sz;
        pool[ i*2 + 1 ] = msi_id_refcount( db->strings, i );
801 802
        used += sz;
        if( used > datasize  )
803
        {
804
            ERR("oops overran %d >= %d\n", used, datasize);
805 806 807 808
            goto err;
        }
    }

809
    if( used != datasize )
810
    {
811
        ERR("oops used %d != datasize %d\n", used, datasize);
812 813 814 815 816
        goto err;
    }

    /* write the streams */
    r = write_stream_data( db->storage, szStringData, data, datasize );
817
    TRACE("Wrote StringData r=%08x\n", r);
818 819 820
    if( r )
        goto err;
    r = write_stream_data( db->storage, szStringPool, pool, poolsize );
821
    TRACE("Wrote StringPool r=%08x\n", r);
822 823 824 825 826 827
    if( r )
        goto err;

    ret = ERROR_SUCCESS;

err:
828 829
    msi_free( data );
    msi_free( pool );
830 831 832 833 834

    return ret;
}

/* information for default tables */
835 836 837 838 839 840 841
static const WCHAR szTables[]  = { '_','T','a','b','l','e','s',0 };
static const WCHAR szTable[]  = { 'T','a','b','l','e',0 };
static const WCHAR szName[]    = { 'N','a','m','e',0 };
static const WCHAR szColumns[] = { '_','C','o','l','u','m','n','s',0 };
static const WCHAR szColumn[]  = { 'C','o','l','u','m','n',0 };
static const WCHAR szNumber[]  = { 'N','u','m','b','e','r',0 };
static const WCHAR szType[]    = { 'T','y','p','e',0 };
842

843
static const MSICOLUMNINFO _Columns_cols[4] = {
844
    { szColumns, 1, szTable,  MSITYPE_VALID | MSITYPE_STRING | 64, 0 },
845
    { szColumns, 2, szNumber, MSITYPE_VALID | 2,                   2 },
846
    { szColumns, 3, szName,   MSITYPE_VALID | MSITYPE_STRING | 64, 4 },
847 848 849
    { szColumns, 4, szType,   MSITYPE_VALID | 2,                   6 },
};
static const MSICOLUMNINFO _Tables_cols[1] = {
850
    { szTables,  1, szName,   MSITYPE_VALID | MSITYPE_STRING | 64, 0 },
851 852
};

853
static UINT get_defaulttablecolumns( LPCWSTR name, MSICOLUMNINFO *colinfo, UINT *sz)
854
{
855 856 857 858
    const MSICOLUMNINFO *p;
    DWORD i, n;

    TRACE("%s\n", debugstr_w(name));
859

860
    if (!lstrcmpW( name, szTables ))
861
    {
862 863 864 865 866 867 868 869 870 871 872 873 874 875 876
        p = _Tables_cols;
        n = 1;
    }
    else if (!lstrcmpW( name, szColumns ))
    {
        p = _Columns_cols;
        n = 4;
    }
    else
        return ERROR_FUNCTION_FAILED;

    /* duplicate the string data so we can free it in msi_free_colinfo */
    for (i=0; i<n; i++)
    {
        if (colinfo && (i < *sz) )
877
        {
878 879 880
            memcpy( &colinfo[i], &p[i], sizeof(MSICOLUMNINFO) );
            colinfo[i].tablename = strdupW( p[i].tablename );
            colinfo[i].colname = strdupW( p[i].colname );
881
        }
882
        if( colinfo && (i >= *sz) )
883 884 885 886 887 888
            break;
    }
    *sz = n;
    return ERROR_SUCCESS;
}

889 890 891 892 893 894 895 896
static void msi_free_colinfo( MSICOLUMNINFO *colinfo, UINT count )
{
    UINT i;

    for( i=0; i<count; i++ )
    {
        msi_free( (LPWSTR) colinfo[i].tablename );
        msi_free( (LPWSTR) colinfo[i].colname );
897
        msi_free( colinfo[i].hash_table );
898 899 900
    }
}

901 902 903 904 905
LPWSTR MSI_makestring( MSIDATABASE *db, UINT stringid)
{
    UINT sz=0, r;
    LPWSTR str;

906
    r = msi_id2stringW( db->strings, stringid, NULL, &sz );
907 908
    if( r != ERROR_SUCCESS )
        return NULL;
Mike McCormack's avatar
Mike McCormack committed
909
    str = msi_alloc( sz*sizeof (WCHAR) );
910 911
    if( !str )
        return str;
912
    r = msi_id2stringW( db->strings, stringid, str, &sz );
913 914
    if( r == ERROR_SUCCESS )
        return str;
Mike McCormack's avatar
Mike McCormack committed
915
    msi_free( str );
916 917 918
    return NULL;
}

919
static UINT get_tablecolumns( MSIDATABASE *db, 
920 921 922 923 924 925 926 927 928 929
       LPCWSTR szTableName, MSICOLUMNINFO *colinfo, UINT *sz)
{
    UINT r, i, n=0, table_id, count, maxcount = *sz;
    MSITABLE *table = NULL;

    /* first check if there is a default table with that name */
    r = get_defaulttablecolumns( szTableName, colinfo, sz );
    if( ( r == ERROR_SUCCESS ) && *sz )
        return r;

930
    table = get_table( db, szColumns, _Columns_cols, 4 );
Mike McCormack's avatar
Mike McCormack committed
931
    if( !table )
932
    {
933
        ERR("couldn't load _Columns table\n");
Mike McCormack's avatar
Mike McCormack committed
934
        return ERROR_FUNCTION_FAILED;
935 936 937
    }

    /* convert table and column names to IDs from the string table */
938
    r = msi_string2idW( db->strings, szTableName, &table_id );
939 940
    if( r != ERROR_SUCCESS )
    {
941
        WARN("Couldn't find id for %s\n", debugstr_w(szTableName));
942 943 944
        return r;
    }

945
    TRACE("Table id is %d, row count is %d\n", table_id, table->row_count);
946

947
    count = table->row_count;
948 949
    for( i=0; i<count; i++ )
    {
950
        if( table->data[ i ][ 0 ] != table_id )
951 952 953
            continue;
        if( colinfo )
        {
954
            UINT id = table->data[ i ] [ 2 ];
955
            colinfo[n].tablename = MSI_makestring( db, table_id );
956
            colinfo[n].number = table->data[ i ][ 1 ] - (1<<15);
957
            colinfo[n].colname = MSI_makestring( db, id );
958
            colinfo[n].type = table->data[ i ] [ 3 ] ^ 0x8000;
959
            colinfo[n].hash_table = NULL;
960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996
            /* this assumes that columns are in order in the table */
            if( n )
                colinfo[n].offset = colinfo[n-1].offset
                                  + bytes_per_column( &colinfo[n-1] );
            else
                colinfo[n].offset = 0;
            TRACE("table %s column %d is [%s] (%d) with type %08x "
                  "offset %d at row %d\n", debugstr_w(szTableName),
                   colinfo[n].number, debugstr_w(colinfo[n].colname),
                   id, colinfo[n].type, colinfo[n].offset, i);
            if( n != (colinfo[n].number-1) )
            {
                ERR("oops. data in the _Columns table isn't in the right "
                    "order for table %s\n", debugstr_w(szTableName));
                return ERROR_FUNCTION_FAILED;
            }
        }
        n++;
        if( colinfo && ( n >= maxcount ) )
            break;
    }
    *sz = n;

    return ERROR_SUCCESS;
}

/* try to find the table name in the _Tables table */
BOOL TABLE_Exists( MSIDATABASE *db, LPWSTR name )
{
    UINT r, table_id = 0, i, count;
    MSITABLE *table = NULL;

    if( !lstrcmpW( name, szTables ) )
        return TRUE;
    if( !lstrcmpW( name, szColumns ) )
        return TRUE;

997
    r = msi_string2idW( db->strings, name, &table_id );
998 999
    if( r != ERROR_SUCCESS )
    {
1000
        TRACE("Couldn't find id for %s\n", debugstr_w(name));
1001 1002 1003
        return FALSE;
    }

1004
    table = get_table( db, szTables, _Tables_cols, 1 );
Mike McCormack's avatar
Mike McCormack committed
1005
    if( !table )
1006
    {
1007
        TRACE("table %s not available\n", debugstr_w(szTables));
1008 1009 1010
        return FALSE;
    }

1011 1012
    /* count = table->size/2; */
    count = table->row_count;
1013
    for( i=0; i<count; i++ )
1014
        if( table->data[ i ][ 0 ] == table_id )
1015 1016 1017 1018 1019
            break;

    if (i!=count)
        return TRUE;

1020
    TRACE("Searched %d tables, but %d was not found\n", count, table_id );
1021

1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
    return FALSE;
}

/* below is the query interface to a table */

typedef struct tagMSITABLEVIEW
{
    MSIVIEW        view;
    MSIDATABASE   *db;
    MSITABLE      *table;
    MSICOLUMNINFO *columns;
    UINT           num_cols;
    UINT           row_size;
    WCHAR          name[1];
} MSITABLEVIEW;

static UINT TABLE_fetch_int( struct tagMSIVIEW *view, UINT row, UINT col, UINT *val )
{
    MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
    UINT offset, num_rows, n;

    if( !tv->table )
        return ERROR_INVALID_PARAMETER;

    if( (col==0) || (col>tv->num_cols) )
        return ERROR_INVALID_PARAMETER;

    /* how many rows are there ? */
1050
    num_rows = tv->table->row_count;
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
    if( row >= num_rows )
        return ERROR_NO_MORE_ITEMS;

    if( tv->columns[col-1].offset >= tv->row_size )
    {
        ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
        ERR("%p %p\n", tv, tv->columns );
        return ERROR_FUNCTION_FAILED;
    }

    offset = row + (tv->columns[col-1].offset/2) * num_rows;
    n = bytes_per_column( &tv->columns[col-1] );
    switch( n )
    {
    case 4:
1066
        offset = tv->columns[col-1].offset/2;
1067 1068
        *val = tv->table->data[row][offset] + 
               (tv->table->data[row][offset + 1] << 16);
1069 1070
        break;
    case 2:
1071 1072
        offset = tv->columns[col-1].offset/2;
        *val = tv->table->data[row][offset];
1073 1074 1075 1076 1077 1078
        break;
    default:
        ERR("oops! what is %d bytes per column?\n", n );
        return ERROR_FUNCTION_FAILED;
    }

1079
    /* TRACE("Data [%d][%d] = %d\n", row, col, *val ); */
1080 1081 1082 1083

    return ERROR_SUCCESS;
}

1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
/*
 * We need a special case for streams, as we need to reference column with
 * the name of the stream in the same table, and the table name
 * which may not be available at higher levels of the query
 */
static UINT TABLE_fetch_stream( struct tagMSIVIEW *view, UINT row, UINT col, IStream **stm )
{
    MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
    UINT ival = 0, refcol = 0, r;
    LPWSTR sval;
1094 1095 1096
    LPWSTR full_name;
    DWORD len;
    static const WCHAR szDot[] = { '.', 0 };
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120

    if( !view->ops->fetch_int )
        return ERROR_INVALID_PARAMETER;

    /*
     * The column marked with the type stream data seems to have a single number
     * which references the column containing the name of the stream data
     *
     * Fetch the column to reference first.
     */
    r = view->ops->fetch_int( view, row, col, &ival );
    if( r != ERROR_SUCCESS )
        return r;

    /* now get the column with the name of the stream */
    r = view->ops->fetch_int( view, row, ival, &refcol );
    if( r != ERROR_SUCCESS )
        return r;

    /* lookup the string value from the string table */
    sval = MSI_makestring( tv->db, refcol );
    if( !sval )
        return ERROR_INVALID_PARAMETER;

1121
    len = lstrlenW( tv->name ) + 2 + lstrlenW( sval );
1122
    full_name = msi_alloc( len*sizeof(WCHAR) );
1123 1124 1125
    lstrcpyW( full_name, tv->name );
    lstrcatW( full_name, szDot );
    lstrcatW( full_name, sval );
1126 1127 1128 1129

    r = db_get_raw_stream( tv->db, full_name, stm );
    if( r )
        ERR("fetching stream %s, error = %d\n",debugstr_w(full_name), r);
1130 1131
    msi_free( full_name );
    msi_free( sval );
1132 1133 1134 1135

    return r;
}

1136 1137 1138
static UINT TABLE_set_int( struct tagMSIVIEW *view, UINT row, UINT col, UINT val )
{
    MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1139
    UINT offset, n;
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172

    if( !tv->table )
        return ERROR_INVALID_PARAMETER;

    if( (col==0) || (col>tv->num_cols) )
        return ERROR_INVALID_PARAMETER;

    if( tv->columns[col-1].offset >= tv->row_size )
    {
        ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
        ERR("%p %p\n", tv, tv->columns );
        return ERROR_FUNCTION_FAILED;
    }

    n = bytes_per_column( &tv->columns[col-1] );
    switch( n )
    {
    case 4:
        offset = tv->columns[col-1].offset/2;
        tv->table->data[row][offset]     = val & 0xffff;
        tv->table->data[row][offset + 1] = (val>>16)&0xffff;
        break;
    case 2:
        offset = tv->columns[col-1].offset/2;
        tv->table->data[row][offset] = val;
        break;
    default:
        ERR("oops! what is %d bytes per column?\n", n );
        return ERROR_FUNCTION_FAILED;
    }
    return ERROR_SUCCESS;
}

1173
static UINT table_create_new_row( struct tagMSIVIEW *view, UINT *num )
1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
{
    MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
    USHORT **p, *row;
    UINT sz;

    TRACE("%p\n", view);

    if( !tv->table )
        return ERROR_INVALID_PARAMETER;

1184
    row = msi_alloc_zero( tv->row_size );
1185 1186 1187 1188 1189
    if( !row )
        return ERROR_NOT_ENOUGH_MEMORY;

    sz = (tv->table->row_count + 1) * sizeof (UINT*);
    if( tv->table->data )
1190
        p = msi_realloc( tv->table->data, sz );
1191
    else
1192
        p = msi_alloc( sz );
1193
    if( !p )
1194
    {
1195
        msi_free( row );
1196
        return ERROR_NOT_ENOUGH_MEMORY;
1197
    }
1198 1199 1200 1201 1202 1203 1204 1205 1206

    tv->table->data = p;
    tv->table->data[tv->table->row_count] = row;
    *num = tv->table->row_count;
    tv->table->row_count++;

    return ERROR_SUCCESS;
}

1207
static UINT TABLE_execute( struct tagMSIVIEW *view, MSIRECORD *record )
1208 1209 1210
{
    MSITABLEVIEW *tv = (MSITABLEVIEW*)view;

1211
    TRACE("%p %p\n", tv, record);
1212

1213 1214
    TRACE("There are %d columns\n", tv->num_cols );
    tv->table = get_table( tv->db, tv->name, tv->columns, tv->num_cols );
Mike McCormack's avatar
Mike McCormack committed
1215 1216
    if( !tv->table )
        return ERROR_FUNCTION_FAILED;
1217

1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
    return ERROR_SUCCESS;
}

static UINT TABLE_close( struct tagMSIVIEW *view )
{
    MSITABLEVIEW *tv = (MSITABLEVIEW*)view;

    TRACE("%p\n", view );

    if( !tv->table )
        return ERROR_FUNCTION_FAILED;

    tv->table = NULL;
    
    return ERROR_SUCCESS;
}

static UINT TABLE_get_dimensions( struct tagMSIVIEW *view, UINT *rows, UINT *cols)
{
    MSITABLEVIEW *tv = (MSITABLEVIEW*)view;

    TRACE("%p %p %p\n", view, rows, cols );

    if( cols )
        *cols = tv->num_cols;
    if( rows )
    {
        if( !tv->table )
            return ERROR_INVALID_PARAMETER;
1247
        *rows = tv->table->row_count;
1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274
    }

    return ERROR_SUCCESS;
}

static UINT TABLE_get_column_info( struct tagMSIVIEW *view,
                UINT n, LPWSTR *name, UINT *type )
{
    MSITABLEVIEW *tv = (MSITABLEVIEW*)view;

    TRACE("%p %d %p %p\n", tv, n, name, type );

    if( ( n == 0 ) || ( n > tv->num_cols ) )
        return ERROR_INVALID_PARAMETER;

    if( name )
    {
        *name = strdupW( tv->columns[n-1].colname );
        if( !*name )
            return ERROR_FUNCTION_FAILED;
    }
    if( type )
        *type = tv->columns[n-1].type;

    return ERROR_SUCCESS;
}

1275
static UINT msi_table_find_row( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *row );
1276 1277 1278

static UINT table_validate_new( MSITABLEVIEW *tv, MSIRECORD *rec )
{
1279
    UINT r, row;
1280

1281 1282 1283 1284
    r = msi_table_find_row( tv, rec, &row );
    if (r != ERROR_SUCCESS)
        return ERROR_SUCCESS;
    return ERROR_INVALID_DATA;
1285 1286
}

1287 1288
static UINT msi_table_modify_row( MSITABLEVIEW *tv, MSIRECORD *rec,
                                  UINT row, UINT mask )
1289
{
1290
    UINT i, val, r = ERROR_SUCCESS;
1291

1292
    TRACE("%p %p %u %08x\n", tv, rec, row, mask );
1293

1294
    for( i = 0; i < tv->num_cols; i++ )
1295
    {
1296 1297 1298
        /* set keys or values specified in the mask */
        if( (~tv->columns[i].type & MSITYPE_KEY) && (~mask & (1<<i)) )
            continue;
1299

1300 1301
        if( (tv->columns[i].type & MSITYPE_STRING) &&
            ! MSITYPE_IS_BINARY(tv->columns[i].type) )
1302
        {
1303
            const WCHAR *str = MSI_RecordGetString( rec, i+1 );
1304 1305 1306 1307
            val = msi_addstringW( tv->db->strings, 0, str, -1, 1 );
        }
        else
        {
1308 1309 1310
            val = MSI_RecordGetInteger( rec, i+1 );
            if ( 2 == bytes_per_column( &tv->columns[i] ) )
                val ^= 0x8000;
1311
        }
1312
        r = TABLE_set_int( &tv->view, row, i+1, val );
1313 1314 1315 1316 1317 1318 1319
        if( r )
            break;
    }

    return r;
}

1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334
static UINT TABLE_insert_row( struct tagMSIVIEW *view, MSIRECORD *rec )
{
    MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
    UINT r, row = -1;

    TRACE("%p %p\n", tv, rec );

    r = table_create_new_row( view, &row );
    TRACE("insert_row returned %08x\n", r);
    if( r != ERROR_SUCCESS )
        return r;

    return msi_table_modify_row( tv, rec, row, ~0 );
}

1335 1336
static UINT TABLE_modify( struct tagMSIVIEW *view, MSIMODIFY eModifyMode,
                MSIRECORD *rec)
1337
{
1338 1339 1340 1341 1342
    MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
    UINT r;

    TRACE("%p %d %p\n", view, eModifyMode, rec );

1343 1344 1345 1346 1347 1348 1349
    if (!tv->table)
    {
        r = TABLE_execute( view, NULL );
        if( r )
            return r;
    }

1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381
    switch (eModifyMode)
    {
    case MSIMODIFY_VALIDATE_NEW:
        r = table_validate_new( tv, rec );
        break;

    case MSIMODIFY_INSERT_TEMPORARY:
        r = table_validate_new( tv, rec );
        if (r != ERROR_SUCCESS)
            break;
        r = TABLE_insert_row( view, rec );
        break;

    case MSIMODIFY_REFRESH:
    case MSIMODIFY_INSERT:
    case MSIMODIFY_UPDATE:
    case MSIMODIFY_ASSIGN:
    case MSIMODIFY_REPLACE:
    case MSIMODIFY_MERGE:
    case MSIMODIFY_DELETE:
    case MSIMODIFY_VALIDATE:
    case MSIMODIFY_VALIDATE_FIELD:
    case MSIMODIFY_VALIDATE_DELETE:
        FIXME("%p %d %p - mode not implemented\n", view, eModifyMode, rec );
        r = ERROR_CALL_NOT_IMPLEMENTED;
        break;

    default:
        r = ERROR_INVALID_DATA;
    }

    return r;
1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393
}

static UINT TABLE_delete( struct tagMSIVIEW *view )
{
    MSITABLEVIEW *tv = (MSITABLEVIEW*)view;

    TRACE("%p\n", view );

    tv->table = NULL;

    if( tv->columns )
    {
1394
        msi_free_colinfo( tv->columns, tv->num_cols );
1395
        msi_free( tv->columns );
1396 1397 1398
    }
    tv->columns = NULL;

1399
    msi_free( tv );
1400 1401 1402 1403

    return ERROR_SUCCESS;
}

1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495
static UINT TABLE_find_matching_rows( struct tagMSIVIEW *view, UINT col,
    UINT val, UINT *row, MSIITERHANDLE *handle )
{
    MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
    const MSICOLUMNHASHENTRY *entry;

    TRACE("%p, %d, %u, %p\n", view, col, val, *handle);

    if( !tv->table )
        return ERROR_INVALID_PARAMETER;

    if( (col==0) || (col > tv->num_cols) )
        return ERROR_INVALID_PARAMETER;

    if( !tv->columns[col-1].hash_table )
    {
        UINT i;
        UINT num_rows = tv->table->row_count;
        MSICOLUMNHASHENTRY **hash_table;
        MSICOLUMNHASHENTRY *new_entry;

        if( tv->columns[col-1].offset >= tv->row_size )
        {
            ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
            ERR("%p %p\n", tv, tv->columns );
            return ERROR_FUNCTION_FAILED;
        }

        /* allocate contiguous memory for the table and its entries so we
         * don't have to do an expensive cleanup */
        hash_table = msi_alloc(MSITABLE_HASH_TABLE_SIZE * sizeof(MSICOLUMNHASHENTRY*) +
            num_rows * sizeof(MSICOLUMNHASHENTRY));
        if (!hash_table)
            return ERROR_OUTOFMEMORY;

        memset(hash_table, 0, MSITABLE_HASH_TABLE_SIZE * sizeof(MSICOLUMNHASHENTRY*));
        tv->columns[col-1].hash_table = hash_table;

        new_entry = (MSICOLUMNHASHENTRY *)(hash_table + MSITABLE_HASH_TABLE_SIZE);

        for (i = 0; i < num_rows; i++, new_entry++)
        {
            UINT row_value, n;
            UINT offset = i + (tv->columns[col-1].offset/2) * num_rows;
            n = bytes_per_column( &tv->columns[col-1] );
            switch( n )
            {
            case 4:
                offset = tv->columns[col-1].offset/2;
                row_value = tv->table->data[i][offset] + 
                    (tv->table->data[i][offset + 1] << 16);
                break;
            case 2:
                offset = tv->columns[col-1].offset/2;
                row_value = tv->table->data[i][offset];
                break;
            default:
                ERR("oops! what is %d bytes per column?\n", n );
                continue;
            }

            new_entry->next = NULL;
            new_entry->value = row_value;
            new_entry->row = i;
            if (hash_table[row_value % MSITABLE_HASH_TABLE_SIZE])
            {
                MSICOLUMNHASHENTRY *prev_entry = hash_table[row_value % MSITABLE_HASH_TABLE_SIZE];
                while (prev_entry->next)
                    prev_entry = prev_entry->next;
                prev_entry->next = new_entry;
            }
            else
                hash_table[row_value % MSITABLE_HASH_TABLE_SIZE] = new_entry;
        }
    }

    if( !*handle )
        entry = tv->columns[col-1].hash_table[val % MSITABLE_HASH_TABLE_SIZE];
    else
        entry = ((const MSICOLUMNHASHENTRY *)*handle)->next;

    while (entry && entry->value != val)
        entry = entry->next;

    *handle = (MSIITERHANDLE)entry;
    if (!entry)
        return ERROR_NO_MORE_ITEMS;

    *row = entry->row;
    return ERROR_SUCCESS;
}

1496 1497 1498 1499

MSIVIEWOPS table_ops =
{
    TABLE_fetch_int,
1500
    TABLE_fetch_stream,
1501 1502
    TABLE_set_int,
    TABLE_insert_row,
1503 1504 1505 1506 1507
    TABLE_execute,
    TABLE_close,
    TABLE_get_dimensions,
    TABLE_get_column_info,
    TABLE_modify,
1508 1509
    TABLE_delete,
    TABLE_find_matching_rows
1510 1511
};

1512
UINT TABLE_CreateView( MSIDATABASE *db, LPCWSTR name, MSIVIEW **view )
1513 1514
{
    MSITABLEVIEW *tv ;
1515
    UINT r, sz, column_count;
1516
    MSICOLUMNINFO *columns;
1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532

    TRACE("%p %s %p\n", db, debugstr_w(name), view );

    /* get the number of columns in this table */
    column_count = 0;
    r = get_tablecolumns( db, name, NULL, &column_count );
    if( r != ERROR_SUCCESS )
        return r;

    /* if there's no columns, there's no table */
    if( column_count == 0 )
        return ERROR_INVALID_PARAMETER;

    TRACE("Table found\n");

    sz = sizeof *tv + lstrlenW(name)*sizeof name[0] ;
1533
    tv = msi_alloc_zero( sz );
1534 1535 1536
    if( !tv )
        return ERROR_FUNCTION_FAILED;
    
1537
    columns = msi_alloc( column_count*sizeof (MSICOLUMNINFO));
1538 1539
    if( !columns )
    {
1540
        msi_free( tv );
1541 1542 1543 1544 1545 1546
        return ERROR_FUNCTION_FAILED;
    }

    r = get_tablecolumns( db, name, columns, &column_count );
    if( r != ERROR_SUCCESS )
    {
1547 1548
        msi_free( columns );
        msi_free( tv );
1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559
        return ERROR_FUNCTION_FAILED;
    }

    TRACE("Table has %d columns\n", column_count);

    /* fill the structure */
    tv->view.ops = &table_ops;
    tv->db = db;
    tv->columns = columns;
    tv->num_cols = column_count;
    tv->table = NULL;
1560
    tv->row_size = msi_table_get_row_size( columns, column_count );
1561

1562
    TRACE("%s one row is %d bytes\n", debugstr_w(name), tv->row_size );
1563 1564 1565 1566 1567 1568

    *view = (MSIVIEW*) tv;
    lstrcpyW( tv->name, name );

    return ERROR_SUCCESS;
}
1569 1570 1571 1572 1573 1574

UINT MSI_CommitTables( MSIDATABASE *db )
{
    UINT r;
    MSITABLE *table = NULL;

1575 1576 1577 1578 1579
    TRACE("%p\n",db);

    r = save_string_table( db );
    if( r != ERROR_SUCCESS )
    {
1580
        WARN("failed to save string table r=%08x\n",r);
1581 1582
        return r;
    }
1583

1584
    LIST_FOR_EACH_ENTRY( table, &db->tables, MSITABLE, entry )
1585 1586 1587
    {
        r = save_table( db, table );
        if( r != ERROR_SUCCESS )
1588
        {
1589
            WARN("failed to save table %s (r=%08x)\n",
1590
                  debugstr_w(table->name), r);
1591
            return r;
1592
        }
1593 1594 1595 1596 1597 1598 1599
    }

    /* force everything to reload next time */
    free_cached_tables( db );

    return ERROR_SUCCESS;
}
1600

1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611
static MSIRECORD *msi_get_transform_record( MSITABLEVIEW *tv, string_table *st, USHORT *rawdata )
{
    UINT i, val, ofs = 0;
    USHORT mask = *rawdata++;
    MSICOLUMNINFO *columns = tv->columns;
    MSIRECORD *rec;

    rec = MSI_CreateRecord( tv->num_cols );
    if( !rec )
        return rec;

1612
    TRACE("row -> ");
1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631
    for( i=0; i<tv->num_cols; i++ )
    {
        UINT n = bytes_per_column( &columns[i] );

        if ( (mask&1) && (i>=(mask>>8)) )
            break;
        /* all keys must be present */
        if ( (~mask&1) && (~columns[i].type & MSITYPE_KEY) && ((1<<i) & ~mask) )
            continue;

        switch( n )
        {
        case 2:
            val = rawdata[ofs];
            if( (columns[i].type & MSITYPE_STRING) &&
                ! MSITYPE_IS_BINARY(tv->columns[i].type) )
            {
                LPCWSTR sval = msi_string_lookup_id( st, val );
                MSI_RecordSetStringW( rec, i+1, sval );
1632
                TRACE("[%s]", debugstr_w(sval));
1633 1634 1635 1636 1637
            }
            else
            {
                val ^= 0x8000;
                MSI_RecordSetInteger( rec, i+1, val );
1638
                TRACE("[0x%04x]", val );
1639 1640 1641 1642 1643 1644
            }
            break;
        case 4:
            val = rawdata[ofs] + (rawdata[ofs + 1]<<16);
            /* val ^= 0x80000000; */
            MSI_RecordSetInteger( rec, i+1, val );
1645
            TRACE("[0x%08x]", val );
1646 1647 1648 1649 1650 1651 1652
            break;
        default:
            ERR("oops - unknown column width %d\n", n);
            break;
        }
        ofs += n/2;
    }
1653
    TRACE("\n");
1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666
    return rec;
}

static void dump_record( MSIRECORD *rec )
{
    UINT i, n;

    n = MSI_RecordGetFieldCount( rec );
    for( i=1; i<=n; i++ )
    {
        LPCWSTR sval = MSI_RecordGetString( rec, i );

        if( MSI_RecordIsNull( rec, i ) )
1667
            TRACE("row -> []\n");
1668
        else if( (sval = MSI_RecordGetString( rec, i )) )
1669
            TRACE("row -> [%s]\n", debugstr_w(sval));
1670
        else
1671
            TRACE("row -> [0x%08x]\n", MSI_RecordGetInteger( rec, i ) );
1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779
    }
}

static void dump_table( string_table *st, USHORT *rawdata, UINT rawsize )
{
    LPCWSTR sval;
    UINT i;

    for( i=0; i<(rawsize/2); i++ )
    {
        sval = msi_string_lookup_id( st, rawdata[i] );
        if( !sval ) sval = (WCHAR[]) {0};
        MESSAGE(" %04x %s\n", rawdata[i], debugstr_w(sval) );
    }
}

static UINT* msi_record_to_row( MSITABLEVIEW *tv, MSIRECORD *rec )
{
    LPCWSTR str;
    UINT i, r, *data;

    data = msi_alloc( tv->num_cols *sizeof (UINT) );
    for( i=0; i<tv->num_cols; i++ )
    {
        data[i] = 0;

        if ( ~tv->columns[i].type & MSITYPE_KEY )
            continue;

        /* turn the transform column value into a row value */
        if ( ( tv->columns[i].type & MSITYPE_STRING ) &&
             ! MSITYPE_IS_BINARY(tv->columns[i].type) )
        {
            str = MSI_RecordGetString( rec, i+1 );
            r = msi_string2idW( tv->db->strings, str, &data[i] );

            /* if there's no matching string in the string table,
               these keys can't match any record, so fail now. */
            if( ERROR_SUCCESS != r )
            {
                msi_free( data );
                return NULL;
            }
        }
        else
            data[i] = MSI_RecordGetInteger( rec, i+1 );
    }
    return data;
}

static UINT msi_row_matches( MSITABLEVIEW *tv, UINT row, UINT *data )
{
    UINT i, r, x, ret = ERROR_FUNCTION_FAILED;

    for( i=0; i<tv->num_cols; i++ )
    {
        if ( ~tv->columns[i].type & MSITYPE_KEY )
            continue;

        /* turn the transform column value into a row value */
        r = TABLE_fetch_int( &tv->view, row, i+1, &x );
        if ( r != ERROR_SUCCESS )
        {
            ERR("TABLE_fetch_int shouldn't fail here\n");
            break;
        }

        /* if this key matches, move to the next column */
        if ( x != data[i] )
        {
            ret = ERROR_FUNCTION_FAILED;
            break;
        }

        ret = ERROR_SUCCESS;
    }

    return ret;
}

static UINT msi_table_find_row( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *row )
{
    UINT i, r = ERROR_FUNCTION_FAILED, *data;

    data = msi_record_to_row( tv, rec );
    if( !data )
        return r;
    for( i=0; i<tv->table->row_count; i++ )
    {
        r = msi_row_matches( tv, i, data );
        if( r == ERROR_SUCCESS )
        {
            *row = i;
            break;
        }
    }
    msi_free( data );
    return r;
}

static UINT msi_delete_row( MSITABLEVIEW *tv, UINT row )
{
    UINT i;
    for( i=1; i<=tv->num_cols; i++ )
        tv->view.ops->set_int( &tv->view, row, i, 0 );
    return ERROR_SUCCESS;
}

1780 1781 1782
static UINT msi_table_load_transform( MSIDATABASE *db, IStorage *stg,
                                      string_table *st, LPCWSTR name )
{
1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860
    UINT rawsize = 0;
    USHORT *rawdata = NULL;
    MSITABLEVIEW *tv = NULL;
    UINT r, n, sz, i, mask;
    MSIRECORD *rec = NULL;

    TRACE("%p %p %p %s\n", db, stg, st, debugstr_w(name) );

    /* create a table view */
    r = TABLE_CreateView( db, name, (MSIVIEW**) &tv );
    if( r != ERROR_SUCCESS )
        goto err;

    r = tv->view.ops->execute( &tv->view, NULL );
    if( r != ERROR_SUCCESS )
        goto err;

    /* read the transform data */
    r = ERROR_FUNCTION_FAILED;
    read_stream_data( stg, name, &rawdata, &rawsize );
    if( !rawdata || (rawsize < 2) )
    {
        ERR("odd sized transform for table %s\n", debugstr_w(name));
        goto err;
    }

    TRACE("name = %s columns = %u row_size = %u raw size = %u\n",
          debugstr_w(name), tv->num_cols, tv->row_size, rawsize );

    /* interpret the data */
    r = ERROR_SUCCESS;
    for( n=0; n < (rawsize/2);  )
    {
        mask = rawdata[n];

        if (mask&1)
        {
            /*
             * if the low bit is set, columns are continuous and
             * the number of columns is specified in the high byte
             */
            sz = 2 + tv->row_size;
        }
        else
        {
            /*
             * If the low bit is not set, rowdata[n] is a bitmask.
             * Excepting for key fields, which are always present,
             *  each bit indicates that a field is present in the transform record.
             *
             * rawdata[n] == 0 is a special case ... only the keys will be present
             * and it means that this row should be deleted.
             */
            sz = 2;
            for( i=0; i<tv->num_cols; i++ )
            {
                if( (tv->columns[i].type & MSITYPE_KEY) || ((1<<i)&mask))
                    sz += bytes_per_column( &tv->columns[i] );
            }
        }

        /* check we didn't run of the end of the table */
        if ( (n+sz) > rawsize )
        {
            ERR("borked.\n");
            dump_table( st, rawdata, rawsize );
            break;
        }

        rec = msi_get_transform_record( tv, st, &rawdata[n] );
        if (rec)
        {
            UINT row = 0;

            r = msi_table_find_row( tv, rec, &row );

            if( rawdata[n] & 1)
            {
1861
                TRACE("insert [%d]: ", row);
1862 1863 1864 1865
                TABLE_insert_row( &tv->view, rec );
            }
            else if( mask & 0xff )
            {
1866
                TRACE("modify [%d]: ", row);
1867 1868 1869 1870
                msi_table_modify_row( tv, rec, row, mask );
            }
            else
            {
1871
                TRACE("delete [%d]: ", row);
1872 1873
                msi_delete_row( tv, row );
            }
1874
            if( TRACE_ON(msidb) ) dump_record( rec );
1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887
            msiobj_release( &rec->hdr );
        }

        n += sz/2;
        
    }

err:
    /* no need to free the table, it's associated with the database */
    msi_free( rawdata );
    if( tv )
        tv->view.ops->delete( &tv->view );

1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905
    return ERROR_SUCCESS;
}

/*
 * msi_table_apply_transform
 *
 * Enumerate the table transforms in a transform storage and apply each one.
 */
UINT msi_table_apply_transform( MSIDATABASE *db, IStorage *stg )
{
    IEnumSTATSTG *stgenum = NULL;
    HRESULT r;
    STATSTG stat;
    ULONG n, count;
    WCHAR name[0x40];
    string_table *strings;
    UINT ret = ERROR_FUNCTION_FAILED;

1906 1907
    TRACE("%p %p\n", db, stg );

1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926
    strings = load_string_table( stg );
    if( !strings )
        goto end;

    r = IStorage_EnumElements( stg, 0, NULL, 0, &stgenum );
    if( FAILED( r ) )
        goto end;

    n = 0;
    ret = ERROR_SUCCESS;

    while( r == ERROR_SUCCESS )
    {
        count = 0;
        r = IEnumSTATSTG_Next( stgenum, 1, &stat, &count );
        if( FAILED( r ) || !count )
            break;
        decode_streamname( stat.pwcsName, name );
        if( ( name[0] == 0x4840 ) && ( name[1] != '_' ) )
1927
            ret = msi_table_load_transform( db, stg, strings, name+1 );
1928
        else
1929
            TRACE("transform contains stream %s\n", debugstr_w(name));
1930 1931 1932
        n++;
    }

1933 1934 1935 1936 1937 1938 1939 1940 1941 1942
    if ( ret == ERROR_SUCCESS )
    {
        MSITRANSFORM *t;

        t = msi_alloc( sizeof *t );
        t->stg = stg;
        IStorage_AddRef( stg );
        list_add_tail( &db->transforms, &t->entry );
    }

1943 1944 1945 1946 1947 1948 1949 1950
end:
    if ( stgenum )
        IEnumSTATSTG_Release( stgenum );
    if ( strings )
        msi_destroy_stringtable( strings );

    return ret;
}
1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962

void msi_free_transforms( MSIDATABASE *db )
{
    while( !list_empty( &db->transforms ) )
    {
        MSITRANSFORM *t = LIST_ENTRY( list_head( &db->transforms ),
                                      MSITRANSFORM, entry );
        list_remove( &t->entry );
        IStorage_Release( t->stg );
        msi_free( t );
    }
}