ddraw: Protect the ddraw list.
[wine] / dlls / msi / table.c
1 /*
2  * Implementation of the Microsoft Installer (msi.dll)
3  *
4  * Copyright 2002-2005 Mike McCormack for CodeWeavers
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * 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 #include <stdarg.h>
22
23 #define COBJMACROS
24 #define NONAMELESSUNION
25 #define NONAMELESSSTRUCT
26
27 #include "windef.h"
28 #include "winbase.h"
29 #include "winerror.h"
30 #include "wine/debug.h"
31 #include "msi.h"
32 #include "msiquery.h"
33 #include "objbase.h"
34 #include "objidl.h"
35 #include "msipriv.h"
36 #include "winnls.h"
37
38 #include "query.h"
39
40 WINE_DEFAULT_DEBUG_CHANNEL(msidb);
41
42 #define MSITABLE_HASH_TABLE_SIZE 37
43
44 typedef struct tagMSICOLUMNHASHENTRY
45 {
46     struct tagMSICOLUMNHASHENTRY *next;
47     UINT value;
48     UINT row;
49 } MSICOLUMNHASHENTRY;
50
51 typedef struct tagMSICOLUMNINFO
52 {
53     LPCWSTR tablename;
54     UINT   number;
55     LPCWSTR colname;
56     UINT   type;
57     UINT   offset;
58     MSICOLUMNHASHENTRY **hash_table;
59 } MSICOLUMNINFO;
60
61 struct tagMSITABLE
62 {
63     USHORT **data;
64     UINT row_count;
65     struct list entry;
66     WCHAR name[1];
67 };
68
69 typedef struct tagMSITRANSFORM {
70     struct list entry;
71     IStorage *stg;
72 } MSITRANSFORM;
73
74 static const WCHAR szStringData[] = {
75     '_','S','t','r','i','n','g','D','a','t','a',0 };
76 static const WCHAR szStringPool[] = {
77     '_','S','t','r','i','n','g','P','o','o','l',0 };
78
79 #define MAX_STREAM_NAME 0x1f
80
81 static UINT table_get_column_info( MSIDATABASE *db, LPCWSTR name,
82        MSICOLUMNINFO **pcols, UINT *pcount );
83 static UINT get_tablecolumns( MSIDATABASE *db, 
84        LPCWSTR szTableName, MSICOLUMNINFO *colinfo, UINT *sz);
85 static void msi_free_colinfo( MSICOLUMNINFO *colinfo, UINT count );
86
87 static inline UINT bytes_per_column( const MSICOLUMNINFO *col )
88 {
89     if( col->type & MSITYPE_STRING )
90         return 2;
91     if( (col->type & 0xff) > 4 )
92         ERR("Invalid column size!\n");
93     return col->type & 0xff;
94 }
95
96 static int utf2mime(int x)
97 {
98     if( (x>='0') && (x<='9') )
99         return x-'0';
100     if( (x>='A') && (x<='Z') )
101         return x-'A'+10;
102     if( (x>='a') && (x<='z') )
103         return x-'a'+10+26;
104     if( x=='.' )
105         return 10+26+26;
106     if( x=='_' )
107         return 10+26+26+1;
108     return -1;
109 }
110
111 static LPWSTR encode_streamname(BOOL bTable, LPCWSTR in)
112 {
113     DWORD count = MAX_STREAM_NAME;
114     DWORD ch, next;
115     LPWSTR out, p;
116
117     if( !bTable )
118         count = lstrlenW( in )+2;
119     out = msi_alloc( count*sizeof(WCHAR) );
120     p = out;
121
122     if( bTable )
123     {
124          *p++ = 0x4840;
125          count --;
126     }
127     while( count -- ) 
128     {
129         ch = *in++;
130         if( !ch )
131         {
132             *p = ch;
133             return out;
134         }
135         if( ( ch < 0x80 ) && ( utf2mime(ch) >= 0 ) )
136         {
137             ch = utf2mime(ch) + 0x4800;
138             next = *in;
139             if( next && (next<0x80) )
140             {
141                 next = utf2mime(next);
142                 if( next >= 0  )
143                 {
144                      next += 0x3ffffc0;
145                      ch += (next<<6);
146                      in++;
147                 }
148             }
149         }
150         *p++ = ch;
151     }
152     ERR("Failed to encode stream name (%s)\n",debugstr_w(in));
153     msi_free( out );
154     return NULL;
155 }
156
157 static int mime2utf(int x)
158 {
159     if( x<10 )
160         return x + '0';
161     if( x<(10+26))
162         return x - 10 + 'A';
163     if( x<(10+26+26))
164         return x - 10 - 26 + 'a';
165     if( x == (10+26+26) )
166         return '.';
167     return '_';
168 }
169
170 static BOOL decode_streamname(LPWSTR in, LPWSTR out)
171 {
172     WCHAR ch;
173     DWORD count = 0;
174
175     while ( (ch = *in++) )
176     {
177         if( (ch >= 0x3800 ) && (ch < 0x4840 ) )
178         {
179             if( ch >= 0x4800 )
180                 ch = mime2utf(ch-0x4800);
181             else
182             {
183                 ch -= 0x3800;
184                 *out++ = mime2utf(ch&0x3f);
185                 count++;
186                 ch = mime2utf((ch>>6)&0x3f);
187             }
188         }
189         *out++ = ch;
190         count++;
191     }
192     *out = 0;
193     return count;
194 }
195
196 void enum_stream_names( IStorage *stg )
197 {
198     IEnumSTATSTG *stgenum = NULL;
199     HRESULT r;
200     STATSTG stat;
201     ULONG n, count;
202     WCHAR name[0x40];
203
204     r = IStorage_EnumElements( stg, 0, NULL, 0, &stgenum );
205     if( FAILED( r ) )
206         return;
207
208     n = 0;
209     while( 1 )
210     {
211         count = 0;
212         r = IEnumSTATSTG_Next( stgenum, 1, &stat, &count );
213         if( FAILED( r ) || !count )
214             break;
215         decode_streamname( stat.pwcsName, name );
216         TRACE("stream %2d -> %s %s\n", n,
217               debugstr_w(stat.pwcsName), debugstr_w(name) );
218         n++;
219     }
220
221     IEnumSTATSTG_Release( stgenum );
222 }
223
224 static UINT read_stream_data( IStorage *stg, LPCWSTR stname,
225                               USHORT **pdata, UINT *psz )
226 {
227     HRESULT r;
228     UINT ret = ERROR_FUNCTION_FAILED;
229     VOID *data;
230     ULONG sz, count;
231     IStream *stm = NULL;
232     STATSTG stat;
233     LPWSTR encname;
234
235     encname = encode_streamname(TRUE, stname);
236
237     TRACE("%s -> %s\n",debugstr_w(stname),debugstr_w(encname));
238
239     r = IStorage_OpenStream(stg, encname, NULL, 
240             STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &stm);
241     msi_free( encname );
242     if( FAILED( r ) )
243     {
244         WARN("open stream failed r = %08x - empty table?\n", r);
245         return ret;
246     }
247
248     r = IStream_Stat(stm, &stat, STATFLAG_NONAME );
249     if( FAILED( r ) )
250     {
251         WARN("open stream failed r = %08x!\n", r);
252         goto end;
253     }
254
255     if( stat.cbSize.QuadPart >> 32 )
256     {
257         WARN("Too big!\n");
258         goto end;
259     }
260         
261     sz = stat.cbSize.QuadPart;
262     data = msi_alloc( sz );
263     if( !data )
264     {
265         WARN("couldn't allocate memory r=%08x!\n", r);
266         ret = ERROR_NOT_ENOUGH_MEMORY;
267         goto end;
268     }
269         
270     r = IStream_Read(stm, data, sz, &count );
271     if( FAILED( r ) || ( count != sz ) )
272     {
273         msi_free( data );
274         WARN("read stream failed r = %08x!\n", r);
275         goto end;
276     }
277
278     *pdata = data;
279     *psz = sz;
280     ret = ERROR_SUCCESS;
281
282 end:
283     IStream_Release( stm );
284
285     return ret;
286 }
287
288 UINT db_get_raw_stream( MSIDATABASE *db, LPCWSTR stname, IStream **stm )
289 {
290     LPWSTR encname;
291     HRESULT r;
292
293     encname = encode_streamname(FALSE, stname);
294
295     TRACE("%s -> %s\n",debugstr_w(stname),debugstr_w(encname));
296
297     r = IStorage_OpenStream(db->storage, encname, NULL, 
298             STGM_READ | STGM_SHARE_EXCLUSIVE, 0, stm);
299     if( FAILED( r ) )
300     {
301         MSITRANSFORM *transform;
302
303         LIST_FOR_EACH_ENTRY( transform, &db->transforms, MSITRANSFORM, entry )
304         {
305             TRACE("looking for %s in transform storage\n", debugstr_w(stname) );
306             r = IStorage_OpenStream( transform->stg, encname, NULL, 
307                     STGM_READ | STGM_SHARE_EXCLUSIVE, 0, stm );
308             if (SUCCEEDED(r))
309                 break;
310         }
311     }
312
313     msi_free( encname );
314
315     return SUCCEEDED(r) ? ERROR_SUCCESS : ERROR_FUNCTION_FAILED;
316 }
317
318 UINT read_raw_stream_data( MSIDATABASE *db, LPCWSTR stname,
319                               USHORT **pdata, UINT *psz )
320 {
321     HRESULT r;
322     UINT ret = ERROR_FUNCTION_FAILED;
323     VOID *data;
324     ULONG sz, count;
325     IStream *stm = NULL;
326     STATSTG stat;
327
328     r = db_get_raw_stream( db, stname, &stm );
329     if( r != ERROR_SUCCESS)
330         return ret;
331     r = IStream_Stat(stm, &stat, STATFLAG_NONAME );
332     if( FAILED( r ) )
333     {
334         WARN("open stream failed r = %08x!\n", r);
335         goto end;
336     }
337
338     if( stat.cbSize.QuadPart >> 32 )
339     {
340         WARN("Too big!\n");
341         goto end;
342     }
343         
344     sz = stat.cbSize.QuadPart;
345     data = msi_alloc( sz );
346     if( !data )
347     {
348         WARN("couldn't allocate memory r=%08x!\n", r);
349         ret = ERROR_NOT_ENOUGH_MEMORY;
350         goto end;
351     }
352         
353     r = IStream_Read(stm, data, sz, &count );
354     if( FAILED( r ) || ( count != sz ) )
355     {
356         msi_free( data );
357         WARN("read stream failed r = %08x!\n", r);
358         goto end;
359     }
360
361     *pdata = data;
362     *psz = sz;
363     ret = ERROR_SUCCESS;
364
365 end:
366     IStream_Release( stm );
367
368     return ret;
369 }
370
371 static UINT write_stream_data( IStorage *stg, LPCWSTR stname,
372                                LPVOID data, UINT sz )
373 {
374     HRESULT r;
375     UINT ret = ERROR_FUNCTION_FAILED;
376     ULONG count;
377     IStream *stm = NULL;
378     ULARGE_INTEGER size;
379     LARGE_INTEGER pos;
380     LPWSTR encname;
381
382     encname = encode_streamname(TRUE, stname );
383     r = IStorage_OpenStream( stg, encname, NULL, 
384             STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, &stm);
385     if( FAILED(r) )
386     {
387         r = IStorage_CreateStream( stg, encname,
388                 STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, 0, &stm);
389     }
390     msi_free( encname );
391     if( FAILED( r ) )
392     {
393         WARN("open stream failed r = %08x\n", r);
394         return ret;
395     }
396
397     size.QuadPart = sz;
398     r = IStream_SetSize( stm, size );
399     if( FAILED( r ) )
400     {
401         WARN("Failed to SetSize\n");
402         goto end;
403     }
404
405     pos.QuadPart = 0;
406     r = IStream_Seek( stm, pos, STREAM_SEEK_SET, NULL );
407     if( FAILED( r ) )
408     {
409         WARN("Failed to Seek\n");
410         goto end;
411     }
412
413     r = IStream_Write(stm, data, sz, &count );
414     if( FAILED( r ) || ( count != sz ) )
415     {
416         WARN("Failed to Write\n");
417         goto end;
418     }
419
420     ret = ERROR_SUCCESS;
421
422 end:
423     IStream_Release( stm );
424
425     return ret;
426 }
427
428 static void free_table( MSITABLE *table )
429 {
430     int i;
431     for( i=0; i<table->row_count; i++ )
432         msi_free( table->data[i] );
433     msi_free( table->data );
434     msi_free( table );
435 }
436
437 static UINT msi_table_get_row_size( const MSICOLUMNINFO *cols, UINT count )
438 {
439     const MSICOLUMNINFO *last_col = &cols[count-1];
440     if (!count)
441         return 0;
442     return last_col->offset + bytes_per_column( last_col );
443 }
444
445 /* add this table to the list of cached tables in the database */
446 static MSITABLE *read_table_from_storage( IStorage *stg, LPCWSTR name,
447                                     const MSICOLUMNINFO *cols, UINT num_cols )
448 {
449     MSITABLE *t;
450     USHORT *rawdata = NULL;
451     UINT rawsize = 0, i, j, row_size = 0;
452
453     TRACE("%s\n",debugstr_w(name));
454
455     /* nonexistent tables should be interpreted as empty tables */
456     t = msi_alloc( sizeof (MSITABLE) + lstrlenW(name)*sizeof (WCHAR) );
457     if( !t )
458         return t;
459
460     row_size = msi_table_get_row_size( cols, num_cols );
461
462     t->row_count = 0;
463     t->data = NULL;
464     lstrcpyW( t->name, name );
465
466     /* if we can't read the table, just assume that it's empty */
467     read_stream_data( stg, name, &rawdata, &rawsize );
468     if( !rawdata )
469         return t;
470
471     TRACE("Read %d bytes\n", rawsize );
472
473     if( rawsize % row_size )
474     {
475         WARN("Table size is invalid %d/%d\n", rawsize, row_size );
476         goto err;
477     }
478
479     t->row_count = rawsize / row_size;
480     t->data = msi_alloc_zero( t->row_count * sizeof (USHORT*) );
481     if( !t->data )
482         goto err;
483
484     /* transpose all the data */
485     TRACE("Transposing data from %d rows\n", t->row_count );
486     for( i=0; i<t->row_count; i++ )
487     {
488         t->data[i] = msi_alloc( row_size );
489         if( !t->data[i] )
490             goto err;
491
492         for( j=0; j<num_cols; j++ )
493         {
494             UINT ofs = cols[j].offset/2;
495             UINT n = bytes_per_column( &cols[j] );
496
497             switch( n )
498             {
499             case 2:
500                 t->data[i][ofs] = rawdata[ofs*t->row_count + i ];
501                 break;
502             case 4:
503                 t->data[i][ofs] = rawdata[ofs*t->row_count + i*2 ];
504                 t->data[i][ofs+1] = rawdata[ofs*t->row_count + i*2 + 1];
505                 break;
506             default:
507                 ERR("oops - unknown column width %d\n", n);
508                 goto err;
509             }
510         }
511     }
512
513     msi_free( rawdata );
514     return t;
515 err:
516     msi_free( rawdata );
517     free_table( t );
518     return NULL;
519 }
520
521 void free_cached_tables( MSIDATABASE *db )
522 {
523     while( !list_empty( &db->tables ) )
524     {
525         MSITABLE *t = LIST_ENTRY( list_head( &db->tables ), MSITABLE, entry );
526
527         list_remove( &t->entry );
528         free_table( t );
529     }
530 }
531
532 static MSITABLE *find_cached_table( MSIDATABASE *db, LPCWSTR name )
533 {
534     MSITABLE *t;
535
536     LIST_FOR_EACH_ENTRY( t, &db->tables, MSITABLE, entry )
537         if( !lstrcmpW( name, t->name ) )
538             return t;
539
540     return NULL;
541 }
542
543 static UINT table_get_column_info( MSIDATABASE *db, LPCWSTR name, MSICOLUMNINFO **pcols, UINT *pcount )
544 {
545     UINT r, column_count = 0;
546     MSICOLUMNINFO *columns;
547
548     /* get the number of columns in this table */
549     column_count = 0;
550     r = get_tablecolumns( db, name, NULL, &column_count );
551     if( r != ERROR_SUCCESS )
552         return r;
553
554     /* if there's no columns, there's no table */
555     if( column_count == 0 )
556         return ERROR_INVALID_PARAMETER;
557
558     TRACE("Table %s found\n", debugstr_w(name) );
559
560     columns = msi_alloc( column_count*sizeof (MSICOLUMNINFO) );
561     if( !columns )
562         return ERROR_FUNCTION_FAILED;
563
564     r = get_tablecolumns( db, name, columns, &column_count );
565     if( r != ERROR_SUCCESS )
566     {
567         msi_free( columns );
568         return ERROR_FUNCTION_FAILED;
569     }
570
571     *pcols = columns;
572     *pcount = column_count;
573
574     return r;
575 }
576
577 static MSITABLE *get_table( MSIDATABASE *db, LPCWSTR name,
578                             const MSICOLUMNINFO *cols, UINT num_cols )
579 {
580     MSITABLE *table;
581
582     /* first, see if the table is cached */
583     table = find_cached_table( db, name );
584     if( table )
585         return table;
586
587     table = read_table_from_storage( db->storage, name, cols, num_cols );
588     if( table )
589         list_add_head( &db->tables, &table->entry );
590
591     return table;
592 }
593
594 static UINT save_table( MSIDATABASE *db, MSITABLE *t )
595 {
596     USHORT *rawdata = NULL, *p;
597     UINT rawsize, r, i, j, row_size, num_cols = 0;
598     MSICOLUMNINFO *cols = NULL;
599
600     TRACE("Saving %s\n", debugstr_w( t->name ) );
601
602     r = table_get_column_info( db, t->name, &cols, &num_cols );
603     if( r != ERROR_SUCCESS )
604         return r;
605     
606     row_size = msi_table_get_row_size( cols, num_cols );
607
608     rawsize = t->row_count * row_size;
609     rawdata = msi_alloc_zero( rawsize );
610     if( !rawdata )
611     {
612         r = ERROR_NOT_ENOUGH_MEMORY;
613         goto err;
614     }
615
616     p = rawdata;
617     for( i=0; i<num_cols; i++ )
618     {
619         for( j=0; j<t->row_count; j++ )
620         {
621             UINT offset = cols[i].offset;
622
623             *p++ = t->data[j][offset/2];
624             if( 4 == bytes_per_column( &cols[i] ) )
625                 *p++ = t->data[j][offset/2+1];
626         }
627     }
628
629     TRACE("writing %d bytes\n", rawsize);
630     r = write_stream_data( db->storage, t->name, rawdata, rawsize );
631
632 err:
633     msi_free_colinfo( cols, num_cols );
634     msi_free( cols );
635     msi_free( rawdata );
636
637     return r;
638 }
639
640 HRESULT init_string_table( IStorage *stg )
641 {
642     HRESULT r;
643     USHORT zero[2] = { 0, 0 };
644     ULONG count = 0;
645     IStream *stm = NULL;
646     LPWSTR encname;
647
648     encname = encode_streamname(TRUE, szStringPool );
649
650     /* create the StringPool stream... add the zero string to it*/
651     r = IStorage_CreateStream( stg, encname,
652             STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, 0, &stm);
653     msi_free( encname );
654     if( r ) 
655     {
656         TRACE("Failed\n");
657         return r;
658     }
659
660     r = IStream_Write(stm, zero, sizeof zero, &count );
661     IStream_Release( stm );
662
663     if( FAILED( r ) || ( count != sizeof zero ) )
664     {
665         TRACE("Failed\n");
666         return E_FAIL;
667     }
668
669     /* create the StringData stream... make it zero length */
670     encname = encode_streamname(TRUE, szStringData );
671     r = IStorage_CreateStream( stg, encname,
672             STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, 0, &stm);
673     msi_free( encname );
674     if( r ) 
675     {
676         TRACE("Failed\n");
677         return E_FAIL;
678     }
679     IStream_Release( stm );
680
681     return r;
682 }
683
684 string_table *load_string_table( IStorage *stg )
685 {
686     string_table *st = NULL;
687     CHAR *data = NULL;
688     USHORT *pool = NULL;
689     UINT r, datasize = 0, poolsize = 0, codepage;
690     DWORD i, count, offset, len, n, refs;
691
692     r = read_stream_data( stg, szStringPool, &pool, &poolsize );
693     if( r != ERROR_SUCCESS)
694         goto end;
695     r = read_stream_data( stg, szStringData, (USHORT**)&data, &datasize );
696     if( r != ERROR_SUCCESS)
697         goto end;
698
699     count = poolsize/4;
700     if( poolsize > 4 )
701         codepage = pool[0] | ( pool[1] << 16 );
702     else
703         codepage = CP_ACP;
704     st = msi_init_stringtable( count, codepage );
705
706     offset = 0;
707     n = 1;
708     i = 1;
709     while( i<count )
710     {
711         /* the string reference count is always the second word */
712         refs = pool[i*2+1];
713
714         /* empty entries have two zeros, still have a string id */
715         if (pool[i*2] == 0 && refs == 0)
716         {
717             i++;
718             n++;
719             continue;
720         }
721
722         /*
723          * If a string is over 64k, the previous string entry is made null
724          * and its the high word of the length is inserted in the null string's
725          * reference count field.
726          */
727         if( pool[i*2] == 0)
728         {
729             len = (pool[i*2+3] << 16) + pool[i*2+2];
730             i += 2;
731         }
732         else
733         {
734             len = pool[i*2];
735             i += 1;
736         }
737
738         if ( (offset + len) > datasize )
739         {
740             ERR("string table corrupt?\n");
741             break;
742         }
743
744         r = msi_addstring( st, n, data+offset, len, refs );
745         if( r != n )
746             ERR("Failed to add string %d\n", n );
747         n++;
748         offset += len;
749     }
750
751     if ( datasize != offset )
752         ERR("string table load failed! (%08x != %08x), please report\n", datasize, offset );
753
754     TRACE("Loaded %d strings\n", count);
755
756 end:
757     msi_free( pool );
758     msi_free( data );
759
760     return st;
761 }
762
763 static UINT save_string_table( MSIDATABASE *db )
764 {
765     UINT i, count, datasize = 0, poolsize = 0, sz, used, r, codepage, n;
766     UINT ret = ERROR_FUNCTION_FAILED;
767     CHAR *data = NULL;
768     USHORT *pool = NULL;
769
770     TRACE("\n");
771
772     /* construct the new table in memory first */
773     count = msi_string_totalsize( db->strings, &datasize, &poolsize );
774
775     TRACE("%u %u %u\n", count, datasize, poolsize );
776
777     pool = msi_alloc( poolsize );
778     if( ! pool )
779     {
780         WARN("Failed to alloc pool %d bytes\n", poolsize );
781         goto err;
782     }
783     data = msi_alloc( datasize );
784     if( ! data )
785     {
786         WARN("Failed to alloc data %d bytes\n", poolsize );
787         goto err;
788     }
789
790     used = 0;
791     codepage = msi_string_get_codepage( db->strings );
792     pool[0]=codepage&0xffff;
793     pool[1]=(codepage>>16);
794     n = 1;
795     for( i=1; i<count; i++ )
796     {
797         sz = datasize - used;
798         r = msi_id2stringA( db->strings, i, data+used, &sz );
799         if( r != ERROR_SUCCESS )
800         {
801             ERR("failed to fetch string\n");
802             sz = 0;
803         }
804         if( sz && (sz < (datasize - used ) ) )
805             sz--;
806
807         pool[ n*2 + 1 ] = msi_id_refcount( db->strings, i );
808         if (sz < 0x10000)
809         {
810             pool[ n*2 ] = sz;
811             n++;
812         }
813         else
814         {
815             pool[ n*2 ] = 0;
816             pool[ n*2 + 2 ] = sz&0xffff;
817             pool[ n*2 + 3 ] = (sz>>16);
818             n += 2;
819         }
820         used += sz;
821         if( used > datasize  )
822         {
823             ERR("oops overran %d >= %d\n", used, datasize);
824             goto err;
825         }
826     }
827
828     if( used != datasize )
829     {
830         ERR("oops used %d != datasize %d\n", used, datasize);
831         goto err;
832     }
833
834     /* write the streams */
835     r = write_stream_data( db->storage, szStringData, data, datasize );
836     TRACE("Wrote StringData r=%08x\n", r);
837     if( r )
838         goto err;
839     r = write_stream_data( db->storage, szStringPool, pool, poolsize );
840     TRACE("Wrote StringPool r=%08x\n", r);
841     if( r )
842         goto err;
843
844     ret = ERROR_SUCCESS;
845
846 err:
847     msi_free( data );
848     msi_free( pool );
849
850     return ret;
851 }
852
853 /* information for default tables */
854 static const WCHAR szTables[]  = { '_','T','a','b','l','e','s',0 };
855 static const WCHAR szTable[]  = { 'T','a','b','l','e',0 };
856 static const WCHAR szName[]    = { 'N','a','m','e',0 };
857 static const WCHAR szColumns[] = { '_','C','o','l','u','m','n','s',0 };
858 static const WCHAR szColumn[]  = { 'C','o','l','u','m','n',0 };
859 static const WCHAR szNumber[]  = { 'N','u','m','b','e','r',0 };
860 static const WCHAR szType[]    = { 'T','y','p','e',0 };
861
862 static const MSICOLUMNINFO _Columns_cols[4] = {
863     { szColumns, 1, szTable,  MSITYPE_VALID | MSITYPE_STRING | 64, 0 },
864     { szColumns, 2, szNumber, MSITYPE_VALID | 2,                   2 },
865     { szColumns, 3, szName,   MSITYPE_VALID | MSITYPE_STRING | 64, 4 },
866     { szColumns, 4, szType,   MSITYPE_VALID | 2,                   6 },
867 };
868 static const MSICOLUMNINFO _Tables_cols[1] = {
869     { szTables,  1, szName,   MSITYPE_VALID | MSITYPE_STRING | 64, 0 },
870 };
871
872 static UINT get_defaulttablecolumns( LPCWSTR name, MSICOLUMNINFO *colinfo, UINT *sz)
873 {
874     const MSICOLUMNINFO *p;
875     DWORD i, n;
876
877     TRACE("%s\n", debugstr_w(name));
878
879     if (!lstrcmpW( name, szTables ))
880     {
881         p = _Tables_cols;
882         n = 1;
883     }
884     else if (!lstrcmpW( name, szColumns ))
885     {
886         p = _Columns_cols;
887         n = 4;
888     }
889     else
890         return ERROR_FUNCTION_FAILED;
891
892     /* duplicate the string data so we can free it in msi_free_colinfo */
893     for (i=0; i<n; i++)
894     {
895         if (colinfo && (i < *sz) )
896         {
897             memcpy( &colinfo[i], &p[i], sizeof(MSICOLUMNINFO) );
898             colinfo[i].tablename = strdupW( p[i].tablename );
899             colinfo[i].colname = strdupW( p[i].colname );
900         }
901         if( colinfo && (i >= *sz) )
902             break;
903     }
904     *sz = n;
905     return ERROR_SUCCESS;
906 }
907
908 static void msi_free_colinfo( MSICOLUMNINFO *colinfo, UINT count )
909 {
910     UINT i;
911
912     for( i=0; i<count; i++ )
913     {
914         msi_free( (LPWSTR) colinfo[i].tablename );
915         msi_free( (LPWSTR) colinfo[i].colname );
916         msi_free( colinfo[i].hash_table );
917     }
918 }
919
920 LPWSTR MSI_makestring( MSIDATABASE *db, UINT stringid)
921 {
922     return strdupW(msi_string_lookup_id( db->strings, stringid ));
923 }
924
925 static UINT get_tablecolumns( MSIDATABASE *db, 
926        LPCWSTR szTableName, MSICOLUMNINFO *colinfo, UINT *sz)
927 {
928     UINT r, i, n=0, table_id, count, maxcount = *sz;
929     MSITABLE *table = NULL;
930
931     /* first check if there is a default table with that name */
932     r = get_defaulttablecolumns( szTableName, colinfo, sz );
933     if( ( r == ERROR_SUCCESS ) && *sz )
934         return r;
935
936     table = get_table( db, szColumns, _Columns_cols, 4 );
937     if( !table )
938     {
939         ERR("couldn't load _Columns table\n");
940         return ERROR_FUNCTION_FAILED;
941     }
942
943     /* convert table and column names to IDs from the string table */
944     r = msi_string2idW( db->strings, szTableName, &table_id );
945     if( r != ERROR_SUCCESS )
946     {
947         WARN("Couldn't find id for %s\n", debugstr_w(szTableName));
948         return r;
949     }
950
951     TRACE("Table id is %d, row count is %d\n", table_id, table->row_count);
952
953     count = table->row_count;
954     for( i=0; i<count; i++ )
955     {
956         if( table->data[ i ][ 0 ] != table_id )
957             continue;
958         if( colinfo )
959         {
960             UINT id = table->data[ i ] [ 2 ];
961             colinfo[n].tablename = MSI_makestring( db, table_id );
962             colinfo[n].number = table->data[ i ][ 1 ] - (1<<15);
963             colinfo[n].colname = MSI_makestring( db, id );
964             colinfo[n].type = table->data[ i ] [ 3 ] ^ 0x8000;
965             colinfo[n].hash_table = NULL;
966             /* this assumes that columns are in order in the table */
967             if( n )
968                 colinfo[n].offset = colinfo[n-1].offset
969                                   + bytes_per_column( &colinfo[n-1] );
970             else
971                 colinfo[n].offset = 0;
972             TRACE("table %s column %d is [%s] (%d) with type %08x "
973                   "offset %d at row %d\n", debugstr_w(szTableName),
974                    colinfo[n].number, debugstr_w(colinfo[n].colname),
975                    id, colinfo[n].type, colinfo[n].offset, i);
976             if( n != (colinfo[n].number-1) )
977             {
978                 ERR("oops. data in the _Columns table isn't in the right "
979                     "order for table %s\n", debugstr_w(szTableName));
980                 return ERROR_FUNCTION_FAILED;
981             }
982         }
983         n++;
984         if( colinfo && ( n >= maxcount ) )
985             break;
986     }
987     *sz = n;
988
989     return ERROR_SUCCESS;
990 }
991
992 /* try to find the table name in the _Tables table */
993 BOOL TABLE_Exists( MSIDATABASE *db, LPWSTR name )
994 {
995     UINT r, table_id = 0, i, count;
996     MSITABLE *table = NULL;
997
998     if( !lstrcmpW( name, szTables ) )
999         return TRUE;
1000     if( !lstrcmpW( name, szColumns ) )
1001         return TRUE;
1002
1003     r = msi_string2idW( db->strings, name, &table_id );
1004     if( r != ERROR_SUCCESS )
1005     {
1006         TRACE("Couldn't find id for %s\n", debugstr_w(name));
1007         return FALSE;
1008     }
1009
1010     table = get_table( db, szTables, _Tables_cols, 1 );
1011     if( !table )
1012     {
1013         TRACE("table %s not available\n", debugstr_w(szTables));
1014         return FALSE;
1015     }
1016
1017     /* count = table->size/2; */
1018     count = table->row_count;
1019     for( i=0; i<count; i++ )
1020         if( table->data[ i ][ 0 ] == table_id )
1021             break;
1022
1023     if (i!=count)
1024         return TRUE;
1025
1026     TRACE("Searched %d tables, but %d was not found\n", count, table_id );
1027
1028     return FALSE;
1029 }
1030
1031 /* below is the query interface to a table */
1032
1033 typedef struct tagMSITABLEVIEW
1034 {
1035     MSIVIEW        view;
1036     MSIDATABASE   *db;
1037     MSITABLE      *table;
1038     MSICOLUMNINFO *columns;
1039     UINT           num_cols;
1040     UINT           row_size;
1041     WCHAR          name[1];
1042 } MSITABLEVIEW;
1043
1044 static UINT TABLE_fetch_int( struct tagMSIVIEW *view, UINT row, UINT col, UINT *val )
1045 {
1046     MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1047     UINT offset, num_rows, n;
1048
1049     if( !tv->table )
1050         return ERROR_INVALID_PARAMETER;
1051
1052     if( (col==0) || (col>tv->num_cols) )
1053         return ERROR_INVALID_PARAMETER;
1054
1055     /* how many rows are there ? */
1056     num_rows = tv->table->row_count;
1057     if( row >= num_rows )
1058         return ERROR_NO_MORE_ITEMS;
1059
1060     if( tv->columns[col-1].offset >= tv->row_size )
1061     {
1062         ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1063         ERR("%p %p\n", tv, tv->columns );
1064         return ERROR_FUNCTION_FAILED;
1065     }
1066
1067     offset = row + (tv->columns[col-1].offset/2) * num_rows;
1068     n = bytes_per_column( &tv->columns[col-1] );
1069     switch( n )
1070     {
1071     case 4:
1072         offset = tv->columns[col-1].offset/2;
1073         *val = tv->table->data[row][offset] + 
1074                (tv->table->data[row][offset + 1] << 16);
1075         break;
1076     case 2:
1077         offset = tv->columns[col-1].offset/2;
1078         *val = tv->table->data[row][offset];
1079         break;
1080     default:
1081         ERR("oops! what is %d bytes per column?\n", n );
1082         return ERROR_FUNCTION_FAILED;
1083     }
1084
1085     /* TRACE("Data [%d][%d] = %d\n", row, col, *val ); */
1086
1087     return ERROR_SUCCESS;
1088 }
1089
1090 /*
1091  * We need a special case for streams, as we need to reference column with
1092  * the name of the stream in the same table, and the table name
1093  * which may not be available at higher levels of the query
1094  */
1095 static UINT TABLE_fetch_stream( struct tagMSIVIEW *view, UINT row, UINT col, IStream **stm )
1096 {
1097     MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1098     UINT ival = 0, refcol = 0, r;
1099     LPCWSTR sval;
1100     LPWSTR full_name;
1101     DWORD len;
1102     static const WCHAR szDot[] = { '.', 0 };
1103
1104     if( !view->ops->fetch_int )
1105         return ERROR_INVALID_PARAMETER;
1106
1107     /*
1108      * The column marked with the type stream data seems to have a single number
1109      * which references the column containing the name of the stream data
1110      *
1111      * Fetch the column to reference first.
1112      */
1113     r = view->ops->fetch_int( view, row, col, &ival );
1114     if( r != ERROR_SUCCESS )
1115         return r;
1116
1117     /* now get the column with the name of the stream */
1118     r = view->ops->fetch_int( view, row, ival, &refcol );
1119     if( r != ERROR_SUCCESS )
1120         return r;
1121
1122     /* lookup the string value from the string table */
1123     sval = msi_string_lookup_id( tv->db->strings, refcol );
1124     if( !sval )
1125         return ERROR_INVALID_PARAMETER;
1126
1127     len = lstrlenW( tv->name ) + 2 + lstrlenW( sval );
1128     full_name = msi_alloc( len*sizeof(WCHAR) );
1129     lstrcpyW( full_name, tv->name );
1130     lstrcatW( full_name, szDot );
1131     lstrcatW( full_name, sval );
1132
1133     r = db_get_raw_stream( tv->db, full_name, stm );
1134     if( r )
1135         ERR("fetching stream %s, error = %d\n",debugstr_w(full_name), r);
1136     msi_free( full_name );
1137
1138     return r;
1139 }
1140
1141 static UINT TABLE_set_int( struct tagMSIVIEW *view, UINT row, UINT col, UINT val )
1142 {
1143     MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1144     UINT offset, n;
1145
1146     if( !tv->table )
1147         return ERROR_INVALID_PARAMETER;
1148
1149     if( (col==0) || (col>tv->num_cols) )
1150         return ERROR_INVALID_PARAMETER;
1151
1152     if( tv->columns[col-1].offset >= tv->row_size )
1153     {
1154         ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1155         ERR("%p %p\n", tv, tv->columns );
1156         return ERROR_FUNCTION_FAILED;
1157     }
1158
1159     n = bytes_per_column( &tv->columns[col-1] );
1160     switch( n )
1161     {
1162     case 4:
1163         offset = tv->columns[col-1].offset/2;
1164         tv->table->data[row][offset]     = val & 0xffff;
1165         tv->table->data[row][offset + 1] = (val>>16)&0xffff;
1166         break;
1167     case 2:
1168         offset = tv->columns[col-1].offset/2;
1169         tv->table->data[row][offset] = val;
1170         break;
1171     default:
1172         ERR("oops! what is %d bytes per column?\n", n );
1173         return ERROR_FUNCTION_FAILED;
1174     }
1175     return ERROR_SUCCESS;
1176 }
1177
1178 static UINT table_create_new_row( struct tagMSIVIEW *view, UINT *num )
1179 {
1180     MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1181     USHORT **p, *row;
1182     UINT sz;
1183
1184     TRACE("%p\n", view);
1185
1186     if( !tv->table )
1187         return ERROR_INVALID_PARAMETER;
1188
1189     row = msi_alloc_zero( tv->row_size );
1190     if( !row )
1191         return ERROR_NOT_ENOUGH_MEMORY;
1192
1193     sz = (tv->table->row_count + 1) * sizeof (UINT*);
1194     if( tv->table->data )
1195         p = msi_realloc( tv->table->data, sz );
1196     else
1197         p = msi_alloc( sz );
1198     if( !p )
1199     {
1200         msi_free( row );
1201         return ERROR_NOT_ENOUGH_MEMORY;
1202     }
1203
1204     tv->table->data = p;
1205     tv->table->data[tv->table->row_count] = row;
1206     *num = tv->table->row_count;
1207     tv->table->row_count++;
1208
1209     return ERROR_SUCCESS;
1210 }
1211
1212 static UINT TABLE_execute( struct tagMSIVIEW *view, MSIRECORD *record )
1213 {
1214     MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1215
1216     TRACE("%p %p\n", tv, record);
1217
1218     TRACE("There are %d columns\n", tv->num_cols );
1219     tv->table = get_table( tv->db, tv->name, tv->columns, tv->num_cols );
1220     if( !tv->table )
1221         return ERROR_FUNCTION_FAILED;
1222
1223     return ERROR_SUCCESS;
1224 }
1225
1226 static UINT TABLE_close( struct tagMSIVIEW *view )
1227 {
1228     MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1229
1230     TRACE("%p\n", view );
1231
1232     if( !tv->table )
1233         return ERROR_FUNCTION_FAILED;
1234
1235     tv->table = NULL;
1236     
1237     return ERROR_SUCCESS;
1238 }
1239
1240 static UINT TABLE_get_dimensions( struct tagMSIVIEW *view, UINT *rows, UINT *cols)
1241 {
1242     MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1243
1244     TRACE("%p %p %p\n", view, rows, cols );
1245
1246     if( cols )
1247         *cols = tv->num_cols;
1248     if( rows )
1249     {
1250         if( !tv->table )
1251             return ERROR_INVALID_PARAMETER;
1252         *rows = tv->table->row_count;
1253     }
1254
1255     return ERROR_SUCCESS;
1256 }
1257
1258 static UINT TABLE_get_column_info( struct tagMSIVIEW *view,
1259                 UINT n, LPWSTR *name, UINT *type )
1260 {
1261     MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1262
1263     TRACE("%p %d %p %p\n", tv, n, name, type );
1264
1265     if( ( n == 0 ) || ( n > tv->num_cols ) )
1266         return ERROR_INVALID_PARAMETER;
1267
1268     if( name )
1269     {
1270         *name = strdupW( tv->columns[n-1].colname );
1271         if( !*name )
1272             return ERROR_FUNCTION_FAILED;
1273     }
1274     if( type )
1275         *type = tv->columns[n-1].type;
1276
1277     return ERROR_SUCCESS;
1278 }
1279
1280 static UINT msi_table_find_row( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *row );
1281
1282 static UINT table_validate_new( MSITABLEVIEW *tv, MSIRECORD *rec )
1283 {
1284     UINT r, row, i;
1285
1286     /* check there's no null values where they're not allowed */
1287     for( i = 0; i < tv->num_cols; i++ )
1288     {
1289         if ( tv->columns[i].type & MSITYPE_NULLABLE )
1290             continue;
1291
1292         if ( tv->columns[i].type & MSITYPE_STRING )
1293         {
1294             LPCWSTR str;
1295
1296             str = MSI_RecordGetString( rec, i+1 );
1297             if (str == NULL || str[0] == 0)
1298                 return ERROR_INVALID_DATA;
1299         }
1300         else
1301         {
1302             UINT n;
1303
1304             n = MSI_RecordGetInteger( rec, i+1 );
1305             if (n == MSI_NULL_INTEGER)
1306                 return ERROR_INVALID_DATA;
1307         }
1308     }
1309
1310     /* check there's no duplicate keys */
1311     r = msi_table_find_row( tv, rec, &row );
1312     if (r == ERROR_SUCCESS)
1313         return ERROR_INVALID_DATA;
1314
1315     return ERROR_SUCCESS;
1316 }
1317
1318 static UINT msi_table_modify_row( MSITABLEVIEW *tv, MSIRECORD *rec,
1319                                   UINT row, UINT mask )
1320 {
1321     UINT i, val, r = ERROR_SUCCESS;
1322
1323     TRACE("%p %p %u %08x\n", tv, rec, row, mask );
1324
1325     for( i = 0; i < tv->num_cols; i++ )
1326     {
1327         /* set keys or values specified in the mask */
1328         if( (~tv->columns[i].type & MSITYPE_KEY) && (~mask & (1<<i)) )
1329             continue;
1330
1331         if( (tv->columns[i].type & MSITYPE_STRING) &&
1332             ! MSITYPE_IS_BINARY(tv->columns[i].type) )
1333         {
1334             const WCHAR *str = MSI_RecordGetString( rec, i+1 );
1335             val = msi_addstringW( tv->db->strings, 0, str, -1, 1 );
1336         }
1337         else
1338         {
1339             val = MSI_RecordGetInteger( rec, i+1 );
1340             if ( 2 == bytes_per_column( &tv->columns[i] ) )
1341                 val ^= 0x8000;
1342             else
1343                 val ^= 0x80000000;
1344         }
1345         r = TABLE_set_int( &tv->view, row, i+1, val );
1346         if( r )
1347             break;
1348     }
1349
1350     return r;
1351 }
1352
1353 static UINT TABLE_insert_row( struct tagMSIVIEW *view, MSIRECORD *rec )
1354 {
1355     MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1356     UINT r, row = -1;
1357
1358     TRACE("%p %p\n", tv, rec );
1359
1360     /* check that the key is unique - can we find a matching row? */
1361     r = table_validate_new( tv, rec );
1362     if( r != ERROR_SUCCESS )
1363         return ERROR_FUNCTION_FAILED;
1364
1365     r = table_create_new_row( view, &row );
1366     TRACE("insert_row returned %08x\n", r);
1367     if( r != ERROR_SUCCESS )
1368         return r;
1369
1370     return msi_table_modify_row( tv, rec, row, ~0 );
1371 }
1372
1373 static UINT TABLE_modify( struct tagMSIVIEW *view, MSIMODIFY eModifyMode,
1374                 MSIRECORD *rec)
1375 {
1376     MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1377     UINT r;
1378
1379     TRACE("%p %d %p\n", view, eModifyMode, rec );
1380
1381     if (!tv->table)
1382     {
1383         r = TABLE_execute( view, NULL );
1384         if( r )
1385             return r;
1386     }
1387
1388     switch (eModifyMode)
1389     {
1390     case MSIMODIFY_VALIDATE_NEW:
1391         r = table_validate_new( tv, rec );
1392         break;
1393
1394     case MSIMODIFY_INSERT_TEMPORARY:
1395         r = table_validate_new( tv, rec );
1396         if (r != ERROR_SUCCESS)
1397             break;
1398         r = TABLE_insert_row( view, rec );
1399         break;
1400
1401     case MSIMODIFY_REFRESH:
1402     case MSIMODIFY_INSERT:
1403     case MSIMODIFY_UPDATE:
1404     case MSIMODIFY_ASSIGN:
1405     case MSIMODIFY_REPLACE:
1406     case MSIMODIFY_MERGE:
1407     case MSIMODIFY_DELETE:
1408     case MSIMODIFY_VALIDATE:
1409     case MSIMODIFY_VALIDATE_FIELD:
1410     case MSIMODIFY_VALIDATE_DELETE:
1411         FIXME("%p %d %p - mode not implemented\n", view, eModifyMode, rec );
1412         r = ERROR_CALL_NOT_IMPLEMENTED;
1413         break;
1414
1415     default:
1416         r = ERROR_INVALID_DATA;
1417     }
1418
1419     return r;
1420 }
1421
1422 static UINT TABLE_delete( struct tagMSIVIEW *view )
1423 {
1424     MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1425
1426     TRACE("%p\n", view );
1427
1428     tv->table = NULL;
1429
1430     if( tv->columns )
1431     {
1432         msi_free_colinfo( tv->columns, tv->num_cols );
1433         msi_free( tv->columns );
1434     }
1435     tv->columns = NULL;
1436
1437     msi_free( tv );
1438
1439     return ERROR_SUCCESS;
1440 }
1441
1442 static UINT TABLE_find_matching_rows( struct tagMSIVIEW *view, UINT col,
1443     UINT val, UINT *row, MSIITERHANDLE *handle )
1444 {
1445     MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1446     const MSICOLUMNHASHENTRY *entry;
1447
1448     TRACE("%p, %d, %u, %p\n", view, col, val, *handle);
1449
1450     if( !tv->table )
1451         return ERROR_INVALID_PARAMETER;
1452
1453     if( (col==0) || (col > tv->num_cols) )
1454         return ERROR_INVALID_PARAMETER;
1455
1456     if( !tv->columns[col-1].hash_table )
1457     {
1458         UINT i;
1459         UINT num_rows = tv->table->row_count;
1460         MSICOLUMNHASHENTRY **hash_table;
1461         MSICOLUMNHASHENTRY *new_entry;
1462
1463         if( tv->columns[col-1].offset >= tv->row_size )
1464         {
1465             ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1466             ERR("%p %p\n", tv, tv->columns );
1467             return ERROR_FUNCTION_FAILED;
1468         }
1469
1470         /* allocate contiguous memory for the table and its entries so we
1471          * don't have to do an expensive cleanup */
1472         hash_table = msi_alloc(MSITABLE_HASH_TABLE_SIZE * sizeof(MSICOLUMNHASHENTRY*) +
1473             num_rows * sizeof(MSICOLUMNHASHENTRY));
1474         if (!hash_table)
1475             return ERROR_OUTOFMEMORY;
1476
1477         memset(hash_table, 0, MSITABLE_HASH_TABLE_SIZE * sizeof(MSICOLUMNHASHENTRY*));
1478         tv->columns[col-1].hash_table = hash_table;
1479
1480         new_entry = (MSICOLUMNHASHENTRY *)(hash_table + MSITABLE_HASH_TABLE_SIZE);
1481
1482         for (i = 0; i < num_rows; i++, new_entry++)
1483         {
1484             UINT row_value, n;
1485             UINT offset = i + (tv->columns[col-1].offset/2) * num_rows;
1486             n = bytes_per_column( &tv->columns[col-1] );
1487             switch( n )
1488             {
1489             case 4:
1490                 offset = tv->columns[col-1].offset/2;
1491                 row_value = tv->table->data[i][offset] + 
1492                     (tv->table->data[i][offset + 1] << 16);
1493                 break;
1494             case 2:
1495                 offset = tv->columns[col-1].offset/2;
1496                 row_value = tv->table->data[i][offset];
1497                 break;
1498             default:
1499                 ERR("oops! what is %d bytes per column?\n", n );
1500                 continue;
1501             }
1502
1503             new_entry->next = NULL;
1504             new_entry->value = row_value;
1505             new_entry->row = i;
1506             if (hash_table[row_value % MSITABLE_HASH_TABLE_SIZE])
1507             {
1508                 MSICOLUMNHASHENTRY *prev_entry = hash_table[row_value % MSITABLE_HASH_TABLE_SIZE];
1509                 while (prev_entry->next)
1510                     prev_entry = prev_entry->next;
1511                 prev_entry->next = new_entry;
1512             }
1513             else
1514                 hash_table[row_value % MSITABLE_HASH_TABLE_SIZE] = new_entry;
1515         }
1516     }
1517
1518     if( !*handle )
1519         entry = tv->columns[col-1].hash_table[val % MSITABLE_HASH_TABLE_SIZE];
1520     else
1521         entry = ((const MSICOLUMNHASHENTRY *)*handle)->next;
1522
1523     while (entry && entry->value != val)
1524         entry = entry->next;
1525
1526     *handle = (MSIITERHANDLE)entry;
1527     if (!entry)
1528         return ERROR_NO_MORE_ITEMS;
1529
1530     *row = entry->row;
1531     return ERROR_SUCCESS;
1532 }
1533
1534
1535 static const MSIVIEWOPS table_ops =
1536 {
1537     TABLE_fetch_int,
1538     TABLE_fetch_stream,
1539     TABLE_set_int,
1540     TABLE_insert_row,
1541     TABLE_execute,
1542     TABLE_close,
1543     TABLE_get_dimensions,
1544     TABLE_get_column_info,
1545     TABLE_modify,
1546     TABLE_delete,
1547     TABLE_find_matching_rows
1548 };
1549
1550 UINT TABLE_CreateView( MSIDATABASE *db, LPCWSTR name, MSIVIEW **view )
1551 {
1552     MSITABLEVIEW *tv ;
1553     UINT r, sz, column_count;
1554     MSICOLUMNINFO *columns;
1555
1556     TRACE("%p %s %p\n", db, debugstr_w(name), view );
1557
1558     /* get the number of columns in this table */
1559     column_count = 0;
1560     r = get_tablecolumns( db, name, NULL, &column_count );
1561     if( r != ERROR_SUCCESS )
1562         return r;
1563
1564     /* if there's no columns, there's no table */
1565     if( column_count == 0 )
1566         return ERROR_INVALID_PARAMETER;
1567
1568     TRACE("Table found\n");
1569
1570     sz = sizeof *tv + lstrlenW(name)*sizeof name[0] ;
1571     tv = msi_alloc_zero( sz );
1572     if( !tv )
1573         return ERROR_FUNCTION_FAILED;
1574     
1575     columns = msi_alloc( column_count*sizeof (MSICOLUMNINFO));
1576     if( !columns )
1577     {
1578         msi_free( tv );
1579         return ERROR_FUNCTION_FAILED;
1580     }
1581
1582     r = get_tablecolumns( db, name, columns, &column_count );
1583     if( r != ERROR_SUCCESS )
1584     {
1585         msi_free( columns );
1586         msi_free( tv );
1587         return ERROR_FUNCTION_FAILED;
1588     }
1589
1590     TRACE("Table has %d columns\n", column_count);
1591
1592     /* fill the structure */
1593     tv->view.ops = &table_ops;
1594     tv->db = db;
1595     tv->columns = columns;
1596     tv->num_cols = column_count;
1597     tv->table = NULL;
1598     tv->row_size = msi_table_get_row_size( columns, column_count );
1599
1600     TRACE("%s one row is %d bytes\n", debugstr_w(name), tv->row_size );
1601
1602     *view = (MSIVIEW*) tv;
1603     lstrcpyW( tv->name, name );
1604
1605     return ERROR_SUCCESS;
1606 }
1607
1608 UINT MSI_CommitTables( MSIDATABASE *db )
1609 {
1610     UINT r;
1611     MSITABLE *table = NULL;
1612
1613     TRACE("%p\n",db);
1614
1615     r = save_string_table( db );
1616     if( r != ERROR_SUCCESS )
1617     {
1618         WARN("failed to save string table r=%08x\n",r);
1619         return r;
1620     }
1621
1622     LIST_FOR_EACH_ENTRY( table, &db->tables, MSITABLE, entry )
1623     {
1624         r = save_table( db, table );
1625         if( r != ERROR_SUCCESS )
1626         {
1627             WARN("failed to save table %s (r=%08x)\n",
1628                   debugstr_w(table->name), r);
1629             return r;
1630         }
1631     }
1632
1633     /* force everything to reload next time */
1634     free_cached_tables( db );
1635
1636     return ERROR_SUCCESS;
1637 }
1638
1639 MSICONDITION MSI_DatabaseIsTablePersistent( MSIDATABASE *db, LPCWSTR table )
1640 {
1641     if (!table)
1642         return MSICONDITION_ERROR;
1643
1644     return MSICONDITION_FALSE;
1645 }
1646
1647 static MSIRECORD *msi_get_transform_record( MSITABLEVIEW *tv, string_table *st, USHORT *rawdata )
1648 {
1649     UINT i, val, ofs = 0;
1650     USHORT mask = *rawdata++;
1651     MSICOLUMNINFO *columns = tv->columns;
1652     MSIRECORD *rec;
1653
1654     rec = MSI_CreateRecord( tv->num_cols );
1655     if( !rec )
1656         return rec;
1657
1658     TRACE("row -> \n");
1659     for( i=0; i<tv->num_cols; i++ )
1660     {
1661         UINT n = bytes_per_column( &columns[i] );
1662
1663         if ( (mask&1) && (i>=(mask>>8)) )
1664             break;
1665         /* all keys must be present */
1666         if ( (~mask&1) && (~columns[i].type & MSITYPE_KEY) && ((1<<i) & ~mask) )
1667             continue;
1668
1669         switch( n )
1670         {
1671         case 2:
1672             val = rawdata[ofs];
1673             if( (columns[i].type & MSITYPE_STRING) &&
1674                 ! MSITYPE_IS_BINARY(tv->columns[i].type) )
1675             {
1676                 LPCWSTR sval = msi_string_lookup_id( st, val );
1677                 MSI_RecordSetStringW( rec, i+1, sval );
1678                 TRACE(" field %d [%s]\n", i+1, debugstr_w(sval));
1679             }
1680             else
1681             {
1682                 if (val)
1683                     MSI_RecordSetInteger( rec, i+1, val^0x8000 );
1684                 TRACE(" field %d [0x%04x]\n", i+1, val );
1685             }
1686             break;
1687         case 4:
1688             val = (rawdata[ofs] + (rawdata[ofs + 1]<<16));
1689             if (val)
1690                 MSI_RecordSetInteger( rec, i+1, val^0x80000000 );
1691             TRACE(" field %d [0x%08x]\n", i+1, val );
1692             break;
1693         default:
1694             ERR("oops - unknown column width %d\n", n);
1695             break;
1696         }
1697         ofs += n/2;
1698     }
1699     return rec;
1700 }
1701
1702 static void dump_record( MSIRECORD *rec )
1703 {
1704     UINT i, n;
1705
1706     n = MSI_RecordGetFieldCount( rec );
1707     for( i=1; i<=n; i++ )
1708     {
1709         LPCWSTR sval = MSI_RecordGetString( rec, i );
1710
1711         if( MSI_RecordIsNull( rec, i ) )
1712             TRACE("row -> []\n");
1713         else if( (sval = MSI_RecordGetString( rec, i )) )
1714             TRACE("row -> [%s]\n", debugstr_w(sval));
1715         else
1716             TRACE("row -> [0x%08x]\n", MSI_RecordGetInteger( rec, i ) );
1717     }
1718 }
1719
1720 static void dump_table( string_table *st, USHORT *rawdata, UINT rawsize )
1721 {
1722     LPCWSTR sval;
1723     UINT i;
1724
1725     for( i=0; i<(rawsize/2); i++ )
1726     {
1727         sval = msi_string_lookup_id( st, rawdata[i] );
1728         MESSAGE(" %04x %s\n", rawdata[i], debugstr_w(sval) );
1729     }
1730 }
1731
1732 static UINT* msi_record_to_row( MSITABLEVIEW *tv, MSIRECORD *rec )
1733 {
1734     LPCWSTR str;
1735     UINT i, r, *data;
1736
1737     data = msi_alloc( tv->num_cols *sizeof (UINT) );
1738     for( i=0; i<tv->num_cols; i++ )
1739     {
1740         data[i] = 0;
1741
1742         if ( ~tv->columns[i].type & MSITYPE_KEY )
1743             continue;
1744
1745         /* turn the transform column value into a row value */
1746         if ( ( tv->columns[i].type & MSITYPE_STRING ) &&
1747              ! MSITYPE_IS_BINARY(tv->columns[i].type) )
1748         {
1749             str = MSI_RecordGetString( rec, i+1 );
1750             r = msi_string2idW( tv->db->strings, str, &data[i] );
1751
1752             /* if there's no matching string in the string table,
1753                these keys can't match any record, so fail now. */
1754             if( ERROR_SUCCESS != r )
1755             {
1756                 msi_free( data );
1757                 return NULL;
1758             }
1759         }
1760         else
1761             data[i] = MSI_RecordGetInteger( rec, i+1 );
1762     }
1763     return data;
1764 }
1765
1766 static UINT msi_row_matches( MSITABLEVIEW *tv, UINT row, UINT *data )
1767 {
1768     UINT i, r, x, ret = ERROR_FUNCTION_FAILED;
1769
1770     for( i=0; i<tv->num_cols; i++ )
1771     {
1772         if ( ~tv->columns[i].type & MSITYPE_KEY )
1773             continue;
1774
1775         /* turn the transform column value into a row value */
1776         r = TABLE_fetch_int( &tv->view, row, i+1, &x );
1777         if ( r != ERROR_SUCCESS )
1778         {
1779             ERR("TABLE_fetch_int shouldn't fail here\n");
1780             break;
1781         }
1782
1783         /* if this key matches, move to the next column */
1784         if ( x != data[i] )
1785         {
1786             ret = ERROR_FUNCTION_FAILED;
1787             break;
1788         }
1789
1790         ret = ERROR_SUCCESS;
1791     }
1792
1793     return ret;
1794 }
1795
1796 static UINT msi_table_find_row( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *row )
1797 {
1798     UINT i, r = ERROR_FUNCTION_FAILED, *data;
1799
1800     data = msi_record_to_row( tv, rec );
1801     if( !data )
1802         return r;
1803     for( i=0; i<tv->table->row_count; i++ )
1804     {
1805         r = msi_row_matches( tv, i, data );
1806         if( r == ERROR_SUCCESS )
1807         {
1808             *row = i;
1809             break;
1810         }
1811     }
1812     msi_free( data );
1813     return r;
1814 }
1815
1816 static UINT msi_delete_row( MSITABLEVIEW *tv, UINT row )
1817 {
1818     UINT i;
1819     for( i=1; i<=tv->num_cols; i++ )
1820         tv->view.ops->set_int( &tv->view, row, i, 0 );
1821     return ERROR_SUCCESS;
1822 }
1823
1824 static UINT msi_table_load_transform( MSIDATABASE *db, IStorage *stg,
1825                                       string_table *st, LPCWSTR name )
1826 {
1827     UINT rawsize = 0;
1828     USHORT *rawdata = NULL;
1829     MSITABLEVIEW *tv = NULL;
1830     UINT r, n, sz, i, mask;
1831     MSIRECORD *rec = NULL;
1832     UINT colcol = 0;
1833
1834     TRACE("%p %p %p %s\n", db, stg, st, debugstr_w(name) );
1835
1836     read_stream_data( stg, name, &rawdata, &rawsize );
1837     if ( !rawdata )
1838     {
1839         TRACE("table %s empty\n", debugstr_w(name) );
1840         return ERROR_INVALID_TABLE;
1841     }
1842
1843     /* create a table view */
1844     r = TABLE_CreateView( db, name, (MSIVIEW**) &tv );
1845     if( r != ERROR_SUCCESS )
1846         goto err;
1847
1848     r = tv->view.ops->execute( &tv->view, NULL );
1849     if( r != ERROR_SUCCESS )
1850         goto err;
1851
1852     /* read the transform data */
1853     r = ERROR_FUNCTION_FAILED;
1854     read_stream_data( stg, name, &rawdata, &rawsize );
1855     if( !rawdata || (rawsize < 2) )
1856     {
1857         ERR("odd sized transform for table %s\n", debugstr_w(name));
1858         goto err;
1859     }
1860
1861     TRACE("name = %s columns = %u row_size = %u raw size = %u\n",
1862           debugstr_w(name), tv->num_cols, tv->row_size, rawsize );
1863
1864     /* interpret the data */
1865     r = ERROR_SUCCESS;
1866     for( n=0; n < (rawsize/2);  )
1867     {
1868         mask = rawdata[n];
1869
1870         if (mask&1)
1871         {
1872             /*
1873              * if the low bit is set, columns are continuous and
1874              * the number of columns is specified in the high byte
1875              */
1876             sz = 2 + tv->row_size;
1877         }
1878         else
1879         {
1880             /*
1881              * If the low bit is not set, rowdata[n] is a bitmask.
1882              * Excepting for key fields, which are always present,
1883              *  each bit indicates that a field is present in the transform record.
1884              *
1885              * rawdata[n] == 0 is a special case ... only the keys will be present
1886              * and it means that this row should be deleted.
1887              */
1888             sz = 2;
1889             for( i=0; i<tv->num_cols; i++ )
1890             {
1891                 if( (tv->columns[i].type & MSITYPE_KEY) || ((1<<i)&mask))
1892                     sz += bytes_per_column( &tv->columns[i] );
1893             }
1894         }
1895
1896         /* check we didn't run of the end of the table */
1897         if ( (n+sz) > rawsize )
1898         {
1899             ERR("borked.\n");
1900             dump_table( st, rawdata, rawsize );
1901             break;
1902         }
1903
1904         rec = msi_get_transform_record( tv, st, &rawdata[n] );
1905         if (rec)
1906         {
1907             UINT row = 0;
1908
1909             r = msi_table_find_row( tv, rec, &row );
1910
1911             if( rawdata[n] & 1)
1912             {
1913                 TRACE("insert [%d]: \n", row);
1914
1915                 /*
1916                  * Native msi seems writes nul into the
1917                  * Number (2nd) column of the _Columns table.
1918                  * Not sure that it's deliberate...
1919                  */
1920                 if (!lstrcmpW(name, szColumns))
1921                 {
1922                     if ( MSI_RecordIsNull( rec, 2 ) )
1923                         MSI_RecordSetInteger( rec, 2, ++colcol );
1924                     else
1925                         ERR("_Columns has non-null data...\n");
1926                 }
1927
1928                 TABLE_insert_row( &tv->view, rec );
1929             }
1930             else if( mask & 0xff )
1931             {
1932                 TRACE("modify [%d]: \n", row);
1933                 msi_table_modify_row( tv, rec, row, mask );
1934             }
1935             else
1936             {
1937                 TRACE("delete [%d]: \n", row);
1938                 msi_delete_row( tv, row );
1939             }
1940             if( TRACE_ON(msidb) ) dump_record( rec );
1941             msiobj_release( &rec->hdr );
1942         }
1943
1944         n += sz/2;
1945         
1946     }
1947
1948 err:
1949     /* no need to free the table, it's associated with the database */
1950     msi_free( rawdata );
1951     if( tv )
1952         tv->view.ops->delete( &tv->view );
1953
1954     return ERROR_SUCCESS;
1955 }
1956
1957 /*
1958  * msi_table_apply_transform
1959  *
1960  * Enumerate the table transforms in a transform storage and apply each one.
1961  */
1962 UINT msi_table_apply_transform( MSIDATABASE *db, IStorage *stg )
1963 {
1964     IEnumSTATSTG *stgenum = NULL;
1965     HRESULT r;
1966     STATSTG stat;
1967     ULONG count;
1968     WCHAR name[0x40];
1969     string_table *strings;
1970     UINT ret = ERROR_FUNCTION_FAILED;
1971
1972     TRACE("%p %p\n", db, stg );
1973
1974     strings = load_string_table( stg );
1975     if( !strings )
1976         goto end;
1977
1978     r = IStorage_EnumElements( stg, 0, NULL, 0, &stgenum );
1979     if( FAILED( r ) )
1980         goto end;
1981
1982     /*
1983      * Apply _Tables and _Coluimns transforms first so that
1984      * the table metadata is correct, and empty tables exist.
1985      */
1986     ret = msi_table_load_transform( db, stg, strings, szTables );
1987     if (ret != ERROR_SUCCESS && ret != ERROR_INVALID_TABLE)
1988         goto end;
1989
1990     ret = msi_table_load_transform( db, stg, strings, szColumns );
1991     if (ret != ERROR_SUCCESS && ret != ERROR_INVALID_TABLE)
1992         goto end;
1993
1994     ret = ERROR_SUCCESS;
1995
1996     while( r == ERROR_SUCCESS )
1997     {
1998         count = 0;
1999         r = IEnumSTATSTG_Next( stgenum, 1, &stat, &count );
2000         if( FAILED( r ) || !count )
2001             break;
2002
2003         decode_streamname( stat.pwcsName, name );
2004         if ( name[0] != 0x4840 )
2005             continue;
2006
2007         TRACE("transform contains stream %s\n", debugstr_w(name));
2008
2009         if ( !lstrcmpW( name+1, szStringPool ) ||
2010              !lstrcmpW( name+1, szStringData ) ||
2011              !lstrcmpW( name+1, szColumns ) ||
2012              !lstrcmpW( name+1, szTables ) )
2013             continue;
2014
2015         ret = msi_table_load_transform( db, stg, strings, name+1 );
2016     }
2017
2018     if ( ret == ERROR_SUCCESS )
2019     {
2020         MSITRANSFORM *t;
2021
2022         t = msi_alloc( sizeof *t );
2023         t->stg = stg;
2024         IStorage_AddRef( stg );
2025         list_add_tail( &db->transforms, &t->entry );
2026     }
2027
2028 end:
2029     if ( stgenum )
2030         IEnumSTATSTG_Release( stgenum );
2031     if ( strings )
2032         msi_destroy_stringtable( strings );
2033
2034     return ret;
2035 }
2036
2037 void msi_free_transforms( MSIDATABASE *db )
2038 {
2039     while( !list_empty( &db->transforms ) )
2040     {
2041         MSITRANSFORM *t = LIST_ENTRY( list_head( &db->transforms ),
2042                                       MSITRANSFORM, entry );
2043         list_remove( &t->entry );
2044         IStorage_Release( t->stg );
2045         msi_free( t );
2046     }
2047 }