setupapi: Add support for .inf files in utf-8 format.
[wine] / dlls / setupapi / parser.c
1 /*
2  * INF file parsing
3  *
4  * Copyright 2002 Alexandre Julliard 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 "config.h"
22 #include "wine/port.h"
23
24 #include <assert.h>
25 #include <limits.h>
26 #include <stdarg.h>
27 #include <string.h>
28 #include <stdlib.h>
29
30 #include "windef.h"
31 #include "winbase.h"
32 #include "wingdi.h"
33 #include "winuser.h"
34 #include "winnls.h"
35 #include "winreg.h"
36 #include "winternl.h"
37 #include "winerror.h"
38 #include "setupapi.h"
39 #include "setupapi_private.h"
40
41 #include "wine/unicode.h"
42 #include "wine/debug.h"
43
44 WINE_DEFAULT_DEBUG_CHANNEL(setupapi);
45
46 #define CONTROL_Z  '\x1a'
47 #define MAX_SECTION_NAME_LEN  255
48 #define MAX_FIELD_LEN         511  /* larger fields get silently truncated */
49 /* actual string limit is MAX_INF_STRING_LENGTH+1 (plus terminating null) under Windows */
50 #define MAX_STRING_LEN        (MAX_INF_STRING_LENGTH+1)
51
52 /* inf file structure definitions */
53
54 struct field
55 {
56     const WCHAR *text;         /* field text */
57 };
58
59 struct line
60 {
61     int first_field;           /* index of first field in field array */
62     int nb_fields;             /* number of fields in line */
63     int key_field;             /* index of field for key or -1 if no key */
64 };
65
66 struct section
67 {
68     const WCHAR *name;         /* section name */
69     unsigned int nb_lines;     /* number of used lines */
70     unsigned int alloc_lines;  /* total number of allocated lines in array below */
71     struct line  lines[16];    /* lines information (grown dynamically, 16 is initial size) */
72 };
73
74 struct inf_file
75 {
76     struct inf_file *next;            /* next appended file */
77     WCHAR           *strings;         /* buffer for string data (section names and field values) */
78     WCHAR           *string_pos;      /* position of next available string in buffer */
79     unsigned int     nb_sections;     /* number of used sections */
80     unsigned int     alloc_sections;  /* total number of allocated section pointers */
81     struct section **sections;        /* section pointers array */
82     unsigned int     nb_fields;
83     unsigned int     alloc_fields;
84     struct field    *fields;
85     int              strings_section; /* index of [Strings] section or -1 if none */
86     WCHAR           *filename;        /* filename of the INF */
87 };
88
89 /* parser definitions */
90
91 enum parser_state
92 {
93     LINE_START,      /* at beginning of a line */
94     SECTION_NAME,    /* parsing a section name */
95     KEY_NAME,        /* parsing a key name */
96     VALUE_NAME,      /* parsing a value name */
97     EOL_BACKSLASH,   /* backslash at end of line */
98     QUOTES,          /* inside quotes */
99     LEADING_SPACES,  /* leading spaces */
100     TRAILING_SPACES, /* trailing spaces */
101     COMMENT,         /* inside a comment */
102     NB_PARSER_STATES
103 };
104
105 struct parser
106 {
107     const WCHAR      *start;        /* start position of item being parsed */
108     const WCHAR      *end;          /* end of buffer */
109     struct inf_file  *file;         /* file being built */
110     enum parser_state state;        /* current parser state */
111     enum parser_state stack[4];     /* state stack */
112     int               stack_pos;    /* current pos in stack */
113
114     int               cur_section;  /* index of section being parsed*/
115     struct line      *line;         /* current line */
116     unsigned int      line_pos;     /* current line position in file */
117     unsigned int      error;        /* error code */
118     unsigned int      token_len;    /* current token len */
119     WCHAR token[MAX_FIELD_LEN+1];   /* current token */
120 };
121
122 typedef const WCHAR * (*parser_state_func)( struct parser *parser, const WCHAR *pos );
123
124 /* parser state machine functions */
125 static const WCHAR *line_start_state( struct parser *parser, const WCHAR *pos );
126 static const WCHAR *section_name_state( struct parser *parser, const WCHAR *pos );
127 static const WCHAR *key_name_state( struct parser *parser, const WCHAR *pos );
128 static const WCHAR *value_name_state( struct parser *parser, const WCHAR *pos );
129 static const WCHAR *eol_backslash_state( struct parser *parser, const WCHAR *pos );
130 static const WCHAR *quotes_state( struct parser *parser, const WCHAR *pos );
131 static const WCHAR *leading_spaces_state( struct parser *parser, const WCHAR *pos );
132 static const WCHAR *trailing_spaces_state( struct parser *parser, const WCHAR *pos );
133 static const WCHAR *comment_state( struct parser *parser, const WCHAR *pos );
134
135 static const parser_state_func parser_funcs[NB_PARSER_STATES] =
136 {
137     line_start_state,      /* LINE_START */
138     section_name_state,    /* SECTION_NAME */
139     key_name_state,        /* KEY_NAME */
140     value_name_state,      /* VALUE_NAME */
141     eol_backslash_state,   /* EOL_BACKSLASH */
142     quotes_state,          /* QUOTES */
143     leading_spaces_state,  /* LEADING_SPACES */
144     trailing_spaces_state, /* TRAILING_SPACES */
145     comment_state          /* COMMENT */
146 };
147
148
149 /* Unicode string constants */
150 static const WCHAR Version[]    = {'V','e','r','s','i','o','n',0};
151 static const WCHAR Signature[]  = {'S','i','g','n','a','t','u','r','e',0};
152 static const WCHAR Chicago[]    = {'$','C','h','i','c','a','g','o','$',0};
153 static const WCHAR WindowsNT[]  = {'$','W','i','n','d','o','w','s',' ','N','T','$',0};
154 static const WCHAR Windows95[]  = {'$','W','i','n','d','o','w','s',' ','9','5','$',0};
155 static const WCHAR LayoutFile[] = {'L','a','y','o','u','t','F','i','l','e',0};
156
157 /* extend an array, allocating more memory if necessary */
158 static void *grow_array( void *array, unsigned int *count, size_t elem )
159 {
160     void *new_array;
161     unsigned int new_count = *count + *count / 2;
162     if (new_count < 32) new_count = 32;
163
164     if (array)
165         new_array = HeapReAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, array, new_count * elem );
166     else
167         new_array = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, new_count * elem );
168
169     if (new_array)
170         *count = new_count;
171     else
172         HeapFree( GetProcessHeap(), 0, array );
173     return new_array;
174 }
175
176
177 /* get the directory of the inf file (as counted string, not null-terminated) */
178 static const WCHAR *get_inf_dir( struct inf_file *file, unsigned int *len )
179 {
180     const WCHAR *p = strrchrW( file->filename, '\\' );
181     *len = p ? (p + 1 - file->filename) : 0;
182     return file->filename;
183 }
184
185
186 /* find a section by name */
187 static int find_section( struct inf_file *file, const WCHAR *name )
188 {
189     unsigned int i;
190
191     for (i = 0; i < file->nb_sections; i++)
192         if (!strcmpiW( name, file->sections[i]->name )) return i;
193     return -1;
194 }
195
196
197 /* find a line by name */
198 static struct line *find_line( struct inf_file *file, int section_index, const WCHAR *name )
199 {
200     struct section *section;
201     struct line *line;
202     int i;
203
204     if (section_index < 0 || section_index >= file->nb_sections) return NULL;
205     section = file->sections[section_index];
206     for (i = 0, line = section->lines; i < section->nb_lines; i++, line++)
207     {
208         if (line->key_field == -1) continue;
209         if (!strcmpiW( name, file->fields[line->key_field].text )) return line;
210     }
211     return NULL;
212 }
213
214
215 /* add a section to the file and return the section index */
216 static int add_section( struct inf_file *file, const WCHAR *name )
217 {
218     struct section *section;
219
220     if (file->nb_sections >= file->alloc_sections)
221     {
222         if (!(file->sections = grow_array( file->sections, &file->alloc_sections,
223                                            sizeof(file->sections[0]) ))) return -1;
224     }
225     if (!(section = HeapAlloc( GetProcessHeap(), 0, sizeof(*section) ))) return -1;
226     section->name        = name;
227     section->nb_lines    = 0;
228     section->alloc_lines = sizeof(section->lines)/sizeof(section->lines[0]);
229     file->sections[file->nb_sections] = section;
230     return file->nb_sections++;
231 }
232
233
234 /* add a line to a given section */
235 static struct line *add_line( struct inf_file *file, int section_index )
236 {
237     struct section *section;
238     struct line *line;
239
240     assert( section_index >= 0 && section_index < file->nb_sections );
241
242     section = file->sections[section_index];
243     if (section->nb_lines == section->alloc_lines)  /* need to grow the section */
244     {
245         int size = sizeof(*section) - sizeof(section->lines) + 2*section->alloc_lines*sizeof(*line);
246         if (!(section = HeapReAlloc( GetProcessHeap(), 0, section, size ))) return NULL;
247         section->alloc_lines *= 2;
248         file->sections[section_index] = section;
249     }
250     line = &section->lines[section->nb_lines++];
251     line->first_field = file->nb_fields;
252     line->nb_fields   = 0;
253     line->key_field   = -1;
254     return line;
255 }
256
257
258 /* retrieve a given line from section/line index */
259 static inline struct line *get_line( struct inf_file *file, unsigned int section_index,
260                                      unsigned int line_index )
261 {
262     struct section *section;
263
264     if (section_index >= file->nb_sections) return NULL;
265     section = file->sections[section_index];
266     if (line_index >= section->nb_lines) return NULL;
267     return &section->lines[line_index];
268 }
269
270
271 /* retrieve a given field from section/line/field index */
272 static struct field *get_field( struct inf_file *file, int section_index, int line_index,
273                                 int field_index )
274 {
275     struct line *line = get_line( file, section_index, line_index );
276
277     if (!line) return NULL;
278     if (!field_index)  /* get the key */
279     {
280         if (line->key_field == -1) return NULL;
281         return &file->fields[line->key_field];
282     }
283     field_index--;
284     if (field_index >= line->nb_fields) return NULL;
285     return &file->fields[line->first_field + field_index];
286 }
287
288
289 /* allocate a new field, growing the array if necessary */
290 static struct field *add_field( struct inf_file *file, const WCHAR *text )
291 {
292     struct field *field;
293
294     if (file->nb_fields >= file->alloc_fields)
295     {
296         if (!(file->fields = grow_array( file->fields, &file->alloc_fields,
297                                          sizeof(file->fields[0]) ))) return NULL;
298     }
299     field = &file->fields[file->nb_fields++];
300     field->text = text;
301     return field;
302 }
303
304
305 /* retrieve the string substitution for a directory id */
306 static const WCHAR *get_dirid_subst( struct inf_file *file, int dirid, unsigned int *len )
307 {
308     const WCHAR *ret;
309
310     if (dirid == DIRID_SRCPATH) return get_inf_dir( file, len );
311     ret = DIRID_get_string( dirid );
312     if (ret) *len = strlenW(ret);
313     return ret;
314 }
315
316
317 /* retrieve the string substitution for a given string, or NULL if not found */
318 /* if found, len is set to the substitution length */
319 static const WCHAR *get_string_subst( struct inf_file *file, const WCHAR *str, unsigned int *len )
320 {
321     static const WCHAR percent = '%';
322
323     struct section *strings_section;
324     struct line *line;
325     struct field *field;
326     unsigned int i;
327     int dirid;
328     WCHAR *dirid_str, *end;
329     const WCHAR *ret = NULL;
330
331     if (!*len)  /* empty string (%%) is replaced by single percent */
332     {
333         *len = 1;
334         return &percent;
335     }
336     if (file->strings_section == -1) goto not_found;
337     strings_section = file->sections[file->strings_section];
338     for (i = 0, line = strings_section->lines; i < strings_section->nb_lines; i++, line++)
339     {
340         if (line->key_field == -1) continue;
341         if (strncmpiW( str, file->fields[line->key_field].text, *len )) continue;
342         if (!file->fields[line->key_field].text[*len]) break;
343     }
344     if (i == strings_section->nb_lines || !line->nb_fields) goto not_found;
345     field = &file->fields[line->first_field];
346     *len = strlenW( field->text );
347     return field->text;
348
349  not_found:  /* check for integer id */
350     if ((dirid_str = HeapAlloc( GetProcessHeap(), 0, (*len+1) * sizeof(WCHAR) )))
351     {
352         memcpy( dirid_str, str, *len * sizeof(WCHAR) );
353         dirid_str[*len] = 0;
354         dirid = strtolW( dirid_str, &end, 10 );
355         if (!*end) ret = get_dirid_subst( file, dirid, len );
356         HeapFree( GetProcessHeap(), 0, dirid_str );
357         return ret;
358     }
359     return NULL;
360 }
361
362
363 /* do string substitutions on the specified text */
364 /* the buffer is assumed to be large enough */
365 /* returns necessary length not including terminating null */
366 unsigned int PARSER_string_substW( struct inf_file *file, const WCHAR *text, WCHAR *buffer,
367                                    unsigned int size )
368 {
369     const WCHAR *start, *subst, *p;
370     unsigned int len, total = 0;
371     int inside = 0;
372
373     if (!buffer) size = MAX_STRING_LEN + 1;
374     for (p = start = text; *p; p++)
375     {
376         if (*p != '%') continue;
377         inside = !inside;
378         if (inside)  /* start of a %xx% string */
379         {
380             len = p - start;
381             if (len > size - 1) len = size - 1;
382             if (buffer) memcpy( buffer + total, start, len * sizeof(WCHAR) );
383             total += len;
384             size -= len;
385             start = p;
386         }
387         else /* end of the %xx% string, find substitution */
388         {
389             len = p - start - 1;
390             subst = get_string_subst( file, start + 1, &len );
391             if (!subst)
392             {
393                 subst = start;
394                 len = p - start + 1;
395             }
396             if (len > size - 1) len = size - 1;
397             if (buffer) memcpy( buffer + total, subst, len * sizeof(WCHAR) );
398             total += len;
399             size -= len;
400             start = p + 1;
401         }
402     }
403
404     if (start != p) /* unfinished string, copy it */
405     {
406         len = p - start;
407         if (len > size - 1) len = size - 1;
408         if (buffer) memcpy( buffer + total, start, len * sizeof(WCHAR) );
409         total += len;
410     }
411     if (buffer && size) buffer[total] = 0;
412     return total;
413 }
414
415
416 /* do string substitutions on the specified text */
417 /* the buffer is assumed to be large enough */
418 /* returns necessary length not including terminating null */
419 unsigned int PARSER_string_substA( struct inf_file *file, const WCHAR *text, char *buffer,
420                                    unsigned int size )
421 {
422     WCHAR buffW[MAX_STRING_LEN+1];
423     DWORD ret;
424
425     unsigned int len = PARSER_string_substW( file, text, buffW, sizeof(buffW)/sizeof(WCHAR) );
426     if (!buffer) RtlUnicodeToMultiByteSize( &ret, buffW, len * sizeof(WCHAR) );
427     else
428     {
429         RtlUnicodeToMultiByteN( buffer, size-1, &ret, buffW, len * sizeof(WCHAR) );
430         buffer[ret] = 0;
431     }
432     return ret;
433 }
434
435
436 /* push some string data into the strings buffer */
437 static WCHAR *push_string( struct inf_file *file, const WCHAR *string )
438 {
439     WCHAR *ret = file->string_pos;
440     strcpyW( ret, string );
441     file->string_pos += strlenW( ret ) + 1;
442     return ret;
443 }
444
445
446 /* push the current state on the parser stack */
447 static inline void push_state( struct parser *parser, enum parser_state state )
448 {
449     assert( parser->stack_pos < sizeof(parser->stack)/sizeof(parser->stack[0]) );
450     parser->stack[parser->stack_pos++] = state;
451 }
452
453
454 /* pop the current state */
455 static inline void pop_state( struct parser *parser )
456 {
457     assert( parser->stack_pos );
458     parser->state = parser->stack[--parser->stack_pos];
459 }
460
461
462 /* set the parser state and return the previous one */
463 static inline enum parser_state set_state( struct parser *parser, enum parser_state state )
464 {
465     enum parser_state ret = parser->state;
466     parser->state = state;
467     return ret;
468 }
469
470
471 /* check if the pointer points to an end of file */
472 static inline int is_eof( struct parser *parser, const WCHAR *ptr )
473 {
474     return (ptr >= parser->end || *ptr == CONTROL_Z);
475 }
476
477
478 /* check if the pointer points to an end of line */
479 static inline int is_eol( struct parser *parser, const WCHAR *ptr )
480 {
481     return (ptr >= parser->end || *ptr == CONTROL_Z || *ptr == '\n');
482 }
483
484
485 /* push data from current token start up to pos into the current token */
486 static int push_token( struct parser *parser, const WCHAR *pos )
487 {
488     int len = pos - parser->start;
489     const WCHAR *src = parser->start;
490     WCHAR *dst = parser->token + parser->token_len;
491
492     if (len > MAX_FIELD_LEN - parser->token_len) len = MAX_FIELD_LEN - parser->token_len;
493
494     parser->token_len += len;
495     for ( ; len > 0; len--, dst++, src++) *dst = *src ? *src : ' ';
496     *dst = 0;
497     parser->start = pos;
498     return 0;
499 }
500
501
502 /* add a section with the current token as name */
503 static int add_section_from_token( struct parser *parser )
504 {
505     int section_index;
506
507     if (parser->token_len > MAX_SECTION_NAME_LEN)
508     {
509         parser->error = ERROR_SECTION_NAME_TOO_LONG;
510         return -1;
511     }
512     if ((section_index = find_section( parser->file, parser->token )) == -1)
513     {
514         /* need to create a new one */
515         const WCHAR *name = push_string( parser->file, parser->token );
516         if ((section_index = add_section( parser->file, name )) == -1)
517         {
518             parser->error = ERROR_NOT_ENOUGH_MEMORY;
519             return -1;
520         }
521     }
522     parser->token_len = 0;
523     parser->cur_section = section_index;
524     return section_index;
525 }
526
527
528 /* add a field containing the current token to the current line */
529 static struct field *add_field_from_token( struct parser *parser, int is_key )
530 {
531     struct field *field;
532     WCHAR *text;
533
534     if (!parser->line)  /* need to start a new line */
535     {
536         if (parser->cur_section == -1)  /* got a line before the first section */
537         {
538             parser->error = ERROR_EXPECTED_SECTION_NAME;
539             return NULL;
540         }
541         if (!(parser->line = add_line( parser->file, parser->cur_section ))) goto error;
542     }
543     else assert(!is_key);
544
545     text = push_string( parser->file, parser->token );
546     if ((field = add_field( parser->file, text )))
547     {
548         if (!is_key) parser->line->nb_fields++;
549         else
550         {
551             /* replace first field by key field */
552             parser->line->key_field = parser->line->first_field;
553             parser->line->first_field++;
554         }
555         parser->token_len = 0;
556         return field;
557     }
558  error:
559     parser->error = ERROR_NOT_ENOUGH_MEMORY;
560     return NULL;
561 }
562
563
564 /* close the current line and prepare for parsing a new one */
565 static void close_current_line( struct parser *parser )
566 {
567     struct line *cur_line = parser->line;
568
569     if (cur_line)
570     {
571         /* if line has a single field and no key, the field is the key too */
572         if (cur_line->nb_fields == 1 && cur_line->key_field == -1)
573             cur_line->key_field = cur_line->first_field;
574     }
575     parser->line = NULL;
576 }
577
578
579 /* handler for parser LINE_START state */
580 static const WCHAR *line_start_state( struct parser *parser, const WCHAR *pos )
581 {
582     const WCHAR *p;
583
584     for (p = pos; !is_eof( parser, p ); p++)
585     {
586         switch(*p)
587         {
588         case '\n':
589             parser->line_pos++;
590             close_current_line( parser );
591             break;
592         case ';':
593             push_state( parser, LINE_START );
594             set_state( parser, COMMENT );
595             return p + 1;
596         case '[':
597             parser->start = p + 1;
598             set_state( parser, SECTION_NAME );
599             return p + 1;
600         default:
601             if (!isspaceW(*p))
602             {
603                 parser->start = p;
604                 set_state( parser, KEY_NAME );
605                 return p;
606             }
607             break;
608         }
609     }
610     close_current_line( parser );
611     return NULL;
612 }
613
614
615 /* handler for parser SECTION_NAME state */
616 static const WCHAR *section_name_state( struct parser *parser, const WCHAR *pos )
617 {
618     const WCHAR *p;
619
620     for (p = pos; !is_eol( parser, p ); p++)
621     {
622         if (*p == ']')
623         {
624             push_token( parser, p );
625             if (add_section_from_token( parser ) == -1) return NULL;
626             push_state( parser, LINE_START );
627             set_state( parser, COMMENT );  /* ignore everything else on the line */
628             return p + 1;
629         }
630     }
631     parser->error = ERROR_BAD_SECTION_NAME_LINE; /* unfinished section name */
632     return NULL;
633 }
634
635
636 /* handler for parser KEY_NAME state */
637 static const WCHAR *key_name_state( struct parser *parser, const WCHAR *pos )
638 {
639     const WCHAR *p, *token_end = parser->start;
640
641     for (p = pos; !is_eol( parser, p ); p++)
642     {
643         if (*p == ',') break;
644         switch(*p)
645         {
646
647          case '=':
648             push_token( parser, token_end );
649             if (!add_field_from_token( parser, 1 )) return NULL;
650             parser->start = p + 1;
651             push_state( parser, VALUE_NAME );
652             set_state( parser, LEADING_SPACES );
653             return p + 1;
654         case ';':
655             push_token( parser, token_end );
656             if (!add_field_from_token( parser, 0 )) return NULL;
657             push_state( parser, LINE_START );
658             set_state( parser, COMMENT );
659             return p + 1;
660         case '"':
661             push_token( parser, p );
662             parser->start = p + 1;
663             push_state( parser, KEY_NAME );
664             set_state( parser, QUOTES );
665             return p + 1;
666         case '\\':
667             push_token( parser, token_end );
668             parser->start = p;
669             push_state( parser, KEY_NAME );
670             set_state( parser, EOL_BACKSLASH );
671             return p;
672         default:
673             if (!isspaceW(*p)) token_end = p + 1;
674             else
675             {
676                 push_token( parser, p );
677                 push_state( parser, KEY_NAME );
678                 set_state( parser, TRAILING_SPACES );
679                 return p;
680             }
681             break;
682         }
683     }
684     push_token( parser, token_end );
685     set_state( parser, VALUE_NAME );
686     return p;
687 }
688
689
690 /* handler for parser VALUE_NAME state */
691 static const WCHAR *value_name_state( struct parser *parser, const WCHAR *pos )
692 {
693     const WCHAR *p, *token_end = parser->start;
694
695     for (p = pos; !is_eol( parser, p ); p++)
696     {
697         switch(*p)
698         {
699         case ';':
700             push_token( parser, token_end );
701             if (!add_field_from_token( parser, 0 )) return NULL;
702             push_state( parser, LINE_START );
703             set_state( parser, COMMENT );
704             return p + 1;
705         case ',':
706             push_token( parser, token_end );
707             if (!add_field_from_token( parser, 0 )) return NULL;
708             parser->start = p + 1;
709             push_state( parser, VALUE_NAME );
710             set_state( parser, LEADING_SPACES );
711             return p + 1;
712         case '"':
713             push_token( parser, p );
714             parser->start = p + 1;
715             push_state( parser, VALUE_NAME );
716             set_state( parser, QUOTES );
717             return p + 1;
718         case '\\':
719             push_token( parser, token_end );
720             parser->start = p;
721             push_state( parser, VALUE_NAME );
722             set_state( parser, EOL_BACKSLASH );
723             return p;
724         default:
725             if (!isspaceW(*p)) token_end = p + 1;
726             else
727             {
728                 push_token( parser, p );
729                 push_state( parser, VALUE_NAME );
730                 set_state( parser, TRAILING_SPACES );
731                 return p;
732             }
733             break;
734         }
735     }
736     push_token( parser, token_end );
737     if (!add_field_from_token( parser, 0 )) return NULL;
738     set_state( parser, LINE_START );
739     return p;
740 }
741
742
743 /* handler for parser EOL_BACKSLASH state */
744 static const WCHAR *eol_backslash_state( struct parser *parser, const WCHAR *pos )
745 {
746     const WCHAR *p;
747
748     for (p = pos; !is_eof( parser, p ); p++)
749     {
750         switch(*p)
751         {
752         case '\n':
753             parser->line_pos++;
754             parser->start = p + 1;
755             set_state( parser, LEADING_SPACES );
756             return p + 1;
757         case '\\':
758             continue;
759         case ';':
760             push_state( parser, EOL_BACKSLASH );
761             set_state( parser, COMMENT );
762             return p + 1;
763         default:
764             if (isspaceW(*p)) continue;
765             push_token( parser, p );
766             pop_state( parser );
767             return p;
768         }
769     }
770     parser->start = p;
771     pop_state( parser );
772     return p;
773 }
774
775
776 /* handler for parser QUOTES state */
777 static const WCHAR *quotes_state( struct parser *parser, const WCHAR *pos )
778 {
779     const WCHAR *p, *token_end = parser->start;
780
781     for (p = pos; !is_eol( parser, p ); p++)
782     {
783         if (*p == '"')
784         {
785             if (p+1 < parser->end && p[1] == '"')  /* double quotes */
786             {
787                 push_token( parser, p + 1 );
788                 parser->start = token_end = p + 2;
789                 p++;
790             }
791             else  /* end of quotes */
792             {
793                 push_token( parser, p );
794                 parser->start = p + 1;
795                 pop_state( parser );
796                 return p + 1;
797             }
798         }
799     }
800     push_token( parser, p );
801     pop_state( parser );
802     return p;
803 }
804
805
806 /* handler for parser LEADING_SPACES state */
807 static const WCHAR *leading_spaces_state( struct parser *parser, const WCHAR *pos )
808 {
809     const WCHAR *p;
810
811     for (p = pos; !is_eol( parser, p ); p++)
812     {
813         if (*p == '\\')
814         {
815             parser->start = p;
816             set_state( parser, EOL_BACKSLASH );
817             return p;
818         }
819         if (!isspaceW(*p)) break;
820     }
821     parser->start = p;
822     pop_state( parser );
823     return p;
824 }
825
826
827 /* handler for parser TRAILING_SPACES state */
828 static const WCHAR *trailing_spaces_state( struct parser *parser, const WCHAR *pos )
829 {
830     const WCHAR *p;
831
832     for (p = pos; !is_eol( parser, p ); p++)
833     {
834         if (*p == '\\')
835         {
836             set_state( parser, EOL_BACKSLASH );
837             return p;
838         }
839         if (!isspaceW(*p)) break;
840     }
841     pop_state( parser );
842     return p;
843 }
844
845
846 /* handler for parser COMMENT state */
847 static const WCHAR *comment_state( struct parser *parser, const WCHAR *pos )
848 {
849     const WCHAR *p = pos;
850
851     while (!is_eol( parser, p )) p++;
852     pop_state( parser );
853     return p;
854 }
855
856
857 /* parse a complete buffer */
858 static DWORD parse_buffer( struct inf_file *file, const WCHAR *buffer, const WCHAR *end,
859                            UINT *error_line )
860 {
861     static const WCHAR Strings[] = {'S','t','r','i','n','g','s',0};
862
863     struct parser parser;
864     const WCHAR *pos = buffer;
865
866     parser.start       = buffer;
867     parser.end         = end;
868     parser.file        = file;
869     parser.line        = NULL;
870     parser.state       = LINE_START;
871     parser.stack_pos   = 0;
872     parser.cur_section = -1;
873     parser.line_pos    = 1;
874     parser.error       = 0;
875     parser.token_len   = 0;
876
877     /* parser main loop */
878     while (pos) pos = (parser_funcs[parser.state])( &parser, pos );
879
880     /* trim excess buffer space */
881     if (file->alloc_sections > file->nb_sections)
882     {
883         file->sections = HeapReAlloc( GetProcessHeap(), 0, file->sections,
884                                       file->nb_sections * sizeof(file->sections[0]) );
885         file->alloc_sections = file->nb_sections;
886     }
887     if (file->alloc_fields > file->nb_fields)
888     {
889         file->fields = HeapReAlloc( GetProcessHeap(), 0, file->fields,
890                                     file->nb_fields * sizeof(file->fields[0]) );
891         file->alloc_fields = file->nb_fields;
892     }
893     file->strings = HeapReAlloc( GetProcessHeap(), HEAP_REALLOC_IN_PLACE_ONLY, file->strings,
894                                  (file->string_pos - file->strings) * sizeof(WCHAR) );
895
896     if (parser.error)
897     {
898         if (error_line) *error_line = parser.line_pos;
899         return parser.error;
900     }
901
902     /* find the [strings] section */
903     file->strings_section = find_section( file, Strings );
904     return 0;
905 }
906
907
908 /* append a child INF file to its parent list, in a thread-safe manner */
909 static void append_inf_file( struct inf_file *parent, struct inf_file *child )
910 {
911     struct inf_file **ppnext = &parent->next;
912     child->next = NULL;
913
914     for (;;)
915     {
916         struct inf_file *next = InterlockedCompareExchangePointer( (void **)ppnext, child, NULL );
917         if (!next) return;
918         ppnext = &next->next;
919     }
920 }
921
922
923 /***********************************************************************
924  *            parse_file
925  *
926  * parse an INF file.
927  */
928 static struct inf_file *parse_file( HANDLE handle, const WCHAR *class, UINT *error_line )
929 {
930     void *buffer;
931     DWORD err = 0;
932     struct inf_file *file;
933
934     DWORD size = GetFileSize( handle, NULL );
935     HANDLE mapping = CreateFileMappingW( handle, NULL, PAGE_READONLY, 0, size, NULL );
936     if (!mapping) return NULL;
937     buffer = MapViewOfFile( mapping, FILE_MAP_READ, 0, 0, size );
938     NtClose( mapping );
939     if (!buffer) return NULL;
940
941     if (class) FIXME( "class %s not supported yet\n", debugstr_w(class) );
942
943     if (!(file = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*file) )))
944     {
945         err = ERROR_NOT_ENOUGH_MEMORY;
946         goto done;
947     }
948
949     /* we won't need more strings space than the size of the file,
950      * so we can preallocate it here
951      */
952     if (!(file->strings = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) )))
953     {
954         err = ERROR_NOT_ENOUGH_MEMORY;
955         goto done;
956     }
957     file->string_pos = file->strings;
958     file->strings_section = -1;
959
960     if (!RtlIsTextUnicode( buffer, size, NULL ))
961     {
962         static const BYTE utf8_bom[3] = { 0xef, 0xbb, 0xbf };
963         WCHAR *new_buff;
964         UINT codepage = CP_ACP;
965         UINT offset = 0;
966
967         if (size > sizeof(utf8_bom) && !memcmp( buffer, utf8_bom, sizeof(utf8_bom) ))
968         {
969             codepage = CP_UTF8;
970             offset = sizeof(utf8_bom);
971         }
972
973         if ((new_buff = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) )))
974         {
975             DWORD len = MultiByteToWideChar( codepage, 0, (char *)buffer + offset,
976                                              size - offset, new_buff, size );
977             err = parse_buffer( file, new_buff, new_buff + len, error_line );
978             HeapFree( GetProcessHeap(), 0, new_buff );
979         }
980     }
981     else
982     {
983         WCHAR *new_buff = (WCHAR *)buffer;
984         /* UCS-16 files should start with the Unicode BOM; we should skip it */
985         if (*new_buff == 0xfeff)
986             new_buff++;
987         err = parse_buffer( file, new_buff, (WCHAR *)((char *)buffer + size), error_line );
988     }
989
990     if (!err)  /* now check signature */
991     {
992         int version_index = find_section( file, Version );
993         if (version_index != -1)
994         {
995             struct line *line = find_line( file, version_index, Signature );
996             if (line && line->nb_fields > 0)
997             {
998                 struct field *field = file->fields + line->first_field;
999                 if (!strcmpiW( field->text, Chicago )) goto done;
1000                 if (!strcmpiW( field->text, WindowsNT )) goto done;
1001                 if (!strcmpiW( field->text, Windows95 )) goto done;
1002             }
1003         }
1004         if (error_line) *error_line = 0;
1005         err = ERROR_WRONG_INF_STYLE;
1006     }
1007
1008  done:
1009     UnmapViewOfFile( buffer );
1010     if (err)
1011     {
1012         HeapFree( GetProcessHeap(), 0, file );
1013         SetLastError( err );
1014         file = NULL;
1015     }
1016     return file;
1017 }
1018
1019
1020 /***********************************************************************
1021  *            PARSER_get_inf_filename
1022  *
1023  * Retrieve the filename of an inf file.
1024  */
1025 const WCHAR *PARSER_get_inf_filename( HINF hinf )
1026 {
1027     struct inf_file *file = hinf;
1028     return file->filename;
1029 }
1030
1031
1032 /***********************************************************************
1033  *            PARSER_get_src_root
1034  *
1035  * Retrieve the source directory of an inf file.
1036  */
1037 WCHAR *PARSER_get_src_root( HINF hinf )
1038 {
1039     unsigned int len;
1040     const WCHAR *dir = get_inf_dir( hinf, &len );
1041     WCHAR *ret = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
1042     if (ret)
1043     {
1044         memcpy( ret, dir, len * sizeof(WCHAR) );
1045         ret[len] = 0;
1046     }
1047     return ret;
1048 }
1049
1050
1051 /***********************************************************************
1052  *            PARSER_get_dest_dir
1053  *
1054  * retrieve a destination dir of the form "dirid,relative_path" in the given entry.
1055  * returned buffer must be freed by caller.
1056  */
1057 WCHAR *PARSER_get_dest_dir( INFCONTEXT *context )
1058 {
1059     const WCHAR *dir;
1060     WCHAR *ptr, *ret;
1061     INT dirid;
1062     unsigned int len1;
1063     DWORD len2;
1064
1065     if (!SetupGetIntField( context, 1, &dirid )) return NULL;
1066     if (!(dir = get_dirid_subst( context->Inf, dirid, &len1 ))) return NULL;
1067     if (!SetupGetStringFieldW( context, 2, NULL, 0, &len2 )) len2 = 0;
1068     if (!(ret = HeapAlloc( GetProcessHeap(), 0, (len1+len2+1) * sizeof(WCHAR) ))) return NULL;
1069     memcpy( ret, dir, len1 * sizeof(WCHAR) );
1070     ptr = ret + len1;
1071     if (len2 && ptr > ret && ptr[-1] != '\\') *ptr++ = '\\';
1072     if (!SetupGetStringFieldW( context, 2, ptr, len2, NULL )) *ptr = 0;
1073     return ret;
1074 }
1075
1076
1077 /***********************************************************************
1078  *            SetupOpenInfFileA   (SETUPAPI.@)
1079  */
1080 HINF WINAPI SetupOpenInfFileA( PCSTR name, PCSTR class, DWORD style, UINT *error )
1081 {
1082     UNICODE_STRING nameW, classW;
1083     HINF ret = (HINF)INVALID_HANDLE_VALUE;
1084
1085     classW.Buffer = NULL;
1086     if (class && !RtlCreateUnicodeStringFromAsciiz( &classW, class ))
1087     {
1088         SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1089         return ret;
1090     }
1091     if (RtlCreateUnicodeStringFromAsciiz( &nameW, name ))
1092     {
1093         ret = SetupOpenInfFileW( nameW.Buffer, classW.Buffer, style, error );
1094         RtlFreeUnicodeString( &nameW );
1095     }
1096     RtlFreeUnicodeString( &classW );
1097     return ret;
1098 }
1099
1100
1101 /***********************************************************************
1102  *            SetupOpenInfFileW   (SETUPAPI.@)
1103  */
1104 HINF WINAPI SetupOpenInfFileW( PCWSTR name, PCWSTR class, DWORD style, UINT *error )
1105 {
1106     struct inf_file *file = NULL;
1107     HANDLE handle;
1108     WCHAR *path, *p;
1109     UINT len;
1110
1111     if (strchrW( name, '\\' ) || strchrW( name, '/' ))
1112     {
1113         if (!(len = GetFullPathNameW( name, 0, NULL, NULL ))) return (HINF)INVALID_HANDLE_VALUE;
1114         if (!(path = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) )))
1115         {
1116             SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1117             return (HINF)INVALID_HANDLE_VALUE;
1118         }
1119         GetFullPathNameW( name, len, path, NULL );
1120         handle = CreateFileW( path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0 );
1121     }
1122     else  /* try Windows directory */
1123     {
1124         static const WCHAR Inf[]      = {'\\','i','n','f','\\',0};
1125         static const WCHAR System32[] = {'\\','s','y','s','t','e','m','3','2','\\',0};
1126
1127         len = GetWindowsDirectoryW( NULL, 0 ) + strlenW(name) + 12;
1128         if (!(path = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) )))
1129         {
1130             SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1131             return (HINF)INVALID_HANDLE_VALUE;
1132         }
1133         GetWindowsDirectoryW( path, len );
1134         p = path + strlenW(path);
1135         strcpyW( p, Inf );
1136         strcatW( p, name );
1137         handle = CreateFileW( path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0 );
1138         if (handle == INVALID_HANDLE_VALUE)
1139         {
1140             strcpyW( p, System32 );
1141             strcatW( p, name );
1142             handle = CreateFileW( path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0 );
1143         }
1144     }
1145
1146     if (handle != INVALID_HANDLE_VALUE)
1147     {
1148         file = parse_file( handle, class, error );
1149         CloseHandle( handle );
1150     }
1151     if (!file)
1152     {
1153         HeapFree( GetProcessHeap(), 0, path );
1154         return (HINF)INVALID_HANDLE_VALUE;
1155     }
1156     TRACE( "%s -> %p\n", debugstr_w(path), file );
1157     file->filename = path;
1158     SetLastError( 0 );
1159     return (HINF)file;
1160 }
1161
1162
1163 /***********************************************************************
1164  *            SetupOpenAppendInfFileA    (SETUPAPI.@)
1165  */
1166 BOOL WINAPI SetupOpenAppendInfFileA( PCSTR name, HINF parent_hinf, UINT *error )
1167 {
1168     HINF child_hinf;
1169
1170     if (!name) return SetupOpenAppendInfFileW( NULL, parent_hinf, error );
1171     child_hinf = SetupOpenInfFileA( name, NULL, INF_STYLE_WIN4, error );
1172     if (child_hinf == (HINF)INVALID_HANDLE_VALUE) return FALSE;
1173     append_inf_file( parent_hinf, child_hinf );
1174     TRACE( "%p: appended %s (%p)\n", parent_hinf, debugstr_a(name), child_hinf );
1175     return TRUE;
1176 }
1177
1178
1179 /***********************************************************************
1180  *            SetupOpenAppendInfFileW    (SETUPAPI.@)
1181  */
1182 BOOL WINAPI SetupOpenAppendInfFileW( PCWSTR name, HINF parent_hinf, UINT *error )
1183 {
1184     HINF child_hinf;
1185
1186     if (!name)
1187     {
1188         INFCONTEXT context;
1189         WCHAR filename[MAX_PATH];
1190         int idx = 1;
1191
1192         if (!SetupFindFirstLineW( parent_hinf, Version, LayoutFile, &context )) return FALSE;
1193         while (SetupGetStringFieldW( &context, idx++, filename,
1194                                      sizeof(filename)/sizeof(WCHAR), NULL ))
1195         {
1196             child_hinf = SetupOpenInfFileW( filename, NULL, INF_STYLE_WIN4, error );
1197             if (child_hinf == (HINF)INVALID_HANDLE_VALUE) return FALSE;
1198             append_inf_file( parent_hinf, child_hinf );
1199             TRACE( "%p: appended %s (%p)\n", parent_hinf, debugstr_w(filename), child_hinf );
1200         }
1201         return TRUE;
1202     }
1203     child_hinf = SetupOpenInfFileW( name, NULL, INF_STYLE_WIN4, error );
1204     if (child_hinf == (HINF)INVALID_HANDLE_VALUE) return FALSE;
1205     append_inf_file( parent_hinf, child_hinf );
1206     TRACE( "%p: appended %s (%p)\n", parent_hinf, debugstr_w(name), child_hinf );
1207     return TRUE;
1208 }
1209
1210
1211 /***********************************************************************
1212  *            SetupOpenMasterInf   (SETUPAPI.@)
1213  */
1214 HINF WINAPI SetupOpenMasterInf( VOID )
1215 {
1216     static const WCHAR Layout[] = {'\\','i','n','f','\\', 'l', 'a', 'y', 'o', 'u', 't', '.', 'i', 'n', 'f', 0};
1217     WCHAR Buffer[MAX_PATH];
1218
1219     GetWindowsDirectoryW( Buffer, MAX_PATH );
1220     strcatW( Buffer, Layout );
1221     return SetupOpenInfFileW( Buffer, NULL, INF_STYLE_WIN4, NULL);
1222 }
1223
1224
1225
1226 /***********************************************************************
1227  *            SetupCloseInfFile   (SETUPAPI.@)
1228  */
1229 void WINAPI SetupCloseInfFile( HINF hinf )
1230 {
1231     struct inf_file *file = hinf;
1232     unsigned int i;
1233
1234     if (!file) return;
1235
1236     for (i = 0; i < file->nb_sections; i++) HeapFree( GetProcessHeap(), 0, file->sections[i] );
1237     HeapFree( GetProcessHeap(), 0, file->filename );
1238     HeapFree( GetProcessHeap(), 0, file->sections );
1239     HeapFree( GetProcessHeap(), 0, file->fields );
1240     HeapFree( GetProcessHeap(), 0, file->strings );
1241     HeapFree( GetProcessHeap(), 0, file );
1242 }
1243
1244
1245 /***********************************************************************
1246  *            SetupGetLineCountA   (SETUPAPI.@)
1247  */
1248 LONG WINAPI SetupGetLineCountA( HINF hinf, PCSTR name )
1249 {
1250     UNICODE_STRING sectionW;
1251     LONG ret = -1;
1252
1253     if (!RtlCreateUnicodeStringFromAsciiz( &sectionW, name ))
1254         SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1255     else
1256     {
1257         ret = SetupGetLineCountW( hinf, sectionW.Buffer );
1258         RtlFreeUnicodeString( &sectionW );
1259     }
1260     return ret;
1261 }
1262
1263
1264 /***********************************************************************
1265  *            SetupGetLineCountW   (SETUPAPI.@)
1266  */
1267 LONG WINAPI SetupGetLineCountW( HINF hinf, PCWSTR section )
1268 {
1269     struct inf_file *file = hinf;
1270     int section_index;
1271     LONG ret = -1;
1272
1273     for (file = hinf; file; file = file->next)
1274     {
1275         if ((section_index = find_section( file, section )) == -1) continue;
1276         if (ret == -1) ret = 0;
1277         ret += file->sections[section_index]->nb_lines;
1278     }
1279     TRACE( "(%p,%s) returning %d\n", hinf, debugstr_w(section), ret );
1280     SetLastError( (ret == -1) ? ERROR_SECTION_NOT_FOUND : 0 );
1281     return ret;
1282 }
1283
1284
1285 /***********************************************************************
1286  *            SetupGetLineByIndexA   (SETUPAPI.@)
1287  */
1288 BOOL WINAPI SetupGetLineByIndexA( HINF hinf, PCSTR section, DWORD index, INFCONTEXT *context )
1289 {
1290     UNICODE_STRING sectionW;
1291     BOOL ret = FALSE;
1292
1293     if (!RtlCreateUnicodeStringFromAsciiz( &sectionW, section ))
1294         SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1295     else
1296     {
1297         ret = SetupGetLineByIndexW( hinf, sectionW.Buffer, index, context );
1298         RtlFreeUnicodeString( &sectionW );
1299     }
1300     return ret;
1301 }
1302
1303
1304 /***********************************************************************
1305  *            SetupGetLineByIndexW   (SETUPAPI.@)
1306  */
1307 BOOL WINAPI SetupGetLineByIndexW( HINF hinf, PCWSTR section, DWORD index, INFCONTEXT *context )
1308 {
1309     struct inf_file *file = hinf;
1310     int section_index;
1311
1312     SetLastError( ERROR_SECTION_NOT_FOUND );
1313     for (file = hinf; file; file = file->next)
1314     {
1315         if ((section_index = find_section( file, section )) == -1) continue;
1316         SetLastError( ERROR_LINE_NOT_FOUND );
1317         if (index < file->sections[section_index]->nb_lines)
1318         {
1319             context->Inf        = hinf;
1320             context->CurrentInf = file;
1321             context->Section    = section_index;
1322             context->Line       = index;
1323             SetLastError( 0 );
1324             TRACE( "(%p,%s): returning %d/%d\n",
1325                    hinf, debugstr_w(section), section_index, index );
1326             return TRUE;
1327         }
1328         index -= file->sections[section_index]->nb_lines;
1329     }
1330     TRACE( "(%p,%s) not found\n", hinf, debugstr_w(section) );
1331     return FALSE;
1332 }
1333
1334
1335 /***********************************************************************
1336  *            SetupFindFirstLineA   (SETUPAPI.@)
1337  */
1338 BOOL WINAPI SetupFindFirstLineA( HINF hinf, PCSTR section, PCSTR key, INFCONTEXT *context )
1339 {
1340     UNICODE_STRING sectionW, keyW;
1341     BOOL ret = FALSE;
1342
1343     if (!RtlCreateUnicodeStringFromAsciiz( &sectionW, section ))
1344     {
1345         SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1346         return FALSE;
1347     }
1348
1349     if (!key) ret = SetupFindFirstLineW( hinf, sectionW.Buffer, NULL, context );
1350     else
1351     {
1352         if (RtlCreateUnicodeStringFromAsciiz( &keyW, key ))
1353         {
1354             ret = SetupFindFirstLineW( hinf, sectionW.Buffer, keyW.Buffer, context );
1355             RtlFreeUnicodeString( &keyW );
1356         }
1357         else SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1358     }
1359     RtlFreeUnicodeString( &sectionW );
1360     return ret;
1361 }
1362
1363
1364 /***********************************************************************
1365  *            SetupFindFirstLineW   (SETUPAPI.@)
1366  */
1367 BOOL WINAPI SetupFindFirstLineW( HINF hinf, PCWSTR section, PCWSTR key, INFCONTEXT *context )
1368 {
1369     struct inf_file *file;
1370     int section_index;
1371
1372     SetLastError( ERROR_SECTION_NOT_FOUND );
1373     for (file = hinf; file; file = file->next)
1374     {
1375         if ((section_index = find_section( file, section )) == -1) continue;
1376         if (key)
1377         {
1378             INFCONTEXT ctx;
1379             ctx.Inf        = hinf;
1380             ctx.CurrentInf = file;
1381             ctx.Section    = section_index;
1382             ctx.Line       = -1;
1383             return SetupFindNextMatchLineW( &ctx, key, context );
1384         }
1385         SetLastError( ERROR_LINE_NOT_FOUND );  /* found at least one section */
1386         if (file->sections[section_index]->nb_lines)
1387         {
1388             context->Inf        = hinf;
1389             context->CurrentInf = file;
1390             context->Section    = section_index;
1391             context->Line       = 0;
1392             SetLastError( 0 );
1393             TRACE( "(%p,%s,%s): returning %d/0\n",
1394                    hinf, debugstr_w(section), debugstr_w(key), section_index );
1395             return TRUE;
1396         }
1397     }
1398     TRACE( "(%p,%s,%s): not found\n", hinf, debugstr_w(section), debugstr_w(key) );
1399     return FALSE;
1400 }
1401
1402
1403 /***********************************************************************
1404  *            SetupFindNextLine   (SETUPAPI.@)
1405  */
1406 BOOL WINAPI SetupFindNextLine( PINFCONTEXT context_in, PINFCONTEXT context_out )
1407 {
1408     struct inf_file *file = context_in->CurrentInf;
1409     struct section *section;
1410
1411     if (context_in->Section >= file->nb_sections) goto error;
1412
1413     section = file->sections[context_in->Section];
1414     if (context_in->Line+1 < section->nb_lines)
1415     {
1416         if (context_out != context_in) *context_out = *context_in;
1417         context_out->Line++;
1418         SetLastError( 0 );
1419         return TRUE;
1420     }
1421
1422     /* now search the appended files */
1423
1424     for (file = file->next; file; file = file->next)
1425     {
1426         int section_index = find_section( file, section->name );
1427         if (section_index == -1) continue;
1428         if (file->sections[section_index]->nb_lines)
1429         {
1430             context_out->Inf        = context_in->Inf;
1431             context_out->CurrentInf = file;
1432             context_out->Section    = section_index;
1433             context_out->Line       = 0;
1434             SetLastError( 0 );
1435             return TRUE;
1436         }
1437     }
1438  error:
1439     SetLastError( ERROR_LINE_NOT_FOUND );
1440     return FALSE;
1441 }
1442
1443
1444 /***********************************************************************
1445  *            SetupFindNextMatchLineA   (SETUPAPI.@)
1446  */
1447 BOOL WINAPI SetupFindNextMatchLineA( PINFCONTEXT context_in, PCSTR key,
1448                                      PINFCONTEXT context_out )
1449 {
1450     UNICODE_STRING keyW;
1451     BOOL ret = FALSE;
1452
1453     if (!key) return SetupFindNextLine( context_in, context_out );
1454
1455     if (!RtlCreateUnicodeStringFromAsciiz( &keyW, key ))
1456         SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1457     else
1458     {
1459         ret = SetupFindNextMatchLineW( context_in, keyW.Buffer, context_out );
1460         RtlFreeUnicodeString( &keyW );
1461     }
1462     return ret;
1463 }
1464
1465
1466 /***********************************************************************
1467  *            SetupFindNextMatchLineW   (SETUPAPI.@)
1468  */
1469 BOOL WINAPI SetupFindNextMatchLineW( PINFCONTEXT context_in, PCWSTR key,
1470                                      PINFCONTEXT context_out )
1471 {
1472     struct inf_file *file = context_in->CurrentInf;
1473     struct section *section;
1474     struct line *line;
1475     unsigned int i;
1476
1477     if (!key) return SetupFindNextLine( context_in, context_out );
1478
1479     if (context_in->Section >= file->nb_sections) goto error;
1480
1481     section = file->sections[context_in->Section];
1482
1483     for (i = context_in->Line+1, line = &section->lines[i]; i < section->nb_lines; i++, line++)
1484     {
1485         if (line->key_field == -1) continue;
1486         if (!strcmpiW( key, file->fields[line->key_field].text ))
1487         {
1488             if (context_out != context_in) *context_out = *context_in;
1489             context_out->Line = i;
1490             SetLastError( 0 );
1491             TRACE( "(%p,%s,%s): returning %d\n",
1492                    file, debugstr_w(section->name), debugstr_w(key), i );
1493             return TRUE;
1494         }
1495     }
1496
1497     /* now search the appended files */
1498
1499     for (file = file->next; file; file = file->next)
1500     {
1501         int section_index = find_section( file, section->name );
1502         if (section_index == -1) continue;
1503         section = file->sections[section_index];
1504         for (i = 0, line = section->lines; i < section->nb_lines; i++, line++)
1505         {
1506             if (line->key_field == -1) continue;
1507             if (!strcmpiW( key, file->fields[line->key_field].text ))
1508             {
1509                 context_out->Inf        = context_in->Inf;
1510                 context_out->CurrentInf = file;
1511                 context_out->Section    = section_index;
1512                 context_out->Line       = i;
1513                 SetLastError( 0 );
1514                 TRACE( "(%p,%s,%s): returning %d/%d\n",
1515                        file, debugstr_w(section->name), debugstr_w(key), section_index, i );
1516                 return TRUE;
1517             }
1518         }
1519     }
1520     TRACE( "(%p,%s,%s): not found\n",
1521            context_in->CurrentInf, debugstr_w(section->name), debugstr_w(key) );
1522  error:
1523     SetLastError( ERROR_LINE_NOT_FOUND );
1524     return FALSE;
1525 }
1526
1527
1528 /***********************************************************************
1529  *              SetupGetLineTextW    (SETUPAPI.@)
1530  */
1531 BOOL WINAPI SetupGetLineTextW( PINFCONTEXT context, HINF hinf, PCWSTR section_name,
1532                                PCWSTR key_name, PWSTR buffer, DWORD size, PDWORD required )
1533 {
1534     struct inf_file *file;
1535     struct line *line;
1536     struct field *field;
1537     int i;
1538     DWORD total = 0;
1539
1540     if (!context)
1541     {
1542         INFCONTEXT new_context;
1543         if (!SetupFindFirstLineW( hinf, section_name, key_name, &new_context )) return FALSE;
1544         file = new_context.CurrentInf;
1545         line = get_line( file, new_context.Section, new_context.Line );
1546     }
1547     else
1548     {
1549         file = context->CurrentInf;
1550         if (!(line = get_line( file, context->Section, context->Line )))
1551         {
1552             SetLastError( ERROR_LINE_NOT_FOUND );
1553             return FALSE;
1554         }
1555     }
1556
1557     for (i = 0, field = &file->fields[line->first_field]; i < line->nb_fields; i++, field++)
1558         total += PARSER_string_substW( file, field->text, NULL, 0 ) + 1;
1559
1560     if (required) *required = total;
1561     if (buffer)
1562     {
1563         if (total > size)
1564         {
1565             SetLastError( ERROR_INSUFFICIENT_BUFFER );
1566             return FALSE;
1567         }
1568         for (i = 0, field = &file->fields[line->first_field]; i < line->nb_fields; i++, field++)
1569         {
1570             unsigned int len = PARSER_string_substW( file, field->text, buffer, size );
1571             if (i+1 < line->nb_fields) buffer[len] = ',';
1572             buffer += len + 1;
1573         }
1574     }
1575     return TRUE;
1576 }
1577
1578
1579 /***********************************************************************
1580  *              SetupGetLineTextA    (SETUPAPI.@)
1581  */
1582 BOOL WINAPI SetupGetLineTextA( PINFCONTEXT context, HINF hinf, PCSTR section_name,
1583                                PCSTR key_name, PSTR buffer, DWORD size, PDWORD required )
1584 {
1585     struct inf_file *file;
1586     struct line *line;
1587     struct field *field;
1588     int i;
1589     DWORD total = 0;
1590
1591     if (!context)
1592     {
1593         INFCONTEXT new_context;
1594         if (!SetupFindFirstLineA( hinf, section_name, key_name, &new_context )) return FALSE;
1595         file = new_context.CurrentInf;
1596         line = get_line( file, new_context.Section, new_context.Line );
1597     }
1598     else
1599     {
1600         file = context->CurrentInf;
1601         if (!(line = get_line( file, context->Section, context->Line )))
1602         {
1603             SetLastError( ERROR_LINE_NOT_FOUND );
1604             return FALSE;
1605         }
1606     }
1607
1608     for (i = 0, field = &file->fields[line->first_field]; i < line->nb_fields; i++, field++)
1609         total += PARSER_string_substA( file, field->text, NULL, 0 ) + 1;
1610
1611     if (required) *required = total;
1612     if (buffer)
1613     {
1614         if (total > size)
1615         {
1616             SetLastError( ERROR_INSUFFICIENT_BUFFER );
1617             return FALSE;
1618         }
1619         for (i = 0, field = &file->fields[line->first_field]; i < line->nb_fields; i++, field++)
1620         {
1621             unsigned int len = PARSER_string_substA( file, field->text, buffer, size );
1622             if (i+1 < line->nb_fields) buffer[len] = ',';
1623             buffer += len + 1;
1624         }
1625     }
1626     return TRUE;
1627 }
1628
1629
1630 /***********************************************************************
1631  *              SetupGetFieldCount    (SETUPAPI.@)
1632  */
1633 DWORD WINAPI SetupGetFieldCount( PINFCONTEXT context )
1634 {
1635     struct inf_file *file = context->CurrentInf;
1636     struct line *line = get_line( file, context->Section, context->Line );
1637
1638     if (!line) return 0;
1639     return line->nb_fields;
1640 }
1641
1642
1643 /***********************************************************************
1644  *              SetupGetStringFieldA    (SETUPAPI.@)
1645  */
1646 BOOL WINAPI SetupGetStringFieldA( PINFCONTEXT context, DWORD index, PSTR buffer,
1647                                   DWORD size, PDWORD required )
1648 {
1649     struct inf_file *file = context->CurrentInf;
1650     struct field *field = get_field( file, context->Section, context->Line, index );
1651     unsigned int len;
1652
1653     SetLastError(0);
1654     if (!field) return FALSE;
1655     len = PARSER_string_substA( file, field->text, NULL, 0 );
1656     if (required) *required = len + 1;
1657     if (buffer)
1658     {
1659         if (size <= len)
1660         {
1661             SetLastError( ERROR_INSUFFICIENT_BUFFER );
1662             return FALSE;
1663         }
1664         PARSER_string_substA( file, field->text, buffer, size );
1665
1666         TRACE( "context %p/%p/%d/%d index %d returning %s\n",
1667                context->Inf, context->CurrentInf, context->Section, context->Line,
1668                index, debugstr_a(buffer) );
1669     }
1670     return TRUE;
1671 }
1672
1673
1674 /***********************************************************************
1675  *              SetupGetStringFieldW    (SETUPAPI.@)
1676  */
1677 BOOL WINAPI SetupGetStringFieldW( PINFCONTEXT context, DWORD index, PWSTR buffer,
1678                                   DWORD size, PDWORD required )
1679 {
1680     struct inf_file *file = context->CurrentInf;
1681     struct field *field = get_field( file, context->Section, context->Line, index );
1682     unsigned int len;
1683
1684     SetLastError(0);
1685     if (!field) return FALSE;
1686     len = PARSER_string_substW( file, field->text, NULL, 0 );
1687     if (required) *required = len + 1;
1688     if (buffer)
1689     {
1690         if (size <= len)
1691         {
1692             SetLastError( ERROR_INSUFFICIENT_BUFFER );
1693             return FALSE;
1694         }
1695         PARSER_string_substW( file, field->text, buffer, size );
1696
1697         TRACE( "context %p/%p/%d/%d index %d returning %s\n",
1698                context->Inf, context->CurrentInf, context->Section, context->Line,
1699                index, debugstr_w(buffer) );
1700     }
1701     return TRUE;
1702 }
1703
1704
1705 /***********************************************************************
1706  *              SetupGetIntField    (SETUPAPI.@)
1707  */
1708 BOOL WINAPI SetupGetIntField( PINFCONTEXT context, DWORD index, PINT result )
1709 {
1710     char localbuff[20];
1711     char *end, *buffer = localbuff;
1712     DWORD required;
1713     INT res;
1714     BOOL ret = FALSE;
1715
1716     if (!SetupGetStringFieldA( context, index, localbuff, sizeof(localbuff), &required ))
1717     {
1718         if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) return FALSE;
1719         if (!(buffer = HeapAlloc( GetProcessHeap(), 0, required ))) return FALSE;
1720         if (!SetupGetStringFieldA( context, index, buffer, required, NULL )) goto done;
1721     }
1722     res = strtol( buffer, &end, 0 );
1723     if (end != buffer && !*end)
1724     {
1725         *result = res;
1726         ret = TRUE;
1727     }
1728     else SetLastError( ERROR_INVALID_DATA );
1729
1730  done:
1731     if (buffer != localbuff) HeapFree( GetProcessHeap(), 0, buffer );
1732     return ret;
1733 }
1734
1735
1736 /***********************************************************************
1737  *              SetupGetBinaryField    (SETUPAPI.@)
1738  */
1739 BOOL WINAPI SetupGetBinaryField( PINFCONTEXT context, DWORD index, BYTE *buffer,
1740                                  DWORD size, LPDWORD required )
1741 {
1742     struct inf_file *file = context->CurrentInf;
1743     struct line *line = get_line( file, context->Section, context->Line );
1744     struct field *field;
1745     int i;
1746
1747     if (!line)
1748     {
1749         SetLastError( ERROR_LINE_NOT_FOUND );
1750         return FALSE;
1751     }
1752     if (!index || index > line->nb_fields)
1753     {
1754         SetLastError( ERROR_INVALID_PARAMETER );
1755         return FALSE;
1756     }
1757     index--;  /* fields start at 0 */
1758     if (required) *required = line->nb_fields - index;
1759     if (!buffer) return TRUE;
1760     if (size < line->nb_fields - index)
1761     {
1762         SetLastError( ERROR_INSUFFICIENT_BUFFER );
1763         return FALSE;
1764     }
1765     field = &file->fields[line->first_field + index];
1766     for (i = index; i < line->nb_fields; i++, field++)
1767     {
1768         const WCHAR *p;
1769         DWORD value = 0;
1770         for (p = field->text; *p && isxdigitW(*p); p++)
1771         {
1772             if ((value <<= 4) > 255)
1773             {
1774                 SetLastError( ERROR_INVALID_DATA );
1775                 return FALSE;
1776             }
1777             if (*p <= '9') value |= (*p - '0');
1778             else value |= (tolowerW(*p) - 'a' + 10);
1779         }
1780         buffer[i - index] = value;
1781     }
1782     if (TRACE_ON(setupapi))
1783     {
1784         TRACE( "%p/%p/%d/%d index %d returning",
1785                context->Inf, context->CurrentInf, context->Section, context->Line, index );
1786         for (i = index; i < line->nb_fields; i++) TRACE( " %02x", buffer[i - index] );
1787         TRACE( "\n" );
1788     }
1789     return TRUE;
1790 }
1791
1792
1793 /***********************************************************************
1794  *              SetupGetMultiSzFieldA    (SETUPAPI.@)
1795  */
1796 BOOL WINAPI SetupGetMultiSzFieldA( PINFCONTEXT context, DWORD index, PSTR buffer,
1797                                    DWORD size, LPDWORD required )
1798 {
1799     struct inf_file *file = context->CurrentInf;
1800     struct line *line = get_line( file, context->Section, context->Line );
1801     struct field *field;
1802     unsigned int len;
1803     int i;
1804     DWORD total = 1;
1805
1806     if (!line)
1807     {
1808         SetLastError( ERROR_LINE_NOT_FOUND );
1809         return FALSE;
1810     }
1811     if (!index || index > line->nb_fields)
1812     {
1813         SetLastError( ERROR_INVALID_PARAMETER );
1814         return FALSE;
1815     }
1816     index--;  /* fields start at 0 */
1817     field = &file->fields[line->first_field + index];
1818     for (i = index; i < line->nb_fields; i++, field++)
1819     {
1820         if (!(len = PARSER_string_substA( file, field->text, NULL, 0 ))) break;
1821         total += len + 1;
1822     }
1823
1824     if (required) *required = total;
1825     if (!buffer) return TRUE;
1826     if (total > size)
1827     {
1828         SetLastError( ERROR_INSUFFICIENT_BUFFER );
1829         return FALSE;
1830     }
1831     field = &file->fields[line->first_field + index];
1832     for (i = index; i < line->nb_fields; i++, field++)
1833     {
1834         if (!(len = PARSER_string_substA( file, field->text, buffer, size ))) break;
1835         buffer += len + 1;
1836     }
1837     *buffer = 0;  /* add final null */
1838     return TRUE;
1839 }
1840
1841
1842 /***********************************************************************
1843  *              SetupGetMultiSzFieldW    (SETUPAPI.@)
1844  */
1845 BOOL WINAPI SetupGetMultiSzFieldW( PINFCONTEXT context, DWORD index, PWSTR buffer,
1846                                    DWORD size, LPDWORD required )
1847 {
1848     struct inf_file *file = context->CurrentInf;
1849     struct line *line = get_line( file, context->Section, context->Line );
1850     struct field *field;
1851     unsigned int len;
1852     int i;
1853     DWORD total = 1;
1854
1855     if (!line)
1856     {
1857         SetLastError( ERROR_LINE_NOT_FOUND );
1858         return FALSE;
1859     }
1860     if (!index || index > line->nb_fields)
1861     {
1862         SetLastError( ERROR_INVALID_PARAMETER );
1863         return FALSE;
1864     }
1865     index--;  /* fields start at 0 */
1866     field = &file->fields[line->first_field + index];
1867     for (i = index; i < line->nb_fields; i++, field++)
1868     {
1869         if (!(len = PARSER_string_substW( file, field->text, NULL, 0 ))) break;
1870         total += len + 1;
1871     }
1872
1873     if (required) *required = total;
1874     if (!buffer) return TRUE;
1875     if (total > size)
1876     {
1877         SetLastError( ERROR_INSUFFICIENT_BUFFER );
1878         return FALSE;
1879     }
1880     field = &file->fields[line->first_field + index];
1881     for (i = index; i < line->nb_fields; i++, field++)
1882     {
1883         if (!(len = PARSER_string_substW( file, field->text, buffer, size ))) break;
1884         buffer += len + 1;
1885     }
1886     *buffer = 0;  /* add final null */
1887     return TRUE;
1888 }
1889
1890 /***********************************************************************
1891  *      pSetupGetField    (SETUPAPI.@)
1892  */
1893 LPCWSTR WINAPI pSetupGetField( PINFCONTEXT context, DWORD index )
1894 {
1895     struct inf_file *file = context->CurrentInf;
1896     struct field *field = get_field( file, context->Section, context->Line, index );
1897
1898     if (!field)
1899     {
1900         SetLastError( ERROR_INVALID_PARAMETER );
1901         return NULL;
1902     }
1903     return field->text;
1904 }