comctl32: We can now store binary files in the repository.
[wine] / dlls / ntdll / actctx.c
1 /*
2  * Activation contexts
3  *
4  * Copyright 2004 Jon Griffiths
5  * Copyright 2007 Eric Pouech
6  * Copyright 2007 Jacek Caban for CodeWeavers
7  * Copyright 2007 Alexandre Julliard
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22  */
23
24 #include "config.h"
25 #include "wine/port.h"
26
27 #include <stdarg.h>
28 #include <stdio.h>
29
30 #define NONAMELESSUNION
31 #define NONAMELESSSTRUCT
32 #include "ntstatus.h"
33 #define WIN32_NO_STATUS
34 #include "winternl.h"
35 #include "ntdll_misc.h"
36 #include "wine/debug.h"
37 #include "wine/unicode.h"
38
39 WINE_DEFAULT_DEBUG_CHANNEL(actctx);
40
41 #define ACTCTX_FLAGS_ALL (\
42  ACTCTX_FLAG_PROCESSOR_ARCHITECTURE_VALID |\
43  ACTCTX_FLAG_LANGID_VALID |\
44  ACTCTX_FLAG_ASSEMBLY_DIRECTORY_VALID |\
45  ACTCTX_FLAG_RESOURCE_NAME_VALID |\
46  ACTCTX_FLAG_SET_PROCESS_DEFAULT |\
47  ACTCTX_FLAG_APPLICATION_NAME_VALID |\
48  ACTCTX_FLAG_SOURCE_IS_ASSEMBLYREF |\
49  ACTCTX_FLAG_HMODULE_VALID )
50
51 #define ACTCTX_MAGIC       0xC07E3E11
52
53 /* we don't want to include winuser.h */
54 #define RT_MANIFEST                        ((ULONG_PTR)24)
55 #define CREATEPROCESS_MANIFEST_RESOURCE_ID ((ULONG_PTR)1)
56
57 typedef struct
58 {
59     const WCHAR        *ptr;
60     unsigned int        len;
61 } xmlstr_t;
62
63 typedef struct
64 {
65     const WCHAR        *ptr;
66     const WCHAR        *end;
67 } xmlbuf_t;
68
69 struct file_info
70 {
71     ULONG               type;
72     WCHAR              *info;
73 };
74
75 struct version
76 {
77     USHORT              major;
78     USHORT              minor;
79     USHORT              build;
80     USHORT              revision;
81 };
82
83 struct assembly_identity
84 {
85     WCHAR                *name;
86     WCHAR                *arch;
87     WCHAR                *public_key;
88     WCHAR                *language;
89     WCHAR                *type;
90     struct version        version;
91     BOOL                  optional;
92 };
93
94 struct entity
95 {
96     DWORD kind;
97     union
98     {
99         struct
100         {
101             WCHAR *tlbid;
102             WCHAR *version;
103             WCHAR *helpdir;
104         } typelib;
105         struct
106         {
107             WCHAR *clsid;
108         } comclass;
109         struct {
110             WCHAR *iid;
111             WCHAR *name;
112         } proxy;
113         struct
114         {
115             WCHAR *name;
116         } class;
117         struct
118         {
119             WCHAR *name;
120             WCHAR *clsid;
121         } clrclass;
122         struct
123         {
124             WCHAR *name;
125             WCHAR *clsid;
126         } clrsurrogate;
127     } u;
128 };
129
130 struct entity_array
131 {
132     struct entity        *base;
133     unsigned int          num;
134     unsigned int          allocated;
135 };
136
137 struct dll_redirect
138 {
139     WCHAR                *name;
140     WCHAR                *hash;
141     struct entity_array   entities;
142 };
143
144 enum assembly_type
145 {
146     APPLICATION_MANIFEST,
147     ASSEMBLY_MANIFEST
148 };
149
150 struct assembly
151 {
152     enum assembly_type       type;
153     struct assembly_identity id;
154     struct file_info         manifest;
155     WCHAR                   *directory;
156     BOOL                     no_inherit;
157     struct dll_redirect     *dlls;
158     unsigned int             num_dlls;
159     unsigned int             allocated_dlls;
160     struct entity_array      entities;
161 };
162
163 typedef struct _ACTIVATION_CONTEXT
164 {
165     ULONG               magic;
166     int                 ref_count;
167     struct file_info    config;
168     struct file_info    appdir;
169     struct assembly    *assemblies;
170     unsigned int        num_assemblies;
171     unsigned int        allocated_assemblies;
172 } ACTIVATION_CONTEXT;
173
174 struct actctx_loader
175 {
176     ACTIVATION_CONTEXT       *actctx;
177     struct assembly_identity *dependencies;
178     unsigned int              num_dependencies;
179     unsigned int              allocated_dependencies;
180 };
181
182 static const WCHAR assemblyW[] = {'a','s','s','e','m','b','l','y',0};
183 static const WCHAR assemblyIdentityW[] = {'a','s','s','e','m','b','l','y','I','d','e','n','t','i','t','y',0};
184 static const WCHAR bindingRedirectW[] = {'b','i','n','d','i','n','g','R','e','d','i','r','e','c','t',0};
185 static const WCHAR clrClassW[] = {'c','l','r','C','l','a','s','s',0};
186 static const WCHAR clrSurrogateW[] = {'c','l','r','S','u','r','r','o','g','a','t','e',0};
187 static const WCHAR comClassW[] = {'c','o','m','C','l','a','s','s',0};
188 static const WCHAR comInterfaceExternalProxyStubW[] = {'c','o','m','I','n','t','e','r','f','a','c','e','E','x','t','e','r','n','a','l','P','r','o','x','y','S','t','u','b',0};
189 static const WCHAR comInterfaceProxyStubW[] = {'c','o','m','I','n','t','e','r','f','a','c','e','P','r','o','x','y','S','t','u','b',0};
190 static const WCHAR dependencyW[] = {'d','e','p','e','n','d','e','n','c','y',0};
191 static const WCHAR dependentAssemblyW[] = {'d','e','p','e','n','d','e','n','t','A','s','s','e','m','b','l','y',0};
192 static const WCHAR descriptionW[] = {'d','e','s','c','r','i','p','t','i','o','n',0};
193 static const WCHAR fileW[] = {'f','i','l','e',0};
194 static const WCHAR asmv2hashW[] = {'a','s','m','v','2',':','h','a','s','h',0};
195 static const WCHAR noInheritW[] = {'n','o','I','n','h','e','r','i','t',0};
196 static const WCHAR noInheritableW[] = {'n','o','I','n','h','e','r','i','t','a','b','l','e',0};
197 static const WCHAR typelibW[] = {'t','y','p','e','l','i','b',0};
198 static const WCHAR windowClassW[] = {'w','i','n','d','o','w','C','l','a','s','s',0};
199
200 static const WCHAR clsidW[] = {'c','l','s','i','d',0};
201 static const WCHAR hashW[] = {'h','a','s','h',0};
202 static const WCHAR hashalgW[] = {'h','a','s','h','a','l','g',0};
203 static const WCHAR helpdirW[] = {'h','e','l','p','d','i','r',0};
204 static const WCHAR iidW[] = {'i','i','d',0};
205 static const WCHAR languageW[] = {'l','a','n','g','u','a','g','e',0};
206 static const WCHAR manifestVersionW[] = {'m','a','n','i','f','e','s','t','V','e','r','s','i','o','n',0};
207 static const WCHAR nameW[] = {'n','a','m','e',0};
208 static const WCHAR newVersionW[] = {'n','e','w','V','e','r','s','i','o','n',0};
209 static const WCHAR oldVersionW[] = {'o','l','d','V','e','r','s','i','o','n',0};
210 static const WCHAR optionalW[] = {'o','p','t','i','o','n','a','l',0};
211 static const WCHAR processorArchitectureW[] = {'p','r','o','c','e','s','s','o','r','A','r','c','h','i','t','e','c','t','u','r','e',0};
212 static const WCHAR publicKeyTokenW[] = {'p','u','b','l','i','c','K','e','y','T','o','k','e','n',0};
213 static const WCHAR tlbidW[] = {'t','l','b','i','d',0};
214 static const WCHAR typeW[] = {'t','y','p','e',0};
215 static const WCHAR versionW[] = {'v','e','r','s','i','o','n',0};
216 static const WCHAR xmlnsW[] = {'x','m','l','n','s',0};
217
218 static const WCHAR xmlW[] = {'?','x','m','l',0};
219 static const WCHAR manifestv1W[] = {'u','r','n',':','s','c','h','e','m','a','s','-','m','i','c','r','o','s','o','f','t','-','c','o','m',':','a','s','m','.','v','1',0};
220 static const WCHAR manifestv3W[] = {'u','r','n',':','s','c','h','e','m','a','s','-','m','i','c','r','o','s','o','f','t','-','c','o','m',':','a','s','m','.','v','3',0};
221
222 static const WCHAR dotManifestW[] = {'.','m','a','n','i','f','e','s','t',0};
223 static const WCHAR version_formatW[] = {'%','u','.','%','u','.','%','u','.','%','u',0};
224
225 static ACTIVATION_CONTEXT system_actctx = { ACTCTX_MAGIC, 1 };
226 static ACTIVATION_CONTEXT *process_actctx = &system_actctx;
227
228 static WCHAR *strdupW(const WCHAR* str)
229 {
230     WCHAR*      ptr;
231
232     if (!(ptr = RtlAllocateHeap(GetProcessHeap(), 0, (strlenW(str) + 1) * sizeof(WCHAR))))
233         return NULL;
234     return strcpyW(ptr, str);
235 }
236
237 static WCHAR *xmlstrdupW(const xmlstr_t* str)
238 {
239     WCHAR *strW;
240
241     if ((strW = RtlAllocateHeap(GetProcessHeap(), 0, (str->len + 1) * sizeof(WCHAR))))
242     {
243         memcpy( strW, str->ptr, str->len * sizeof(WCHAR) );
244         strW[str->len] = 0;
245     }
246     return strW;
247 }
248
249 static inline BOOL xmlstr_cmp(const xmlstr_t* xmlstr, const WCHAR *str)
250 {
251     return !strncmpW(xmlstr->ptr, str, xmlstr->len) && !str[xmlstr->len];
252 }
253
254 static inline BOOL xmlstr_cmpi(const xmlstr_t* xmlstr, const WCHAR *str)
255 {
256     return !strncmpiW(xmlstr->ptr, str, xmlstr->len) && !str[xmlstr->len];
257 }
258
259 static inline BOOL xmlstr_cmp_end(const xmlstr_t* xmlstr, const WCHAR *str)
260 {
261     return (xmlstr->len && xmlstr->ptr[0] == '/' &&
262             !strncmpW(xmlstr->ptr + 1, str, xmlstr->len - 1) && !str[xmlstr->len - 1]);
263 }
264
265 static inline BOOL isxmlspace( WCHAR ch )
266 {
267     return (ch == ' ' || ch == '\r' || ch == '\n' || ch == '\t');
268 }
269
270 static inline const char* debugstr_xmlstr(const xmlstr_t* str)
271 {
272     return debugstr_wn(str->ptr, str->len);
273 }
274
275 static inline const char* debugstr_version(const struct version *ver)
276 {
277     return wine_dbg_sprintf("%u.%u.%u.%u", ver->major, ver->minor, ver->build, ver->revision);
278 }
279
280 static struct assembly *add_assembly(ACTIVATION_CONTEXT *actctx, enum assembly_type at)
281 {
282     struct assembly *assembly;
283
284     if (actctx->num_assemblies == actctx->allocated_assemblies)
285     {
286         void *ptr;
287         unsigned int new_count;
288         if (actctx->assemblies)
289         {
290             new_count = actctx->allocated_assemblies * 2;
291             ptr = RtlReAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY,
292                                      actctx->assemblies, new_count * sizeof(*assembly) );
293         }
294         else
295         {
296             new_count = 4;
297             ptr = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, new_count * sizeof(*assembly) );
298         }
299         if (!ptr) return NULL;
300         actctx->assemblies = ptr;
301         actctx->allocated_assemblies = new_count;
302     }
303
304     assembly = &actctx->assemblies[actctx->num_assemblies++];
305     assembly->type = at;
306     return assembly;
307 }
308
309 static struct dll_redirect* add_dll_redirect(struct assembly* assembly)
310 {
311     if (assembly->num_dlls == assembly->allocated_dlls)
312     {
313         void *ptr;
314         unsigned int new_count;
315         if (assembly->dlls)
316         {
317             new_count = assembly->allocated_dlls * 2;
318             ptr = RtlReAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY,
319                                      assembly->dlls, new_count * sizeof(*assembly->dlls) );
320         }
321         else
322         {
323             new_count = 4;
324             ptr = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, new_count * sizeof(*assembly->dlls) );
325         }
326         if (!ptr) return NULL;
327         assembly->dlls = ptr;
328         assembly->allocated_dlls = new_count;
329     }
330     return &assembly->dlls[assembly->num_dlls++];
331 }
332
333 static void free_assembly_identity(struct assembly_identity *ai)
334 {
335     RtlFreeHeap( GetProcessHeap(), 0, ai->name );
336     RtlFreeHeap( GetProcessHeap(), 0, ai->arch );
337     RtlFreeHeap( GetProcessHeap(), 0, ai->public_key );
338     RtlFreeHeap( GetProcessHeap(), 0, ai->language );
339 }
340
341 static struct entity* add_entity(struct entity_array *array, DWORD kind)
342 {
343     struct entity*      entity;
344
345     if (array->num == array->allocated)
346     {
347         void *ptr;
348         unsigned int new_count;
349         if (array->base)
350         {
351             new_count = array->allocated * 2;
352             ptr = RtlReAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY,
353                                      array->base, new_count * sizeof(*array->base) );
354         }
355         else
356         {
357             new_count = 4;
358             ptr = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, new_count * sizeof(*array->base) );
359         }
360         if (!ptr) return NULL;
361         array->base = ptr;
362         array->allocated = new_count;
363     }
364     entity = &array->base[array->num++];
365     entity->kind = kind;
366     return entity;
367 }
368
369 static void free_entity_array(struct entity_array *array)
370 {
371     unsigned int i;
372     for (i = 0; i < array->num; i++)
373     {
374         struct entity *entity = &array->base[i];
375         switch (entity->kind)
376         {
377         case ACTIVATION_CONTEXT_SECTION_COM_SERVER_REDIRECTION:
378             RtlFreeHeap(GetProcessHeap(), 0, entity->u.comclass.clsid);
379             break;
380         case ACTIVATION_CONTEXT_SECTION_COM_INTERFACE_REDIRECTION:
381             RtlFreeHeap(GetProcessHeap(), 0, entity->u.proxy.iid);
382             RtlFreeHeap(GetProcessHeap(), 0, entity->u.proxy.name);
383             break;
384         case ACTIVATION_CONTEXT_SECTION_COM_TYPE_LIBRARY_REDIRECTION:
385             RtlFreeHeap(GetProcessHeap(), 0, entity->u.typelib.tlbid);
386             RtlFreeHeap(GetProcessHeap(), 0, entity->u.typelib.version);
387             RtlFreeHeap(GetProcessHeap(), 0, entity->u.typelib.helpdir);
388             break;
389         case ACTIVATION_CONTEXT_SECTION_WINDOW_CLASS_REDIRECTION:
390             RtlFreeHeap(GetProcessHeap(), 0, entity->u.class.name);
391             break;
392         case ACTIVATION_CONTEXT_SECTION_COM_PROGID_REDIRECTION:
393             RtlFreeHeap(GetProcessHeap(), 0, entity->u.clrclass.name);
394             RtlFreeHeap(GetProcessHeap(), 0, entity->u.clrclass.clsid);
395             break;
396         case ACTIVATION_CONTEXT_SECTION_CLR_SURROGATES:
397             RtlFreeHeap(GetProcessHeap(), 0, entity->u.clrsurrogate.name);
398             RtlFreeHeap(GetProcessHeap(), 0, entity->u.clrsurrogate.clsid);
399             break;
400         default:
401             FIXME("Unknown entity kind %d\n", entity->kind);
402         }
403     }
404     RtlFreeHeap( GetProcessHeap(), 0, array->base );
405 }
406
407 static BOOL is_matching_string( const WCHAR *str1, const WCHAR *str2 )
408 {
409     if (!str1) return !str2;
410     return str2 && !strcmpiW( str1, str2 );
411 }
412
413 static BOOL is_matching_identity( const struct assembly_identity *id1,
414                                   const struct assembly_identity *id2 )
415 {
416     if (!is_matching_string( id1->name, id2->name )) return FALSE;
417     if (!is_matching_string( id1->arch, id2->arch )) return FALSE;
418     if (!is_matching_string( id1->public_key, id2->public_key )) return FALSE;
419
420     if (id1->language && id2->language && strcmpiW( id1->language, id2->language ))
421     {
422         static const WCHAR wildcardW[] = {'*',0};
423         if (strcmpW( wildcardW, id1->language ) && strcmpW( wildcardW, id2->language ))
424             return FALSE;
425     }
426     if (id1->version.major != id2->version.major) return FALSE;
427     if (id1->version.minor != id2->version.minor) return FALSE;
428     if (id1->version.build > id2->version.build) return FALSE;
429     if (id1->version.build == id2->version.build &&
430         id1->version.revision > id2->version.revision) return FALSE;
431     return TRUE;
432 }
433
434 static BOOL add_dependent_assembly_id(struct actctx_loader* acl,
435                                       struct assembly_identity* ai)
436 {
437     unsigned int i;
438
439     /* check if we already have that assembly */
440
441     for (i = 0; i < acl->actctx->num_assemblies; i++)
442         if (is_matching_identity( ai, &acl->actctx->assemblies[i].id ))
443         {
444             TRACE( "reusing existing assembly for %s arch %s version %u.%u.%u.%u\n",
445                    debugstr_w(ai->name), debugstr_w(ai->arch), ai->version.major, ai->version.minor,
446                    ai->version.build, ai->version.revision );
447             return TRUE;
448         }
449
450     for (i = 0; i < acl->num_dependencies; i++)
451         if (is_matching_identity( ai, &acl->dependencies[i] ))
452         {
453             TRACE( "reusing existing dependency for %s arch %s version %u.%u.%u.%u\n",
454                    debugstr_w(ai->name), debugstr_w(ai->arch), ai->version.major, ai->version.minor,
455                    ai->version.build, ai->version.revision );
456             return TRUE;
457         }
458
459     if (acl->num_dependencies == acl->allocated_dependencies)
460     {
461         void *ptr;
462         unsigned int new_count;
463         if (acl->dependencies)
464         {
465             new_count = acl->allocated_dependencies * 2;
466             ptr = RtlReAllocateHeap(GetProcessHeap(), 0, acl->dependencies,
467                                     new_count * sizeof(acl->dependencies[0]));
468         }
469         else
470         {
471             new_count = 4;
472             ptr = RtlAllocateHeap(GetProcessHeap(), 0, new_count * sizeof(acl->dependencies[0]));
473         }
474         if (!ptr) return FALSE;
475         acl->dependencies = ptr;
476         acl->allocated_dependencies = new_count;
477     }
478     acl->dependencies[acl->num_dependencies++] = *ai;
479
480     return TRUE;
481 }
482
483 static void free_depend_manifests(struct actctx_loader* acl)
484 {
485     unsigned int i;
486     for (i = 0; i < acl->num_dependencies; i++)
487         free_assembly_identity(&acl->dependencies[i]);
488     RtlFreeHeap(GetProcessHeap(), 0, acl->dependencies);
489 }
490
491 static WCHAR *build_assembly_dir(struct assembly_identity* ai)
492 {
493     static const WCHAR undW[] = {'_',0};
494     static const WCHAR noneW[] = {'n','o','n','e',0};
495     static const WCHAR mskeyW[] = {'d','e','a','d','b','e','e','f',0};
496
497     const WCHAR *key = ai->public_key ? ai->public_key : noneW;
498     const WCHAR *lang = ai->language ? ai->language : noneW;
499     SIZE_T size = (strlenW(ai->arch) + 1 + strlenW(ai->name) + 1 + strlenW(key) + 24 + 1 +
500                    strlenW(lang) + 1) * sizeof(WCHAR) + sizeof(mskeyW);
501     WCHAR *ret;
502
503     if (!(ret = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return NULL;
504
505     strcpyW( ret, ai->arch );
506     strcatW( ret, undW );
507     strcatW( ret, ai->name );
508     strcatW( ret, undW );
509     strcatW( ret, key );
510     strcatW( ret, undW );
511     sprintfW( ret + strlenW(ret), version_formatW,
512               ai->version.major, ai->version.minor, ai->version.build, ai->version.revision );
513     strcatW( ret, undW );
514     strcatW( ret, lang );
515     strcatW( ret, undW );
516     strcatW( ret, mskeyW );
517     return ret;
518 }
519
520 static inline void append_string( WCHAR *buffer, const WCHAR *prefix, const WCHAR *str )
521 {
522     WCHAR *p = buffer;
523
524     if (!str) return;
525     strcatW( buffer, prefix );
526     p += strlenW(p);
527     *p++ = '"';
528     strcpyW( p, str );
529     p += strlenW(p);
530     *p++ = '"';
531     *p = 0;
532 }
533
534 static WCHAR *build_assembly_id( const struct assembly_identity *ai )
535 {
536     static const WCHAR archW[] =
537         {',','p','r','o','c','e','s','s','o','r','A','r','c','h','i','t','e','c','t','u','r','e','=',0};
538     static const WCHAR public_keyW[] =
539         {',','p','u','b','l','i','c','K','e','y','T','o','k','e','n','=',0};
540     static const WCHAR typeW[] =
541         {',','t','y','p','e','=',0};
542     static const WCHAR versionW[] =
543         {',','v','e','r','s','i','o','n','=',0};
544
545     WCHAR version[64], *ret;
546     SIZE_T size = 0;
547
548     sprintfW( version, version_formatW,
549               ai->version.major, ai->version.minor, ai->version.build, ai->version.revision );
550     if (ai->name) size += strlenW(ai->name) * sizeof(WCHAR);
551     if (ai->arch) size += strlenW(archW) + strlenW(ai->arch) + 2;
552     if (ai->public_key) size += strlenW(public_keyW) + strlenW(ai->public_key) + 2;
553     if (ai->type) size += strlenW(typeW) + strlenW(ai->type) + 2;
554     size += strlenW(versionW) + strlenW(version) + 2;
555
556     if (!(ret = RtlAllocateHeap( GetProcessHeap(), 0, (size + 1) * sizeof(WCHAR) )))
557         return NULL;
558
559     if (ai->name) strcpyW( ret, ai->name );
560     else *ret = 0;
561     append_string( ret, archW, ai->arch );
562     append_string( ret, public_keyW, ai->public_key );
563     append_string( ret, typeW, ai->type );
564     append_string( ret, versionW, version );
565     return ret;
566 }
567
568 static ACTIVATION_CONTEXT *check_actctx( HANDLE h )
569 {
570     ACTIVATION_CONTEXT *actctx = h;
571
572     if (!h || h == INVALID_HANDLE_VALUE) return NULL;
573     switch (actctx->magic)
574     {
575     case ACTCTX_MAGIC:
576         return actctx;
577     default:
578         return NULL;
579     }
580 }
581
582 static inline void actctx_addref( ACTIVATION_CONTEXT *actctx )
583 {
584     interlocked_xchg_add( &actctx->ref_count, 1 );
585 }
586
587 static void actctx_release( ACTIVATION_CONTEXT *actctx )
588 {
589     if (interlocked_xchg_add( &actctx->ref_count, -1 ) == 1)
590     {
591         unsigned int i, j;
592
593         for (i = 0; i < actctx->num_assemblies; i++)
594         {
595             struct assembly *assembly = &actctx->assemblies[i];
596             for (j = 0; j < assembly->num_dlls; j++)
597             {
598                 struct dll_redirect *dll = &assembly->dlls[j];
599                 free_entity_array( &dll->entities );
600                 RtlFreeHeap( GetProcessHeap(), 0, dll->name );
601                 RtlFreeHeap( GetProcessHeap(), 0, dll->hash );
602             }
603             RtlFreeHeap( GetProcessHeap(), 0, assembly->dlls );
604             RtlFreeHeap( GetProcessHeap(), 0, assembly->manifest.info );
605             RtlFreeHeap( GetProcessHeap(), 0, assembly->directory );
606             free_entity_array( &assembly->entities );
607             free_assembly_identity(&assembly->id);
608         }
609         RtlFreeHeap( GetProcessHeap(), 0, actctx->config.info );
610         RtlFreeHeap( GetProcessHeap(), 0, actctx->appdir.info );
611         RtlFreeHeap( GetProcessHeap(), 0, actctx->assemblies );
612         actctx->magic = 0;
613         RtlFreeHeap( GetProcessHeap(), 0, actctx );
614     }
615 }
616
617 static BOOL next_xml_attr(xmlbuf_t* xmlbuf, xmlstr_t* name, xmlstr_t* value,
618                           BOOL* error, BOOL* end)
619 {
620     const WCHAR* ptr;
621
622     *error = TRUE;
623
624     while (xmlbuf->ptr < xmlbuf->end && isxmlspace(*xmlbuf->ptr))
625         xmlbuf->ptr++;
626
627     if (xmlbuf->ptr == xmlbuf->end) return FALSE;
628
629     if (*xmlbuf->ptr == '/')
630     {
631         xmlbuf->ptr++;
632         if (xmlbuf->ptr == xmlbuf->end || *xmlbuf->ptr != '>')
633             return FALSE;
634
635         xmlbuf->ptr++;
636         *end = TRUE;
637         *error = FALSE;
638         return FALSE;
639     }
640
641     if (*xmlbuf->ptr == '>')
642     {
643         xmlbuf->ptr++;
644         *error = FALSE;
645         return FALSE;
646     }
647
648     ptr = xmlbuf->ptr;
649     while (ptr < xmlbuf->end && *ptr != '=' && *ptr != '>' && !isxmlspace(*ptr)) ptr++;
650
651     if (ptr == xmlbuf->end || *ptr != '=') return FALSE;
652
653     name->ptr = xmlbuf->ptr;
654     name->len = ptr-xmlbuf->ptr;
655     xmlbuf->ptr = ptr;
656
657     ptr++;
658     if (ptr == xmlbuf->end || (*ptr != '"' && *ptr != '\'')) return FALSE;
659
660     value->ptr = ++ptr;
661     if (ptr == xmlbuf->end) return FALSE;
662
663     ptr = memchrW(ptr, ptr[-1], xmlbuf->end - ptr);
664     if (!ptr)
665     {
666         xmlbuf->ptr = xmlbuf->end;
667         return FALSE;
668     }
669
670     value->len = ptr - value->ptr;
671     xmlbuf->ptr = ptr + 1;
672
673     if (xmlbuf->ptr == xmlbuf->end) return FALSE;
674
675     *error = FALSE;
676     return TRUE;
677 }
678
679 static BOOL next_xml_elem(xmlbuf_t* xmlbuf, xmlstr_t* elem)
680 {
681     const WCHAR* ptr;
682
683     for (;;)
684     {
685         ptr = memchrW(xmlbuf->ptr, '<', xmlbuf->end - xmlbuf->ptr);
686         if (!ptr)
687         {
688             xmlbuf->ptr = xmlbuf->end;
689             return FALSE;
690         }
691         ptr++;
692         if (ptr + 3 < xmlbuf->end && ptr[0] == '!' && ptr[1] == '-' && ptr[2] == '-') /* skip comment */
693         {
694             for (ptr += 3; ptr + 3 <= xmlbuf->end; ptr++)
695                 if (ptr[0] == '-' && ptr[1] == '-' && ptr[2] == '>') break;
696
697             if (ptr + 3 > xmlbuf->end)
698             {
699                 xmlbuf->ptr = xmlbuf->end;
700                 return FALSE;
701             }
702             xmlbuf->ptr = ptr + 3;
703         }
704         else break;
705     }
706
707     xmlbuf->ptr = ptr;
708     while (ptr < xmlbuf->end && !isxmlspace(*ptr) && *ptr != '>' && (*ptr != '/' || ptr == xmlbuf->ptr))
709         ptr++;
710
711     elem->ptr = xmlbuf->ptr;
712     elem->len = ptr - xmlbuf->ptr;
713     xmlbuf->ptr = ptr;
714     return xmlbuf->ptr != xmlbuf->end;
715 }
716
717 static BOOL parse_xml_header(xmlbuf_t* xmlbuf)
718 {
719     /* FIXME: parse attributes */
720     const WCHAR *ptr;
721
722     for (ptr = xmlbuf->ptr; ptr < xmlbuf->end - 1; ptr++)
723     {
724         if (ptr[0] == '?' && ptr[1] == '>')
725         {
726             xmlbuf->ptr = ptr + 2;
727             return TRUE;
728         }
729     }
730     return FALSE;
731 }
732
733 static BOOL parse_text_content(xmlbuf_t* xmlbuf, xmlstr_t* content)
734 {
735     const WCHAR *ptr = memchrW(xmlbuf->ptr, '<', xmlbuf->end - xmlbuf->ptr);
736
737     if (!ptr) return FALSE;
738
739     content->ptr = xmlbuf->ptr;
740     content->len = ptr - xmlbuf->ptr;
741     xmlbuf->ptr = ptr;
742
743     return TRUE;
744 }
745
746 static BOOL parse_version(const xmlstr_t *str, struct version *version)
747 {
748     unsigned int ver[4];
749     unsigned int pos;
750     const WCHAR *curr;
751
752     /* major.minor.build.revision */
753     ver[0] = ver[1] = ver[2] = ver[3] = pos = 0;
754     for (curr = str->ptr; curr < str->ptr + str->len; curr++)
755     {
756         if (*curr >= '0' && *curr <= '9')
757         {
758             ver[pos] = ver[pos] * 10 + *curr - '0';
759             if (ver[pos] >= 0x10000) goto error;
760         }
761         else if (*curr == '.')
762         {
763             if (++pos >= 4) goto error;
764         }
765         else goto error;
766     }
767     version->major = ver[0];
768     version->minor = ver[1];
769     version->build = ver[2];
770     version->revision = ver[3];
771     return TRUE;
772
773 error:
774     FIXME( "Wrong version definition in manifest file (%s)\n", debugstr_xmlstr(str) );
775     return FALSE;
776 }
777
778 static BOOL parse_expect_elem(xmlbuf_t* xmlbuf, const WCHAR* name)
779 {
780     xmlstr_t    elem;
781     if (!next_xml_elem(xmlbuf, &elem)) return FALSE;
782     if (xmlstr_cmp(&elem, name)) return TRUE;
783     FIXME( "unexpected element %s\n", debugstr_xmlstr(&elem) );
784     return FALSE;
785 }
786
787 static BOOL parse_expect_no_attr(xmlbuf_t* xmlbuf, BOOL* end)
788 {
789     xmlstr_t    attr_name, attr_value;
790     BOOL        error;
791
792     while (next_xml_attr(xmlbuf, &attr_name, &attr_value, &error, end))
793     {
794         WARN("unexpected attr %s=%s\n", debugstr_xmlstr(&attr_name),
795              debugstr_xmlstr(&attr_value));
796     }
797     return !error;
798 }
799
800 static BOOL parse_end_element(xmlbuf_t *xmlbuf)
801 {
802     BOOL end = FALSE;
803     return parse_expect_no_attr(xmlbuf, &end) && !end;
804 }
805
806 static BOOL parse_expect_end_elem(xmlbuf_t *xmlbuf, const WCHAR *name)
807 {
808     xmlstr_t    elem;
809     if (!next_xml_elem(xmlbuf, &elem)) return FALSE;
810     if (!xmlstr_cmp_end(&elem, name))
811     {
812         FIXME( "unexpected element %s\n", debugstr_xmlstr(&elem) );
813         return FALSE;
814     }
815     return parse_end_element(xmlbuf);
816 }
817
818 static BOOL parse_unknown_elem(xmlbuf_t *xmlbuf, const xmlstr_t *unknown_elem)
819 {
820     xmlstr_t attr_name, attr_value, elem;
821     BOOL end = FALSE, error, ret = TRUE;
822
823     while(next_xml_attr(xmlbuf, &attr_name, &attr_value, &error, &end));
824     if(error || end) return end;
825
826     while(ret && (ret = next_xml_elem(xmlbuf, &elem)))
827     {
828         if(*elem.ptr == '/' && elem.len - 1 == unknown_elem->len &&
829            !strncmpW(elem.ptr+1, unknown_elem->ptr, unknown_elem->len))
830             break;
831         else
832             ret = parse_unknown_elem(xmlbuf, &elem);
833     }
834
835     return ret && parse_end_element(xmlbuf);
836 }
837
838 static BOOL parse_assembly_identity_elem(xmlbuf_t* xmlbuf, ACTIVATION_CONTEXT* actctx,
839                                          struct assembly_identity* ai)
840 {
841     xmlstr_t    attr_name, attr_value;
842     BOOL        end = FALSE, error;
843
844     while (next_xml_attr(xmlbuf, &attr_name, &attr_value, &error, &end))
845     {
846         if (xmlstr_cmp(&attr_name, nameW))
847         {
848             if (!(ai->name = xmlstrdupW(&attr_value))) return FALSE;
849         }
850         else if (xmlstr_cmp(&attr_name, typeW))
851         {
852             if (!(ai->type = xmlstrdupW(&attr_value))) return FALSE;
853         }
854         else if (xmlstr_cmp(&attr_name, versionW))
855         {
856             if (!parse_version(&attr_value, &ai->version)) return FALSE;
857         }
858         else if (xmlstr_cmp(&attr_name, processorArchitectureW))
859         {
860             if (!(ai->arch = xmlstrdupW(&attr_value))) return FALSE;
861         }
862         else if (xmlstr_cmp(&attr_name, publicKeyTokenW))
863         {
864             if (!(ai->public_key = xmlstrdupW(&attr_value))) return FALSE;
865         }
866         else if (xmlstr_cmp(&attr_name, languageW))
867         {
868             WARN("Unsupported yet language attribute (%s)\n",
869                  debugstr_xmlstr(&attr_value));
870             if (!(ai->language = xmlstrdupW(&attr_value))) return FALSE;
871         }
872         else
873         {
874             WARN("unknown attr %s=%s\n", debugstr_xmlstr(&attr_name),
875                  debugstr_xmlstr(&attr_value));
876         }
877     }
878
879     TRACE( "name=%s version=%s arch=%s\n",
880            debugstr_w(ai->name), debugstr_version(&ai->version), debugstr_w(ai->arch) );
881
882     if (error || end) return end;
883     return parse_expect_end_elem(xmlbuf, assemblyIdentityW);
884 }
885
886 static BOOL parse_com_class_elem(xmlbuf_t* xmlbuf, struct dll_redirect* dll)
887 {
888     xmlstr_t elem, attr_name, attr_value;
889     BOOL ret, end = FALSE, error;
890     struct entity*      entity;
891
892     if (!(entity = add_entity(&dll->entities, ACTIVATION_CONTEXT_SECTION_COM_SERVER_REDIRECTION)))
893         return FALSE;
894
895     while (next_xml_attr(xmlbuf, &attr_name, &attr_value, &error, &end))
896     {
897         if (xmlstr_cmp(&attr_name, clsidW))
898         {
899             if (!(entity->u.comclass.clsid = xmlstrdupW(&attr_value))) return FALSE;
900         }
901         else
902         {
903             WARN("unknown attr %s=%s\n", debugstr_xmlstr(&attr_name), debugstr_xmlstr(&attr_value));
904         }
905     }
906
907     if (error || end) return end;
908
909     while ((ret = next_xml_elem(xmlbuf, &elem)))
910     {
911         if (xmlstr_cmp_end(&elem, comClassW))
912         {
913             ret = parse_end_element(xmlbuf);
914             break;
915         }
916         else
917         {
918             WARN("unknown elem %s\n", debugstr_xmlstr(&elem));
919             ret = parse_unknown_elem(xmlbuf, &elem);
920         }
921     }
922     return ret;
923 }
924
925 static BOOL parse_cominterface_proxy_stub_elem(xmlbuf_t* xmlbuf, struct dll_redirect* dll)
926 {
927     xmlstr_t    attr_name, attr_value;
928     BOOL        end = FALSE, error;
929     struct entity*      entity;
930
931     if (!(entity = add_entity(&dll->entities, ACTIVATION_CONTEXT_SECTION_COM_INTERFACE_REDIRECTION)))
932         return FALSE;
933
934     while (next_xml_attr(xmlbuf, &attr_name, &attr_value, &error, &end))
935     {
936         if (xmlstr_cmp(&attr_name, iidW))
937         {
938             if (!(entity->u.proxy.iid = xmlstrdupW(&attr_value))) return FALSE;
939         }
940         if (xmlstr_cmp(&attr_name, nameW))
941         {
942             if (!(entity->u.proxy.name = xmlstrdupW(&attr_value))) return FALSE;
943         }
944         else
945         {
946             WARN("unknown attr %s=%s\n", debugstr_xmlstr(&attr_name), debugstr_xmlstr(&attr_value));
947         }
948     }
949
950     if (error || end) return end;
951     return parse_expect_end_elem(xmlbuf, comInterfaceProxyStubW);
952 }
953
954 static BOOL parse_typelib_elem(xmlbuf_t* xmlbuf, struct dll_redirect* dll)
955 {
956     xmlstr_t    attr_name, attr_value;
957     BOOL        end = FALSE, error;
958     struct entity*      entity;
959
960     if (!(entity = add_entity(&dll->entities, ACTIVATION_CONTEXT_SECTION_COM_TYPE_LIBRARY_REDIRECTION)))
961         return FALSE;
962
963     while (next_xml_attr(xmlbuf, &attr_name, &attr_value, &error, &end))
964     {
965         if (xmlstr_cmp(&attr_name, tlbidW))
966         {
967             if (!(entity->u.typelib.tlbid = xmlstrdupW(&attr_value))) return FALSE;
968         }
969         if (xmlstr_cmp(&attr_name, versionW))
970         {
971             if (!(entity->u.typelib.version = xmlstrdupW(&attr_value))) return FALSE;
972         }
973         if (xmlstr_cmp(&attr_name, helpdirW))
974         {
975             if (!(entity->u.typelib.helpdir = xmlstrdupW(&attr_value))) return FALSE;
976         }
977         else
978         {
979             WARN("unknown attr %s=%s\n", debugstr_xmlstr(&attr_name), debugstr_xmlstr(&attr_value));
980         }
981     }
982
983     if (error || end) return end;
984     return parse_expect_end_elem(xmlbuf, typelibW);
985 }
986
987 static BOOL parse_window_class_elem(xmlbuf_t* xmlbuf, struct dll_redirect* dll)
988 {
989     xmlstr_t    elem, content;
990     BOOL        end = FALSE, ret = TRUE;
991     struct entity*      entity;
992
993     if (!(entity = add_entity(&dll->entities, ACTIVATION_CONTEXT_SECTION_WINDOW_CLASS_REDIRECTION)))
994         return FALSE;
995
996     if (!parse_expect_no_attr(xmlbuf, &end)) return FALSE;
997     if (end) return FALSE;
998
999     if (!parse_text_content(xmlbuf, &content)) return FALSE;
1000
1001     if (!(entity->u.class.name = xmlstrdupW(&content))) return FALSE;
1002
1003     while (ret && (ret = next_xml_elem(xmlbuf, &elem)))
1004     {
1005         if (xmlstr_cmp_end(&elem, windowClassW))
1006         {
1007             ret = parse_end_element(xmlbuf);
1008             break;
1009         }
1010         else
1011         {
1012             WARN("unknown elem %s\n", debugstr_xmlstr(&elem));
1013             ret = parse_unknown_elem(xmlbuf, &elem);
1014         }
1015     }
1016
1017     return ret;
1018 }
1019
1020 static BOOL parse_binding_redirect_elem(xmlbuf_t* xmlbuf)
1021 {
1022     xmlstr_t    attr_name, attr_value;
1023     BOOL        end = FALSE, error;
1024
1025     while (next_xml_attr(xmlbuf, &attr_name, &attr_value, &error, &end))
1026     {
1027         if (xmlstr_cmp(&attr_name, oldVersionW))
1028         {
1029             FIXME("Not stored yet oldVersion=%s\n", debugstr_xmlstr(&attr_value));
1030         }
1031         else if (xmlstr_cmp(&attr_name, newVersionW))
1032         {
1033             FIXME("Not stored yet newVersion=%s\n", debugstr_xmlstr(&attr_value));
1034         }
1035         else
1036         {
1037             WARN("unknown attr %s=%s\n", debugstr_xmlstr(&attr_name), debugstr_xmlstr(&attr_value));
1038         }
1039     }
1040
1041     if (error || end) return end;
1042     return parse_expect_end_elem(xmlbuf, bindingRedirectW);
1043 }
1044
1045 static BOOL parse_description_elem(xmlbuf_t* xmlbuf)
1046 {
1047     xmlstr_t    elem, content;
1048     BOOL        end = FALSE, ret = TRUE;
1049
1050     if (!parse_expect_no_attr(xmlbuf, &end) || end ||
1051         !parse_text_content(xmlbuf, &content))
1052         return FALSE;
1053
1054     TRACE("Got description %s\n", debugstr_xmlstr(&content));
1055
1056     while (ret && (ret = next_xml_elem(xmlbuf, &elem)))
1057     {
1058         if (xmlstr_cmp_end(&elem, descriptionW))
1059         {
1060             ret = parse_end_element(xmlbuf);
1061             break;
1062         }
1063         else
1064         {
1065             WARN("unknown elem %s\n", debugstr_xmlstr(&elem));
1066             ret = parse_unknown_elem(xmlbuf, &elem);
1067         }
1068     }
1069
1070     return ret;
1071 }
1072
1073 static BOOL parse_com_interface_external_proxy_stub_elem(xmlbuf_t* xmlbuf,
1074                                                          struct assembly* assembly)
1075 {
1076     xmlstr_t            attr_name, attr_value;
1077     BOOL                end = FALSE, error;
1078     struct entity*      entity;
1079
1080     entity = add_entity(&assembly->entities, ACTIVATION_CONTEXT_SECTION_COM_INTERFACE_REDIRECTION);
1081     if (!entity) return FALSE;
1082
1083     while (next_xml_attr(xmlbuf, &attr_name, &attr_value, &error, &end))
1084     {
1085         if (xmlstr_cmp(&attr_name, iidW))
1086         {
1087             if (!(entity->u.proxy.iid = xmlstrdupW(&attr_value))) return FALSE;
1088         }
1089         if (xmlstr_cmp(&attr_name, nameW))
1090         {
1091             if (!(entity->u.proxy.name = xmlstrdupW(&attr_value))) return FALSE;
1092         }
1093         else
1094         {
1095             WARN("unknown attr %s=%s\n", debugstr_xmlstr(&attr_name), debugstr_xmlstr(&attr_value));
1096         }
1097     }
1098
1099     if (error || end) return end;
1100     return parse_expect_end_elem(xmlbuf, comInterfaceExternalProxyStubW);
1101 }
1102
1103 static BOOL parse_clr_class_elem(xmlbuf_t* xmlbuf, struct assembly* assembly)
1104 {
1105     xmlstr_t    attr_name, attr_value;
1106     BOOL        end = FALSE, error;
1107     struct entity*      entity;
1108
1109     entity = add_entity(&assembly->entities, ACTIVATION_CONTEXT_SECTION_COM_PROGID_REDIRECTION);
1110     if (!entity) return FALSE;
1111
1112     while (next_xml_attr(xmlbuf, &attr_name, &attr_value, &error, &end))
1113     {
1114         if (xmlstr_cmp(&attr_name, nameW))
1115         {
1116             if (!(entity->u.clrclass.name = xmlstrdupW(&attr_value))) return FALSE;
1117         }
1118         else if (xmlstr_cmp(&attr_name, clsidW))
1119         {
1120             if (!(entity->u.clrclass.clsid = xmlstrdupW(&attr_value))) return FALSE;
1121         }
1122         else
1123         {
1124             WARN("unknown attr %s=%s\n", debugstr_xmlstr(&attr_name), debugstr_xmlstr(&attr_value));
1125         }
1126     }
1127
1128     if (error || end) return end;
1129     return parse_expect_end_elem(xmlbuf, clrClassW);
1130 }
1131
1132 static BOOL parse_clr_surrogate_elem(xmlbuf_t* xmlbuf, struct assembly* assembly)
1133 {
1134     xmlstr_t    attr_name, attr_value;
1135     BOOL        end = FALSE, error;
1136     struct entity*      entity;
1137
1138     entity = add_entity(&assembly->entities, ACTIVATION_CONTEXT_SECTION_CLR_SURROGATES);
1139     if (!entity) return FALSE;
1140
1141     while (next_xml_attr(xmlbuf, &attr_name, &attr_value, &error, &end))
1142     {
1143         if (xmlstr_cmp(&attr_name, nameW))
1144         {
1145             if (!(entity->u.clrsurrogate.name = xmlstrdupW(&attr_value))) return FALSE;
1146         }
1147         else if (xmlstr_cmp(&attr_name, clsidW))
1148         {
1149             if (!(entity->u.clrsurrogate.clsid = xmlstrdupW(&attr_value))) return FALSE;
1150         }
1151         else
1152         {
1153             WARN("unknown attr %s=%s\n", debugstr_xmlstr(&attr_name), debugstr_xmlstr(&attr_value));
1154         }
1155     }
1156
1157     if (error || end) return end;
1158     return parse_expect_end_elem(xmlbuf, clrSurrogateW);
1159 }
1160
1161 static BOOL parse_dependent_assembly_elem(xmlbuf_t* xmlbuf, struct actctx_loader* acl, BOOL optional)
1162 {
1163     struct assembly_identity    ai;
1164     xmlstr_t                    elem;
1165     BOOL                        end = FALSE, ret = TRUE;
1166
1167     if (!parse_expect_no_attr(xmlbuf, &end) || end) return end;
1168
1169     memset(&ai, 0, sizeof(ai));
1170     ai.optional = optional;
1171
1172     if (!parse_expect_elem(xmlbuf, assemblyIdentityW) ||
1173         !parse_assembly_identity_elem(xmlbuf, acl->actctx, &ai))
1174         return FALSE;
1175
1176     TRACE( "adding name=%s version=%s arch=%s\n",
1177            debugstr_w(ai.name), debugstr_version(&ai.version), debugstr_w(ai.arch) );
1178
1179     /* store the newly found identity for later loading */
1180     if (!add_dependent_assembly_id(acl, &ai)) return FALSE;
1181
1182     while (ret && (ret = next_xml_elem(xmlbuf, &elem)))
1183     {
1184         if (xmlstr_cmp_end(&elem, dependentAssemblyW))
1185         {
1186             ret = parse_end_element(xmlbuf);
1187             break;
1188         }
1189         else if (xmlstr_cmp(&elem, bindingRedirectW))
1190         {
1191             ret = parse_binding_redirect_elem(xmlbuf);
1192         }
1193         else
1194         {
1195             WARN("unknown elem %s\n", debugstr_xmlstr(&elem));
1196             ret = parse_unknown_elem(xmlbuf, &elem);
1197         }
1198     }
1199
1200     return ret;
1201 }
1202
1203 static BOOL parse_dependency_elem(xmlbuf_t* xmlbuf, struct actctx_loader* acl)
1204 {
1205     xmlstr_t attr_name, attr_value, elem;
1206     BOOL end = FALSE, ret = TRUE, error, optional = FALSE;
1207
1208     while (next_xml_attr(xmlbuf, &attr_name, &attr_value, &error, &end))
1209     {
1210         if (xmlstr_cmp(&attr_name, optionalW))
1211         {
1212             static const WCHAR yesW[] = {'y','e','s',0};
1213             optional = xmlstr_cmpi( &attr_value, yesW );
1214             TRACE("optional=%s\n", debugstr_xmlstr(&attr_value));
1215         }
1216         else
1217         {
1218             WARN("unknown attr %s=%s\n", debugstr_xmlstr(&attr_name), debugstr_xmlstr(&attr_value));
1219         }
1220     }
1221
1222     while (ret && (ret = next_xml_elem(xmlbuf, &elem)))
1223     {
1224         if (xmlstr_cmp_end(&elem, dependencyW))
1225         {
1226             ret = parse_end_element(xmlbuf);
1227             break;
1228         }
1229         else if (xmlstr_cmp(&elem, dependentAssemblyW))
1230         {
1231             ret = parse_dependent_assembly_elem(xmlbuf, acl, optional);
1232         }
1233         else
1234         {
1235             WARN("unknown element %s\n", debugstr_xmlstr(&elem));
1236             ret = parse_unknown_elem(xmlbuf, &elem);
1237         }
1238     }
1239
1240     return ret;
1241 }
1242
1243 static BOOL parse_noinherit_elem(xmlbuf_t* xmlbuf)
1244 {
1245     BOOL end = FALSE;
1246
1247     if (!parse_expect_no_attr(xmlbuf, &end)) return FALSE;
1248     return end || parse_expect_end_elem(xmlbuf, noInheritW);
1249 }
1250
1251 static BOOL parse_noinheritable_elem(xmlbuf_t* xmlbuf)
1252 {
1253     BOOL end = FALSE;
1254
1255     if (!parse_expect_no_attr(xmlbuf, &end)) return FALSE;
1256     return end || parse_expect_end_elem(xmlbuf, noInheritableW);
1257 }
1258
1259 static BOOL parse_file_elem(xmlbuf_t* xmlbuf, struct assembly* assembly)
1260 {
1261     xmlstr_t    attr_name, attr_value, elem;
1262     BOOL        end = FALSE, error, ret = TRUE;
1263     struct dll_redirect* dll;
1264
1265     if (!(dll = add_dll_redirect(assembly))) return FALSE;
1266
1267     while (next_xml_attr(xmlbuf, &attr_name, &attr_value, &error, &end))
1268     {
1269         if (xmlstr_cmp(&attr_name, nameW))
1270         {
1271             if (!(dll->name = xmlstrdupW(&attr_value))) return FALSE;
1272             TRACE("name=%s\n", debugstr_xmlstr(&attr_value));
1273         }
1274         else if (xmlstr_cmp(&attr_name, hashW))
1275         {
1276             if (!(dll->hash = xmlstrdupW(&attr_value))) return FALSE;
1277         }
1278         else if (xmlstr_cmp(&attr_name, hashalgW))
1279         {
1280             static const WCHAR sha1W[] = {'S','H','A','1',0};
1281             if (!xmlstr_cmpi(&attr_value, sha1W))
1282                 FIXME("hashalg should be SHA1, got %s\n", debugstr_xmlstr(&attr_value));
1283         }
1284         else
1285         {
1286             WARN("unknown attr %s=%s\n", debugstr_xmlstr(&attr_name), debugstr_xmlstr(&attr_value));
1287         }
1288     }
1289
1290     if (error || !dll->name) return FALSE;
1291     if (end) return TRUE;
1292
1293     while (ret && (ret = next_xml_elem(xmlbuf, &elem)))
1294     {
1295         if (xmlstr_cmp_end(&elem, fileW))
1296         {
1297             ret = parse_end_element(xmlbuf);
1298             break;
1299         }
1300         else if (xmlstr_cmp(&elem, comClassW))
1301         {
1302             ret = parse_com_class_elem(xmlbuf, dll);
1303         }
1304         else if (xmlstr_cmp(&elem, comInterfaceProxyStubW))
1305         {
1306             ret = parse_cominterface_proxy_stub_elem(xmlbuf, dll);
1307         }
1308         else if (xmlstr_cmp(&elem, asmv2hashW))
1309         {
1310             WARN("asmv2hash (undocumented) not supported\n");
1311             ret = parse_unknown_elem(xmlbuf, &elem);
1312         }
1313         else if (xmlstr_cmp(&elem, typelibW))
1314         {
1315             ret = parse_typelib_elem(xmlbuf, dll);
1316         }
1317         else if (xmlstr_cmp(&elem, windowClassW))
1318         {
1319             ret = parse_window_class_elem(xmlbuf, dll);
1320         }
1321         else
1322         {
1323             WARN("unknown elem %s\n", debugstr_xmlstr(&elem));
1324             ret = parse_unknown_elem( xmlbuf, &elem );
1325         }
1326     }
1327
1328     return ret;
1329 }
1330
1331 static BOOL parse_assembly_elem(xmlbuf_t* xmlbuf, struct actctx_loader* acl,
1332                                 struct assembly* assembly,
1333                                 struct assembly_identity* expected_ai)
1334 {
1335     xmlstr_t    attr_name, attr_value, elem;
1336     BOOL        end = FALSE, error, version = FALSE, xmlns = FALSE, ret = TRUE;
1337
1338     TRACE("(%p)\n", xmlbuf);
1339
1340     while (next_xml_attr(xmlbuf, &attr_name, &attr_value, &error, &end))
1341     {
1342         if (xmlstr_cmp(&attr_name, manifestVersionW))
1343         {
1344             static const WCHAR v10W[] = {'1','.','0',0};
1345             if (!xmlstr_cmp(&attr_value, v10W))
1346             {
1347                 FIXME("wrong version %s\n", debugstr_xmlstr(&attr_value));
1348                 return FALSE;
1349             }
1350             version = TRUE;
1351         }
1352         else if (xmlstr_cmp(&attr_name, xmlnsW))
1353         {
1354             if (!xmlstr_cmp(&attr_value, manifestv1W) && !xmlstr_cmp(&attr_value, manifestv3W))
1355             {
1356                 FIXME("wrong namespace %s\n", debugstr_xmlstr(&attr_value));
1357                 return FALSE;
1358             }
1359             xmlns = TRUE;
1360         }
1361         else
1362         {
1363             WARN("unknown attr %s=%s\n", debugstr_xmlstr(&attr_name), debugstr_xmlstr(&attr_value));
1364         }
1365     }
1366
1367     if (error || end || !xmlns || !version) return FALSE;
1368     if (!next_xml_elem(xmlbuf, &elem)) return FALSE;
1369
1370     if (assembly->type == APPLICATION_MANIFEST && xmlstr_cmp(&elem, noInheritW))
1371     {
1372         if (!parse_noinherit_elem(xmlbuf) || !next_xml_elem(xmlbuf, &elem))
1373             return FALSE;
1374         assembly->no_inherit = TRUE;
1375     }
1376
1377     if (xmlstr_cmp(&elem, noInheritableW))
1378     {
1379         if (!parse_noinheritable_elem(xmlbuf) || !next_xml_elem(xmlbuf, &elem))
1380             return FALSE;
1381     }
1382     else if (assembly->type == ASSEMBLY_MANIFEST && assembly->no_inherit)
1383         return FALSE;
1384
1385     if (xmlstr_cmp(&elem, assemblyIdentityW))
1386     {
1387         if (!parse_assembly_identity_elem(xmlbuf, acl->actctx, &assembly->id)) return FALSE;
1388         ret = next_xml_elem(xmlbuf, &elem);
1389
1390         if (expected_ai)
1391         {
1392             /* FIXME: more tests */
1393             if (assembly->type == ASSEMBLY_MANIFEST &&
1394                 memcmp(&assembly->id.version, &expected_ai->version, sizeof(assembly->id.version)))
1395             {
1396                 FIXME("wrong version\n");
1397                 return FALSE;
1398             }
1399         }
1400     }
1401
1402     while (ret)
1403     {
1404         if (xmlstr_cmp_end(&elem, assemblyW))
1405         {
1406             ret = parse_end_element(xmlbuf);
1407             break;
1408         }
1409         else if (xmlstr_cmp(&elem, descriptionW))
1410         {
1411             ret = parse_description_elem(xmlbuf);
1412         }
1413         else if (xmlstr_cmp(&elem, comInterfaceExternalProxyStubW))
1414         {
1415             ret = parse_com_interface_external_proxy_stub_elem(xmlbuf, assembly);
1416         }
1417         else if (xmlstr_cmp(&elem, dependencyW))
1418         {
1419             ret = parse_dependency_elem(xmlbuf, acl);
1420         }
1421         else if (xmlstr_cmp(&elem, fileW))
1422         {
1423             ret = parse_file_elem(xmlbuf, assembly);
1424         }
1425         else if (xmlstr_cmp(&elem, clrClassW))
1426         {
1427             ret = parse_clr_class_elem(xmlbuf, assembly);
1428         }
1429         else if (xmlstr_cmp(&elem, clrSurrogateW))
1430         {
1431             ret = parse_clr_surrogate_elem(xmlbuf, assembly);
1432         }
1433         else
1434         {
1435             WARN("unknown element %s\n", debugstr_xmlstr(&elem));
1436             ret = parse_unknown_elem(xmlbuf, &elem);
1437         }
1438         if (ret) ret = next_xml_elem(xmlbuf, &elem);
1439     }
1440
1441     return ret;
1442 }
1443
1444 static NTSTATUS parse_manifest_buffer( struct actctx_loader* acl, struct assembly *assembly,
1445                                        struct assembly_identity* ai, xmlbuf_t *xmlbuf )
1446 {
1447     xmlstr_t elem;
1448
1449     if (!next_xml_elem(xmlbuf, &elem)) return STATUS_SXS_CANT_GEN_ACTCTX;
1450
1451     if (xmlstr_cmp(&elem, xmlW) &&
1452         (!parse_xml_header(xmlbuf) || !next_xml_elem(xmlbuf, &elem)))
1453         return STATUS_SXS_CANT_GEN_ACTCTX;
1454
1455     if (!xmlstr_cmp(&elem, assemblyW))
1456     {
1457         FIXME("root element is %s, not <assembly>\n", debugstr_xmlstr(&elem));
1458         return STATUS_SXS_CANT_GEN_ACTCTX;
1459     }
1460
1461     if (!parse_assembly_elem(xmlbuf, acl, assembly, ai))
1462     {
1463         FIXME("failed to parse manifest %s\n", debugstr_w(assembly->manifest.info) );
1464         return STATUS_SXS_CANT_GEN_ACTCTX;
1465     }
1466
1467     if (next_xml_elem(xmlbuf, &elem))
1468     {
1469         FIXME("unexpected element %s\n", debugstr_xmlstr(&elem));
1470         return STATUS_SXS_CANT_GEN_ACTCTX;
1471     }
1472
1473     if (xmlbuf->ptr != xmlbuf->end)
1474     {
1475         FIXME("parse error\n");
1476         return STATUS_SXS_CANT_GEN_ACTCTX;
1477     }
1478     return STATUS_SUCCESS;
1479 }
1480
1481 static NTSTATUS parse_manifest( struct actctx_loader* acl, struct assembly_identity* ai,
1482                                 LPCWSTR filename, LPCWSTR directory, const void *buffer, SIZE_T size )
1483 {
1484     xmlbuf_t xmlbuf;
1485     NTSTATUS status;
1486     struct assembly *assembly;
1487
1488     TRACE( "parsing manifest loaded from %s base dir %s\n", debugstr_w(filename), debugstr_w(directory) );
1489
1490     if (!(assembly = add_assembly(acl->actctx, ASSEMBLY_MANIFEST)))
1491         return STATUS_SXS_CANT_GEN_ACTCTX;
1492
1493     if (directory && !(assembly->directory = strdupW(directory)))
1494         return STATUS_NO_MEMORY;
1495
1496     if (filename) assembly->manifest.info = strdupW( filename + 4 /* skip \??\ prefix */ );
1497     assembly->manifest.type = assembly->manifest.info ? ACTIVATION_CONTEXT_PATH_TYPE_WIN32_FILE
1498                                                       : ACTIVATION_CONTEXT_PATH_TYPE_NONE;
1499
1500     if (!RtlIsTextUnicode( buffer, size, NULL ))
1501     {
1502         /* let's assume utf-8 for now */
1503         int len = wine_utf8_mbstowcs( 0, buffer, size, NULL, 0 );
1504         WCHAR *new_buff;
1505
1506         if (len == -1)
1507         {
1508             FIXME( "utf-8 conversion failed\n" );
1509             return STATUS_SXS_CANT_GEN_ACTCTX;
1510         }
1511         if (!(new_buff = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR) )))
1512             return STATUS_NO_MEMORY;
1513         wine_utf8_mbstowcs( 0, buffer, size, new_buff, len );
1514         xmlbuf.ptr = new_buff;
1515         xmlbuf.end = xmlbuf.ptr + len;
1516         status = parse_manifest_buffer( acl, assembly, ai, &xmlbuf );
1517         RtlFreeHeap( GetProcessHeap(), 0, new_buff );
1518     }
1519     else
1520     {
1521         xmlbuf.ptr = buffer;
1522         xmlbuf.end = xmlbuf.ptr + size / sizeof(WCHAR);
1523         status = parse_manifest_buffer( acl, assembly, ai, &xmlbuf );
1524     }
1525     return status;
1526 }
1527
1528 static NTSTATUS open_nt_file( HANDLE *handle, UNICODE_STRING *name )
1529 {
1530     OBJECT_ATTRIBUTES attr;
1531     IO_STATUS_BLOCK io;
1532
1533     attr.Length = sizeof(attr);
1534     attr.RootDirectory = 0;
1535     attr.Attributes = OBJ_CASE_INSENSITIVE;
1536     attr.ObjectName = name;
1537     attr.SecurityDescriptor = NULL;
1538     attr.SecurityQualityOfService = NULL;
1539     return NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ, FILE_SYNCHRONOUS_IO_ALERT );
1540 }
1541
1542 static NTSTATUS get_module_filename( HMODULE module, UNICODE_STRING *str, unsigned int extra_len )
1543 {
1544     NTSTATUS status;
1545     ULONG magic;
1546     LDR_MODULE *pldr;
1547
1548     LdrLockLoaderLock(0, NULL, &magic);
1549     status = LdrFindEntryForAddress( module, &pldr );
1550     if (status == STATUS_SUCCESS)
1551     {
1552         if ((str->Buffer = RtlAllocateHeap( GetProcessHeap(), 0,
1553                                             pldr->FullDllName.Length + extra_len + sizeof(WCHAR) )))
1554         {
1555             memcpy( str->Buffer, pldr->FullDllName.Buffer, pldr->FullDllName.Length + sizeof(WCHAR) );
1556             str->Length = pldr->FullDllName.Length;
1557             str->MaximumLength = pldr->FullDllName.Length + extra_len + sizeof(WCHAR);
1558         }
1559         else status = STATUS_NO_MEMORY;
1560     }
1561     LdrUnlockLoaderLock(0, magic);
1562     return status;
1563 }
1564
1565 static NTSTATUS get_manifest_in_module( struct actctx_loader* acl, struct assembly_identity* ai,
1566                                         LPCWSTR filename, LPCWSTR directory, HANDLE hModule,
1567                                         LPCWSTR resname, ULONG lang )
1568 {
1569     NTSTATUS status;
1570     UNICODE_STRING nameW;
1571     LDR_RESOURCE_INFO info;
1572     const IMAGE_RESOURCE_DATA_ENTRY* entry = NULL;
1573     void *ptr;
1574
1575     if (TRACE_ON(actctx))
1576     {
1577         if (!filename && !get_module_filename( hModule, &nameW, 0 ))
1578         {
1579             TRACE( "looking for res %s in module %p %s\n", debugstr_w(resname),
1580                    hModule, debugstr_w(nameW.Buffer) );
1581             RtlFreeUnicodeString( &nameW );
1582         }
1583         else TRACE( "looking for res %s in module %p %s\n", debugstr_w(resname),
1584                     hModule, debugstr_w(filename) );
1585     }
1586
1587     if (!resname) return STATUS_INVALID_PARAMETER;
1588
1589     info.Type = RT_MANIFEST;
1590     info.Language = lang;
1591     if (!((ULONG_PTR)resname >> 16))
1592     {
1593         info.Name = (ULONG_PTR)resname;
1594         status = LdrFindResource_U(hModule, &info, 3, &entry);
1595     }
1596     else if (resname[0] == '#')
1597     {
1598         ULONG value;
1599         RtlInitUnicodeString(&nameW, resname + 1);
1600         if (RtlUnicodeStringToInteger(&nameW, 10, &value) != STATUS_SUCCESS || HIWORD(value))
1601             return STATUS_INVALID_PARAMETER;
1602         info.Name = value;
1603         status = LdrFindResource_U(hModule, &info, 3, &entry);
1604     }
1605     else
1606     {
1607         RtlCreateUnicodeString(&nameW, resname);
1608         RtlUpcaseUnicodeString(&nameW, &nameW, FALSE);
1609         info.Name = (ULONG_PTR)nameW.Buffer;
1610         status = LdrFindResource_U(hModule, &info, 3, &entry);
1611         RtlFreeUnicodeString(&nameW);
1612     }
1613     if (status == STATUS_SUCCESS) status = LdrAccessResource(hModule, entry, &ptr, NULL);
1614
1615     if (status == STATUS_SUCCESS)
1616         status = parse_manifest(acl, ai, filename, directory, ptr, entry->Size);
1617
1618     return status;
1619 }
1620
1621 static NTSTATUS get_manifest_in_pe_file( struct actctx_loader* acl, struct assembly_identity* ai,
1622                                          LPCWSTR filename, LPCWSTR directory, HANDLE file,
1623                                          LPCWSTR resname, ULONG lang )
1624 {
1625     HANDLE              mapping;
1626     OBJECT_ATTRIBUTES   attr;
1627     LARGE_INTEGER       size;
1628     LARGE_INTEGER       offset;
1629     NTSTATUS            status;
1630     SIZE_T              count;
1631     void               *base;
1632
1633     TRACE( "looking for res %s in %s\n", debugstr_w(resname), debugstr_w(filename) );
1634
1635     attr.Length                   = sizeof(attr);
1636     attr.RootDirectory            = 0;
1637     attr.ObjectName               = NULL;
1638     attr.Attributes               = OBJ_CASE_INSENSITIVE | OBJ_OPENIF;
1639     attr.SecurityDescriptor       = NULL;
1640     attr.SecurityQualityOfService = NULL;
1641
1642     size.QuadPart = 0;
1643     status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
1644                               &attr, &size, PAGE_READONLY, SEC_COMMIT, file );
1645     if (status != STATUS_SUCCESS) return status;
1646
1647     offset.QuadPart = 0;
1648     count = 0;
1649     base = NULL;
1650     status = NtMapViewOfSection( mapping, GetCurrentProcess(), &base, 0, 0, &offset,
1651                                  &count, ViewShare, 0, PAGE_READONLY );
1652     NtClose( mapping );
1653     if (status != STATUS_SUCCESS) return status;
1654
1655     if (RtlImageNtHeader(base)) /* we got a PE file */
1656     {
1657         HANDLE module = (HMODULE)((ULONG_PTR)base | 1);  /* make it a LOAD_LIBRARY_AS_DATAFILE handle */
1658         status = get_manifest_in_module( acl, ai, filename, directory, module, resname, lang );
1659     }
1660     else status = STATUS_INVALID_IMAGE_FORMAT;
1661
1662     NtUnmapViewOfSection( GetCurrentProcess(), base );
1663     return status;
1664 }
1665
1666 static NTSTATUS get_manifest_in_manifest_file( struct actctx_loader* acl, struct assembly_identity* ai,
1667                                                LPCWSTR filename, LPCWSTR directory, HANDLE file )
1668 {
1669     FILE_END_OF_FILE_INFORMATION info;
1670     IO_STATUS_BLOCK io;
1671     HANDLE              mapping;
1672     OBJECT_ATTRIBUTES   attr;
1673     LARGE_INTEGER       size;
1674     LARGE_INTEGER       offset;
1675     NTSTATUS            status;
1676     SIZE_T              count;
1677     void               *base;
1678
1679     TRACE( "loading manifest file %s\n", debugstr_w(filename) );
1680
1681     attr.Length                   = sizeof(attr);
1682     attr.RootDirectory            = 0;
1683     attr.ObjectName               = NULL;
1684     attr.Attributes               = OBJ_CASE_INSENSITIVE | OBJ_OPENIF;
1685     attr.SecurityDescriptor       = NULL;
1686     attr.SecurityQualityOfService = NULL;
1687
1688     size.QuadPart = 0;
1689     status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
1690                               &attr, &size, PAGE_READONLY, SEC_COMMIT, file );
1691     if (status != STATUS_SUCCESS) return status;
1692
1693     offset.QuadPart = 0;
1694     count = 0;
1695     base = NULL;
1696     status = NtMapViewOfSection( mapping, GetCurrentProcess(), &base, 0, 0, &offset,
1697                                  &count, ViewShare, 0, PAGE_READONLY );
1698     NtClose( mapping );
1699     if (status != STATUS_SUCCESS) return status;
1700
1701     status = NtQueryInformationFile( file, &io, &info, sizeof(info), FileEndOfFileInformation );
1702     if (status == STATUS_SUCCESS)
1703         status = parse_manifest(acl, ai, filename, directory, base, info.EndOfFile.QuadPart);
1704
1705     NtUnmapViewOfSection( GetCurrentProcess(), base );
1706     return status;
1707 }
1708
1709 /* try to load the .manifest file associated to the file */
1710 static NTSTATUS get_manifest_in_associated_manifest( struct actctx_loader* acl, struct assembly_identity* ai,
1711                                                      LPCWSTR filename, LPCWSTR directory, HMODULE module, LPCWSTR resname )
1712 {
1713     static const WCHAR fmtW[] = { '.','%','l','u',0 };
1714     WCHAR *buffer;
1715     NTSTATUS status;
1716     UNICODE_STRING nameW;
1717     HANDLE file;
1718     ULONG_PTR resid = CREATEPROCESS_MANIFEST_RESOURCE_ID;
1719
1720     if (!((ULONG_PTR)resname >> 16)) resid = (ULONG_PTR)resname & 0xffff;
1721
1722     TRACE( "looking for manifest associated with %s id %lu\n", debugstr_w(filename), resid );
1723
1724     if (module) /* use the module filename */
1725     {
1726         UNICODE_STRING name;
1727
1728         if (!(status = get_module_filename( module, &name, sizeof(dotManifestW) + 10*sizeof(WCHAR) )))
1729         {
1730             if (resid != 1) sprintfW( name.Buffer + strlenW(name.Buffer), fmtW, resid );
1731             strcatW( name.Buffer, dotManifestW );
1732             if (!RtlDosPathNameToNtPathName_U( name.Buffer, &nameW, NULL, NULL ))
1733                 status = STATUS_RESOURCE_DATA_NOT_FOUND;
1734             RtlFreeUnicodeString( &name );
1735         }
1736         if (status) return status;
1737     }
1738     else
1739     {
1740         if (!(buffer = RtlAllocateHeap( GetProcessHeap(), 0,
1741                                         (strlenW(filename) + 10) * sizeof(WCHAR) + sizeof(dotManifestW) )))
1742             return STATUS_NO_MEMORY;
1743         strcpyW( buffer, filename );
1744         if (resid != 1) sprintfW( buffer + strlenW(buffer), fmtW, resid );
1745         strcatW( buffer, dotManifestW );
1746         RtlInitUnicodeString( &nameW, buffer );
1747     }
1748
1749     if (!open_nt_file( &file, &nameW ))
1750     {
1751         status = get_manifest_in_manifest_file( acl, ai, nameW.Buffer, directory, file );
1752         NtClose( file );
1753     }
1754     else status = STATUS_RESOURCE_DATA_NOT_FOUND;
1755     RtlFreeUnicodeString( &nameW );
1756     return status;
1757 }
1758
1759 static WCHAR *lookup_manifest_file( HANDLE dir, struct assembly_identity *ai )
1760 {
1761     static const WCHAR lookup_fmtW[] =
1762         {'%','s','_','%','s','_','%','s','_','%','u','.','%','u','.','*','.','*','_',
1763          '*', /* FIXME */
1764          '.','m','a','n','i','f','e','s','t',0};
1765
1766     WCHAR *lookup, *ret = NULL;
1767     UNICODE_STRING lookup_us;
1768     IO_STATUS_BLOCK io;
1769     unsigned int data_pos = 0, data_len;
1770     char buffer[8192];
1771
1772     if (!(lookup = RtlAllocateHeap( GetProcessHeap(), 0,
1773                                     (strlenW(ai->arch) + strlenW(ai->name)
1774                                      + strlenW(ai->public_key) + 20) * sizeof(WCHAR)
1775                                     + sizeof(lookup_fmtW) )))
1776         return NULL;
1777
1778     sprintfW( lookup, lookup_fmtW, ai->arch, ai->name, ai->public_key, ai->version.major, ai->version.minor);
1779     RtlInitUnicodeString( &lookup_us, lookup );
1780
1781     NtQueryDirectoryFile( dir, 0, NULL, NULL, &io, buffer, sizeof(buffer),
1782                           FileBothDirectoryInformation, FALSE, &lookup_us, TRUE );
1783     if (io.u.Status == STATUS_SUCCESS)
1784     {
1785         FILE_BOTH_DIR_INFORMATION *dir_info;
1786         WCHAR *tmp;
1787         ULONG build, revision;
1788
1789         data_len = io.Information;
1790
1791         for (;;)
1792         {
1793             if (data_pos >= data_len)
1794             {
1795                 NtQueryDirectoryFile( dir, 0, NULL, NULL, &io, buffer, sizeof(buffer),
1796                                       FileBothDirectoryInformation, FALSE, &lookup_us, FALSE );
1797                 if (io.u.Status != STATUS_SUCCESS) break;
1798                 data_len = io.Information;
1799                 data_pos = 0;
1800             }
1801             dir_info = (FILE_BOTH_DIR_INFORMATION*)(buffer + data_pos);
1802
1803             if (dir_info->NextEntryOffset) data_pos += dir_info->NextEntryOffset;
1804             else data_pos = data_len;
1805
1806             tmp = (WCHAR *)dir_info->FileName + (strchrW(lookup, '*') - lookup);
1807             build = atoiW(tmp);
1808             if (build < ai->version.build) continue;
1809             tmp = strchrW(tmp, '.') + 1;
1810             revision = atoiW(tmp);
1811             if (build == ai->version.build && revision < ai->version.revision)
1812                 continue;
1813             ai->version.build = build;
1814             ai->version.revision = revision;
1815             if ((ret = RtlAllocateHeap( GetProcessHeap(), 0, dir_info->FileNameLength + sizeof(WCHAR) )))
1816             {
1817                 memcpy( ret, dir_info->FileName, dir_info->FileNameLength );
1818                 ret[dir_info->FileNameLength/sizeof(WCHAR)] = 0;
1819             }
1820             break;
1821         }
1822     }
1823     else WARN("no matching file for %s\n", debugstr_w(lookup));
1824     RtlFreeHeap( GetProcessHeap(), 0, lookup );
1825     return ret;
1826 }
1827
1828 static NTSTATUS lookup_winsxs(struct actctx_loader* acl, struct assembly_identity* ai)
1829 {
1830     struct assembly_identity    sxs_ai;
1831     UNICODE_STRING              path_us;
1832     OBJECT_ATTRIBUTES           attr;
1833     IO_STATUS_BLOCK             io;
1834     WCHAR *path, *file = NULL;
1835     HANDLE handle;
1836
1837     static const WCHAR manifest_dirW[] =
1838         {'\\','w','i','n','s','x','s','\\','m','a','n','i','f','e','s','t','s',0};
1839
1840     if (!ai->arch || !ai->name || !ai->public_key) return STATUS_NO_SUCH_FILE;
1841
1842     if (!(path = RtlAllocateHeap( GetProcessHeap(), 0, windows_dir.Length + sizeof(manifest_dirW) )))
1843         return STATUS_NO_MEMORY;
1844
1845     memcpy( path, windows_dir.Buffer, windows_dir.Length );
1846     memcpy( path + windows_dir.Length/sizeof(WCHAR), manifest_dirW, sizeof(manifest_dirW) );
1847
1848     if (!RtlDosPathNameToNtPathName_U( path, &path_us, NULL, NULL ))
1849     {
1850         RtlFreeHeap( GetProcessHeap(), 0, path );
1851         return STATUS_NO_SUCH_FILE;
1852     }
1853     RtlFreeHeap( GetProcessHeap(), 0, path );
1854
1855     attr.Length = sizeof(attr);
1856     attr.RootDirectory = 0;
1857     attr.Attributes = OBJ_CASE_INSENSITIVE;
1858     attr.ObjectName = &path_us;
1859     attr.SecurityDescriptor = NULL;
1860     attr.SecurityQualityOfService = NULL;
1861
1862     if (!NtOpenFile( &handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ | FILE_SHARE_WRITE,
1863                      FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT ))
1864     {
1865         sxs_ai = *ai;
1866         file = lookup_manifest_file( handle, &sxs_ai );
1867         NtClose( handle );
1868     }
1869     if (!file)
1870     {
1871         RtlFreeUnicodeString( &path_us );
1872         return STATUS_NO_SUCH_FILE;
1873     }
1874
1875     /* append file name to directory path */
1876     if (!(path = RtlReAllocateHeap( GetProcessHeap(), 0, path_us.Buffer,
1877                                     path_us.Length + (strlenW(file) + 2) * sizeof(WCHAR) )))
1878     {
1879         RtlFreeHeap( GetProcessHeap(), 0, file );
1880         RtlFreeUnicodeString( &path_us );
1881         return STATUS_NO_MEMORY;
1882     }
1883
1884     path[path_us.Length/sizeof(WCHAR)] = '\\';
1885     strcpyW( path + path_us.Length/sizeof(WCHAR) + 1, file );
1886     RtlInitUnicodeString( &path_us, path );
1887     *strrchrW(file, '.') = 0;  /* remove .manifest extension */
1888
1889     if (!open_nt_file( &handle, &path_us ))
1890     {
1891         io.u.Status = get_manifest_in_manifest_file(acl, &sxs_ai, path_us.Buffer, file, handle);
1892         NtClose( handle );
1893     }
1894     else io.u.Status = STATUS_NO_SUCH_FILE;
1895
1896     RtlFreeHeap( GetProcessHeap(), 0, file );
1897     RtlFreeUnicodeString( &path_us );
1898     return io.u.Status;
1899 }
1900
1901 static NTSTATUS lookup_assembly(struct actctx_loader* acl,
1902                                 struct assembly_identity* ai)
1903 {
1904     static const WCHAR dotDllW[] = {'.','d','l','l',0};
1905     unsigned int i;
1906     WCHAR *buffer, *p, *directory;
1907     NTSTATUS status;
1908     UNICODE_STRING nameW;
1909     HANDLE file;
1910
1911     TRACE( "looking for name=%s version=%s arch=%s\n",
1912            debugstr_w(ai->name), debugstr_version(&ai->version), debugstr_w(ai->arch) );
1913
1914     if ((status = lookup_winsxs(acl, ai)) != STATUS_NO_SUCH_FILE) return status;
1915
1916     /* FIXME: add support for language specific lookup */
1917
1918     nameW.Buffer = NULL;
1919     if (!(buffer = RtlAllocateHeap( GetProcessHeap(), 0,
1920                                     (strlenW(acl->actctx->appdir.info) + 2 * strlenW(ai->name) + 2) * sizeof(WCHAR) + sizeof(dotManifestW) )))
1921         return STATUS_NO_MEMORY;
1922
1923     if (!(directory = build_assembly_dir( ai )))
1924     {
1925         RtlFreeHeap( GetProcessHeap(), 0, buffer );
1926         return STATUS_NO_MEMORY;
1927     }
1928
1929     /* lookup in appdir\name.dll
1930      *           appdir\name.manifest
1931      *           appdir\name\name.dll
1932      *           appdir\name\name.manifest
1933      */
1934     strcpyW( buffer, acl->actctx->appdir.info );
1935     p = buffer + strlenW(buffer);
1936     for (i = 0; i < 2; i++)
1937     {
1938         *p++ = '\\';
1939         strcpyW( p, ai->name );
1940         p += strlenW(p);
1941
1942         strcpyW( p, dotDllW );
1943         if (RtlDosPathNameToNtPathName_U( buffer, &nameW, NULL, NULL ))
1944         {
1945             status = open_nt_file( &file, &nameW );
1946             if (!status)
1947             {
1948                 status = get_manifest_in_pe_file( acl, ai, nameW.Buffer, directory, file,
1949                                                   (LPCWSTR)CREATEPROCESS_MANIFEST_RESOURCE_ID, 0 );
1950                 NtClose( file );
1951                 break;
1952             }
1953             RtlFreeUnicodeString( &nameW );
1954         }
1955
1956         strcpyW( p, dotManifestW );
1957         if (RtlDosPathNameToNtPathName_U( buffer, &nameW, NULL, NULL ))
1958         {
1959             status = open_nt_file( &file, &nameW );
1960             if (!status)
1961             {
1962                 status = get_manifest_in_manifest_file( acl, ai, nameW.Buffer, directory, file );
1963                 NtClose( file );
1964                 break;
1965             }
1966             RtlFreeUnicodeString( &nameW );
1967         }
1968         status = STATUS_SXS_ASSEMBLY_NOT_FOUND;
1969     }
1970     RtlFreeUnicodeString( &nameW );
1971     RtlFreeHeap( GetProcessHeap(), 0, directory );
1972     RtlFreeHeap( GetProcessHeap(), 0, buffer );
1973     return status;
1974 }
1975
1976 static NTSTATUS parse_depend_manifests(struct actctx_loader* acl)
1977 {
1978     NTSTATUS status = STATUS_SUCCESS;
1979     unsigned int i;
1980
1981     for (i = 0; i < acl->num_dependencies; i++)
1982     {
1983         if (lookup_assembly(acl, &acl->dependencies[i]) != STATUS_SUCCESS)
1984         {
1985             if (!acl->dependencies[i].optional)
1986             {
1987                 FIXME( "Could not find dependent assembly %s\n", debugstr_w(acl->dependencies[i].name) );
1988                 status = STATUS_SXS_CANT_GEN_ACTCTX;
1989                 break;
1990             }
1991         }
1992     }
1993     /* FIXME should now iterate through all refs */
1994     return status;
1995 }
1996
1997 /* find the appropriate activation context for RtlQueryInformationActivationContext */
1998 static NTSTATUS find_query_actctx( HANDLE *handle, DWORD flags )
1999 {
2000     NTSTATUS status = STATUS_SUCCESS;
2001
2002     if (flags & QUERY_ACTCTX_FLAG_USE_ACTIVE_ACTCTX)
2003     {
2004         if (NtCurrentTeb()->ActivationContextStack.ActiveFrame)
2005             *handle = NtCurrentTeb()->ActivationContextStack.ActiveFrame->ActivationContext;
2006     }
2007     else if (flags & (QUERY_ACTCTX_FLAG_ACTCTX_IS_ADDRESS|QUERY_ACTCTX_FLAG_ACTCTX_IS_HMODULE))
2008     {
2009         ULONG magic;
2010         LDR_MODULE *pldr;
2011
2012         LdrLockLoaderLock( 0, NULL, &magic );
2013         if (!LdrFindEntryForAddress( *handle, &pldr ))
2014         {
2015             if ((flags & QUERY_ACTCTX_FLAG_ACTCTX_IS_HMODULE) && *handle != pldr->BaseAddress)
2016                 status = STATUS_DLL_NOT_FOUND;
2017             else
2018                 *handle = pldr->ActivationContext;
2019         }
2020         else status = STATUS_DLL_NOT_FOUND;
2021         LdrUnlockLoaderLock( 0, magic );
2022     }
2023     else if (!*handle) *handle = process_actctx;
2024
2025     return status;
2026 }
2027
2028 static NTSTATUS fill_keyed_data(PACTCTX_SECTION_KEYED_DATA data, PVOID v1, PVOID v2, unsigned int i)
2029 {
2030     data->ulDataFormatVersion = 1;
2031     data->lpData = v1;
2032     data->ulLength = 20; /* FIXME */
2033     data->lpSectionGlobalData = NULL; /* FIXME */
2034     data->ulSectionGlobalDataLength = 0; /* FIXME */
2035     data->lpSectionBase = v2;
2036     data->ulSectionTotalLength = 0; /* FIXME */
2037     data->hActCtx = NULL;
2038     if (data->cbSize >= offsetof(ACTCTX_SECTION_KEYED_DATA, ulAssemblyRosterIndex) + sizeof(ULONG))
2039         data->ulAssemblyRosterIndex = i + 1;
2040
2041     return STATUS_SUCCESS;
2042 }
2043
2044 static NTSTATUS find_dll_redirection(ACTIVATION_CONTEXT* actctx, const UNICODE_STRING *section_name,
2045                                      PACTCTX_SECTION_KEYED_DATA data)
2046 {
2047     unsigned int i, j, snlen = section_name->Length / sizeof(WCHAR);
2048
2049     for (i = 0; i < actctx->num_assemblies; i++)
2050     {
2051         struct assembly *assembly = &actctx->assemblies[i];
2052         for (j = 0; j < assembly->num_dlls; j++)
2053         {
2054             struct dll_redirect *dll = &assembly->dlls[j];
2055             if (!strncmpiW(section_name->Buffer, dll->name, snlen) && !dll->name[snlen])
2056                 return fill_keyed_data(data, dll, assembly, i);
2057         }
2058     }
2059     return STATUS_SXS_KEY_NOT_FOUND;
2060 }
2061
2062 static NTSTATUS find_window_class(ACTIVATION_CONTEXT* actctx, const UNICODE_STRING *section_name,
2063                                   PACTCTX_SECTION_KEYED_DATA data)
2064 {
2065     unsigned int i, j, k, snlen = section_name->Length / sizeof(WCHAR);
2066
2067     for (i = 0; i < actctx->num_assemblies; i++)
2068     {
2069         struct assembly *assembly = &actctx->assemblies[i];
2070         for (j = 0; j < assembly->num_dlls; j++)
2071         {
2072             struct dll_redirect *dll = &assembly->dlls[j];
2073             for (k = 0; k < dll->entities.num; k++)
2074             {
2075                 struct entity *entity = &dll->entities.base[k];
2076                 if (entity->kind == ACTIVATION_CONTEXT_SECTION_WINDOW_CLASS_REDIRECTION)
2077                 {
2078                     if (!strncmpiW(section_name->Buffer, entity->u.class.name, snlen) && !entity->u.class.name[snlen])
2079                         return fill_keyed_data(data, entity, dll, i);
2080                 }
2081             }
2082         }
2083     }
2084     return STATUS_SXS_KEY_NOT_FOUND;
2085 }
2086
2087 static NTSTATUS find_string(ACTIVATION_CONTEXT* actctx, ULONG section_kind,
2088                             const UNICODE_STRING *section_name,
2089                             DWORD flags, PACTCTX_SECTION_KEYED_DATA data)
2090 {
2091     NTSTATUS status;
2092
2093     switch (section_kind)
2094     {
2095     case ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION:
2096         status = find_dll_redirection(actctx, section_name, data);
2097         break;
2098     case ACTIVATION_CONTEXT_SECTION_WINDOW_CLASS_REDIRECTION:
2099         status = find_window_class(actctx, section_name, data);
2100         break;
2101     case ACTIVATION_CONTEXT_SECTION_COM_SERVER_REDIRECTION:
2102     case ACTIVATION_CONTEXT_SECTION_COM_INTERFACE_REDIRECTION:
2103     case ACTIVATION_CONTEXT_SECTION_COM_TYPE_LIBRARY_REDIRECTION:
2104     case ACTIVATION_CONTEXT_SECTION_COM_PROGID_REDIRECTION:
2105     case ACTIVATION_CONTEXT_SECTION_GLOBAL_OBJECT_RENAME_TABLE:
2106     case ACTIVATION_CONTEXT_SECTION_CLR_SURROGATES:
2107         FIXME("Unsupported yet section_kind %x\n", section_kind);
2108         return STATUS_SXS_SECTION_NOT_FOUND;
2109     default:
2110         WARN("Unknown section_kind %x\n", section_kind);
2111         return STATUS_SXS_SECTION_NOT_FOUND;
2112     }
2113
2114     if (status != STATUS_SUCCESS) return status;
2115
2116     if (flags & FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX)
2117     {
2118         actctx_addref(actctx);
2119         data->hActCtx = actctx;
2120     }
2121     return STATUS_SUCCESS;
2122 }
2123
2124 /* initialize the activation context for the current process */
2125 void actctx_init(void)
2126 {
2127     ACTCTXW ctx;
2128     HANDLE handle;
2129
2130     ctx.cbSize   = sizeof(ctx);
2131     ctx.lpSource = NULL;
2132     ctx.dwFlags  = ACTCTX_FLAG_RESOURCE_NAME_VALID | ACTCTX_FLAG_HMODULE_VALID;
2133     ctx.hModule  = NtCurrentTeb()->Peb->ImageBaseAddress;
2134     ctx.lpResourceName = (LPCWSTR)CREATEPROCESS_MANIFEST_RESOURCE_ID;
2135
2136     if (!RtlCreateActivationContext( &handle, &ctx )) process_actctx = check_actctx(handle);
2137 }
2138
2139
2140 /***********************************************************************
2141  * RtlCreateActivationContext (NTDLL.@)
2142  *
2143  * Create an activation context.
2144  *
2145  * FIXME: function signature/prototype is wrong
2146  */
2147 NTSTATUS WINAPI RtlCreateActivationContext( HANDLE *handle, const void *ptr )
2148 {
2149     const ACTCTXW *pActCtx = ptr;  /* FIXME: not the right structure */
2150     const WCHAR *directory = NULL;
2151     ACTIVATION_CONTEXT *actctx;
2152     UNICODE_STRING nameW;
2153     ULONG lang = 0;
2154     NTSTATUS status = STATUS_NO_MEMORY;
2155     HANDLE file = 0;
2156     struct actctx_loader acl;
2157
2158     TRACE("%p %08x\n", pActCtx, pActCtx ? pActCtx->dwFlags : 0);
2159
2160     if (!pActCtx || pActCtx->cbSize < sizeof(*pActCtx) ||
2161         (pActCtx->dwFlags & ~ACTCTX_FLAGS_ALL))
2162         return STATUS_INVALID_PARAMETER;
2163
2164     if (!(actctx = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*actctx) )))
2165         return STATUS_NO_MEMORY;
2166
2167     actctx->magic = ACTCTX_MAGIC;
2168     actctx->ref_count = 1;
2169     actctx->config.type = ACTIVATION_CONTEXT_PATH_TYPE_NONE;
2170     actctx->config.info = NULL;
2171     actctx->appdir.type = ACTIVATION_CONTEXT_PATH_TYPE_WIN32_FILE;
2172     if (pActCtx->dwFlags & ACTCTX_FLAG_APPLICATION_NAME_VALID)
2173     {
2174         if (!(actctx->appdir.info = strdupW( pActCtx->lpApplicationName ))) goto error;
2175     }
2176     else
2177     {
2178         UNICODE_STRING dir;
2179         WCHAR *p;
2180
2181         if ((status = get_module_filename( NtCurrentTeb()->Peb->ImageBaseAddress, &dir, 0 )))
2182             goto error;
2183         if ((p = strrchrW( dir.Buffer, '\\' ))) p[1] = 0;
2184         actctx->appdir.info = dir.Buffer;
2185     }
2186
2187     nameW.Buffer = NULL;
2188     if (pActCtx->lpSource)
2189     {
2190         if (!RtlDosPathNameToNtPathName_U(pActCtx->lpSource, &nameW, NULL, NULL))
2191         {
2192             status = STATUS_NO_SUCH_FILE;
2193             goto error;
2194         }
2195         status = open_nt_file( &file, &nameW );
2196         if (status)
2197         {
2198             RtlFreeUnicodeString( &nameW );
2199             goto error;
2200         }
2201     }
2202
2203     acl.actctx = actctx;
2204     acl.dependencies = NULL;
2205     acl.num_dependencies = 0;
2206     acl.allocated_dependencies = 0;
2207
2208     if (pActCtx->dwFlags & ACTCTX_FLAG_LANGID_VALID) lang = pActCtx->wLangId;
2209     if (pActCtx->dwFlags & ACTCTX_FLAG_ASSEMBLY_DIRECTORY_VALID) directory = pActCtx->lpAssemblyDirectory;
2210
2211     if (pActCtx->dwFlags & ACTCTX_FLAG_RESOURCE_NAME_VALID)
2212     {
2213         /* if we have a resource it's a PE file */
2214         if (pActCtx->dwFlags & ACTCTX_FLAG_HMODULE_VALID)
2215         {
2216             status = get_manifest_in_module( &acl, NULL, NULL, directory, pActCtx->hModule,
2217                                              pActCtx->lpResourceName, lang );
2218             if (status && status != STATUS_SXS_CANT_GEN_ACTCTX)
2219                 /* FIXME: what to do if pActCtx->lpSource is set */
2220                 status = get_manifest_in_associated_manifest( &acl, NULL, NULL, directory,
2221                                                               pActCtx->hModule, pActCtx->lpResourceName );
2222         }
2223         else if (pActCtx->lpSource)
2224         {
2225             status = get_manifest_in_pe_file( &acl, NULL, nameW.Buffer, directory,
2226                                               file, pActCtx->lpResourceName, lang );
2227             if (status && status != STATUS_SXS_CANT_GEN_ACTCTX)
2228                 status = get_manifest_in_associated_manifest( &acl, NULL, nameW.Buffer, directory,
2229                                                               NULL, pActCtx->lpResourceName );
2230         }
2231         else status = STATUS_INVALID_PARAMETER;
2232     }
2233     else
2234     {
2235         status = get_manifest_in_manifest_file( &acl, NULL, nameW.Buffer, directory, file );
2236     }
2237
2238     if (file) NtClose( file );
2239     RtlFreeUnicodeString( &nameW );
2240
2241     if (status == STATUS_SUCCESS) status = parse_depend_manifests(&acl);
2242     free_depend_manifests( &acl );
2243
2244     if (status == STATUS_SUCCESS) *handle = actctx;
2245     else actctx_release( actctx );
2246     return status;
2247
2248 error:
2249     if (file) NtClose( file );
2250     actctx_release( actctx );
2251     return status;
2252 }
2253
2254
2255 /***********************************************************************
2256  *              RtlAddRefActivationContext (NTDLL.@)
2257  */
2258 void WINAPI RtlAddRefActivationContext( HANDLE handle )
2259 {
2260     ACTIVATION_CONTEXT *actctx;
2261
2262     if ((actctx = check_actctx( handle ))) actctx_addref( actctx );
2263 }
2264
2265
2266 /******************************************************************
2267  *              RtlReleaseActivationContext (NTDLL.@)
2268  */
2269 void WINAPI RtlReleaseActivationContext( HANDLE handle )
2270 {
2271     ACTIVATION_CONTEXT *actctx;
2272
2273     if ((actctx = check_actctx( handle ))) actctx_release( actctx );
2274 }
2275
2276
2277 /******************************************************************
2278  *              RtlActivateActivationContext (NTDLL.@)
2279  */
2280 NTSTATUS WINAPI RtlActivateActivationContext( ULONG unknown, HANDLE handle, PULONG_PTR cookie )
2281 {
2282     RTL_ACTIVATION_CONTEXT_STACK_FRAME *frame;
2283
2284     if (!(frame = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*frame) )))
2285         return STATUS_NO_MEMORY;
2286
2287     frame->Previous = NtCurrentTeb()->ActivationContextStack.ActiveFrame;
2288     frame->ActivationContext = handle;
2289     frame->Flags = 0;
2290     NtCurrentTeb()->ActivationContextStack.ActiveFrame = frame;
2291     RtlAddRefActivationContext( handle );
2292
2293     *cookie = (ULONG_PTR)frame;
2294     TRACE( "%p cookie=%lx\n", handle, *cookie );
2295     return STATUS_SUCCESS;
2296 }
2297
2298
2299 /***********************************************************************
2300  *              RtlDeactivateActivationContext (NTDLL.@)
2301  */
2302 void WINAPI RtlDeactivateActivationContext( ULONG flags, ULONG_PTR cookie )
2303 {
2304     RTL_ACTIVATION_CONTEXT_STACK_FRAME *frame, *top;
2305
2306     TRACE( "%x cookie=%lx\n", flags, cookie );
2307
2308     /* find the right frame */
2309     top = NtCurrentTeb()->ActivationContextStack.ActiveFrame;
2310     for (frame = top; frame; frame = frame->Previous)
2311         if ((ULONG_PTR)frame == cookie) break;
2312
2313     if (!frame)
2314         RtlRaiseStatus( STATUS_SXS_INVALID_DEACTIVATION );
2315
2316     if (frame != top && !(flags & DEACTIVATE_ACTCTX_FLAG_FORCE_EARLY_DEACTIVATION))
2317         RtlRaiseStatus( STATUS_SXS_EARLY_DEACTIVATION );
2318
2319     /* pop everything up to and including frame */
2320     NtCurrentTeb()->ActivationContextStack.ActiveFrame = frame->Previous;
2321
2322     while (top != NtCurrentTeb()->ActivationContextStack.ActiveFrame)
2323     {
2324         frame = top->Previous;
2325         RtlReleaseActivationContext( top->ActivationContext );
2326         RtlFreeHeap( GetProcessHeap(), 0, top );
2327         top = frame;
2328     }
2329 }
2330
2331
2332 /******************************************************************
2333  *              RtlFreeThreadActivationContextStack (NTDLL.@)
2334  */
2335 void WINAPI RtlFreeThreadActivationContextStack(void)
2336 {
2337     RTL_ACTIVATION_CONTEXT_STACK_FRAME *frame;
2338
2339     frame = NtCurrentTeb()->ActivationContextStack.ActiveFrame;
2340     while (frame)
2341     {
2342         RTL_ACTIVATION_CONTEXT_STACK_FRAME *prev = frame->Previous;
2343         RtlReleaseActivationContext( frame->ActivationContext );
2344         RtlFreeHeap( GetProcessHeap(), 0, frame );
2345         frame = prev;
2346     }
2347     NtCurrentTeb()->ActivationContextStack.ActiveFrame = NULL;
2348 }
2349
2350
2351 /******************************************************************
2352  *              RtlGetActiveActivationContext (NTDLL.@)
2353  */
2354 NTSTATUS WINAPI RtlGetActiveActivationContext( HANDLE *handle )
2355 {
2356     if (NtCurrentTeb()->ActivationContextStack.ActiveFrame)
2357     {
2358         *handle = NtCurrentTeb()->ActivationContextStack.ActiveFrame->ActivationContext;
2359         RtlAddRefActivationContext( *handle );
2360     }
2361     else
2362         *handle = 0;
2363
2364     return STATUS_SUCCESS;
2365 }
2366
2367
2368 /******************************************************************
2369  *              RtlIsActivationContextActive (NTDLL.@)
2370  */
2371 BOOLEAN WINAPI RtlIsActivationContextActive( HANDLE handle )
2372 {
2373     RTL_ACTIVATION_CONTEXT_STACK_FRAME *frame;
2374
2375     for (frame = NtCurrentTeb()->ActivationContextStack.ActiveFrame; frame; frame = frame->Previous)
2376         if (frame->ActivationContext == handle) return TRUE;
2377     return FALSE;
2378 }
2379
2380
2381 /***********************************************************************
2382  *              RtlQueryInformationActivationContext (NTDLL.@)
2383  *
2384  * Get information about an activation context.
2385  * FIXME: function signature/prototype may be wrong
2386  */
2387 NTSTATUS WINAPI RtlQueryInformationActivationContext( ULONG flags, HANDLE handle, PVOID subinst,
2388                                                       ULONG class, PVOID buffer,
2389                                                       SIZE_T bufsize, SIZE_T *retlen )
2390 {
2391     ACTIVATION_CONTEXT *actctx;
2392     NTSTATUS status;
2393
2394     TRACE("%08x %p %p %u %p %ld %p\n", flags, handle,
2395           subinst, class, buffer, bufsize, retlen);
2396
2397     if ((status = find_query_actctx( &handle, flags ))) return status;
2398
2399     switch (class)
2400     {
2401     case ActivationContextBasicInformation:
2402         {
2403             ACTIVATION_CONTEXT_BASIC_INFORMATION *info = buffer;
2404
2405             if (retlen) *retlen = sizeof(*info);
2406             if (!info || bufsize < sizeof(*info)) return STATUS_BUFFER_TOO_SMALL;
2407
2408             info->hActCtx = handle;
2409             info->dwFlags = 0;  /* FIXME */
2410             if (!(flags & QUERY_ACTCTX_FLAG_NO_ADDREF)) RtlAddRefActivationContext( handle );
2411         }
2412         break;
2413
2414     case ActivationContextDetailedInformation:
2415         {
2416             ACTIVATION_CONTEXT_DETAILED_INFORMATION *acdi = buffer;
2417             struct assembly *assembly = NULL;
2418             SIZE_T len, manifest_len = 0, config_len = 0, appdir_len = 0;
2419             LPWSTR ptr;
2420
2421             if (!(actctx = check_actctx(handle))) return STATUS_INVALID_PARAMETER;
2422
2423             if (actctx->num_assemblies) assembly = actctx->assemblies;
2424
2425             if (assembly && assembly->manifest.info)
2426                 manifest_len = strlenW(assembly->manifest.info) + 1;
2427             if (actctx->config.info) config_len = strlenW(actctx->config.info) + 1;
2428             if (actctx->appdir.info) appdir_len = strlenW(actctx->appdir.info) + 1;
2429             len = sizeof(*acdi) + (manifest_len + config_len + appdir_len) * sizeof(WCHAR);
2430
2431             if (retlen) *retlen = len;
2432             if (!buffer || bufsize < len) return STATUS_BUFFER_TOO_SMALL;
2433
2434             acdi->dwFlags = 0;
2435             acdi->ulFormatVersion = assembly ? 1 : 0; /* FIXME */
2436             acdi->ulAssemblyCount = actctx->num_assemblies;
2437             acdi->ulRootManifestPathType = assembly ? assembly->manifest.type : 0 /* FIXME */;
2438             acdi->ulRootManifestPathChars = assembly && assembly->manifest.info ? manifest_len - 1 : 0;
2439             acdi->ulRootConfigurationPathType = actctx->config.type;
2440             acdi->ulRootConfigurationPathChars = actctx->config.info ? config_len - 1 : 0;
2441             acdi->ulAppDirPathType = actctx->appdir.type;
2442             acdi->ulAppDirPathChars = actctx->appdir.info ? appdir_len - 1 : 0;
2443             ptr = (LPWSTR)(acdi + 1);
2444             if (manifest_len)
2445             {
2446                 acdi->lpRootManifestPath = ptr;
2447                 memcpy(ptr, assembly->manifest.info, manifest_len * sizeof(WCHAR));
2448                 ptr += manifest_len;
2449             }
2450             else acdi->lpRootManifestPath = NULL;
2451             if (config_len)
2452             {
2453                 acdi->lpRootConfigurationPath = ptr;
2454                 memcpy(ptr, actctx->config.info, config_len * sizeof(WCHAR));
2455                 ptr += config_len;
2456             }
2457             else acdi->lpRootConfigurationPath = NULL;
2458             if (appdir_len)
2459             {
2460                 acdi->lpAppDirPath = ptr;
2461                 memcpy(ptr, actctx->appdir.info, appdir_len * sizeof(WCHAR));
2462             }
2463             else acdi->lpAppDirPath = NULL;
2464         }
2465         break;
2466
2467     case AssemblyDetailedInformationInActivationContext:
2468         {
2469             ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION *afdi = buffer;
2470             struct assembly *assembly;
2471             WCHAR *assembly_id;
2472             DWORD index;
2473             SIZE_T len, id_len = 0, ad_len = 0, path_len = 0;
2474             LPWSTR ptr;
2475
2476             if (!(actctx = check_actctx(handle))) return STATUS_INVALID_PARAMETER;
2477             if (!subinst) return STATUS_INVALID_PARAMETER;
2478
2479             index = *(DWORD*)subinst;
2480             if (!index || index > actctx->num_assemblies) return STATUS_INVALID_PARAMETER;
2481
2482             assembly = &actctx->assemblies[index - 1];
2483
2484             if (!(assembly_id = build_assembly_id( &assembly->id ))) return STATUS_NO_MEMORY;
2485             id_len = strlenW(assembly_id) + 1;
2486             if (assembly->directory) ad_len = strlenW(assembly->directory) + 1;
2487
2488             if (assembly->manifest.info && assembly->type == ASSEMBLY_MANIFEST)
2489                 path_len  = strlenW(assembly->manifest.info) + 1;
2490
2491             len = sizeof(*afdi) + (id_len + ad_len + path_len) * sizeof(WCHAR);
2492
2493             if (retlen) *retlen = len;
2494             if (!buffer || bufsize < len)
2495             {
2496                 RtlFreeHeap( GetProcessHeap(), 0, assembly_id );
2497                 return STATUS_BUFFER_TOO_SMALL;
2498             }
2499
2500             afdi->ulFlags = 0;  /* FIXME */
2501             afdi->ulEncodedAssemblyIdentityLength = (id_len - 1) * sizeof(WCHAR);
2502             afdi->ulManifestPathType = assembly->manifest.type;
2503             afdi->ulManifestPathLength = assembly->manifest.info ? (path_len - 1) * sizeof(WCHAR) : 0;
2504             /* FIXME afdi->liManifestLastWriteTime = 0; */
2505             afdi->ulPolicyPathType = ACTIVATION_CONTEXT_PATH_TYPE_NONE; /* FIXME */
2506             afdi->ulPolicyPathLength = 0;
2507             /* FIXME afdi->liPolicyLastWriteTime = 0; */
2508             afdi->ulMetadataSatelliteRosterIndex = 0; /* FIXME */
2509             afdi->ulManifestVersionMajor = 1;
2510             afdi->ulManifestVersionMinor = 0;
2511             afdi->ulPolicyVersionMajor = 0; /* FIXME */
2512             afdi->ulPolicyVersionMinor = 0; /* FIXME */
2513             afdi->ulAssemblyDirectoryNameLength = ad_len ? (ad_len - 1) * sizeof(WCHAR) : 0;
2514             ptr = (LPWSTR)(afdi + 1);
2515             afdi->lpAssemblyEncodedAssemblyIdentity = ptr;
2516             memcpy( ptr, assembly_id, id_len * sizeof(WCHAR) );
2517             ptr += id_len;
2518             if (path_len)
2519             {
2520                 afdi->lpAssemblyManifestPath = ptr;
2521                 memcpy(ptr, assembly->manifest.info, path_len * sizeof(WCHAR));
2522                 ptr += path_len;
2523             } else afdi->lpAssemblyManifestPath = NULL;
2524             afdi->lpAssemblyPolicyPath = NULL; /* FIXME */
2525             if (ad_len)
2526             {
2527                 afdi->lpAssemblyDirectoryName = ptr;
2528                 memcpy(ptr, assembly->directory, ad_len * sizeof(WCHAR));
2529                 ptr += ad_len;
2530             }
2531             else afdi->lpAssemblyDirectoryName = NULL;
2532             RtlFreeHeap( GetProcessHeap(), 0, assembly_id );
2533         }
2534         break;
2535
2536     case FileInformationInAssemblyOfAssemblyInActivationContext:
2537         {
2538             const ACTIVATION_CONTEXT_QUERY_INDEX *acqi = subinst;
2539             ASSEMBLY_FILE_DETAILED_INFORMATION *afdi = buffer;
2540             struct assembly *assembly;
2541             struct dll_redirect *dll;
2542             SIZE_T len, dll_len = 0;
2543             LPWSTR ptr;
2544
2545             if (!(actctx = check_actctx(handle))) return STATUS_INVALID_PARAMETER;
2546             if (!acqi) return STATUS_INVALID_PARAMETER;
2547
2548             if (acqi->ulAssemblyIndex >= actctx->num_assemblies)
2549                 return STATUS_INVALID_PARAMETER;
2550             assembly = &actctx->assemblies[acqi->ulAssemblyIndex];
2551
2552             if (acqi->ulFileIndexInAssembly >= assembly->num_dlls)
2553                 return STATUS_INVALID_PARAMETER;
2554             dll = &assembly->dlls[acqi->ulFileIndexInAssembly];
2555
2556             if (dll->name) dll_len = strlenW(dll->name) + 1;
2557             len = sizeof(*afdi) + dll_len * sizeof(WCHAR);
2558
2559             if (!buffer || bufsize < len)
2560             {
2561                 if (retlen) *retlen = len;
2562                 return STATUS_BUFFER_TOO_SMALL;
2563             }
2564             if (retlen) *retlen = 0; /* yes that's what native does !! */
2565             afdi->ulFlags = ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION;
2566             afdi->ulFilenameLength = dll_len ? (dll_len - 1) * sizeof(WCHAR) : 0;
2567             afdi->ulPathLength = 0; /* FIXME */
2568             ptr = (LPWSTR)(afdi + 1);
2569             if (dll_len)
2570             {
2571                 afdi->lpFileName = ptr;
2572                 memcpy( ptr, dll->name, dll_len * sizeof(WCHAR) );
2573             } else afdi->lpFileName = NULL;
2574             afdi->lpFilePath = NULL; /* FIXME */
2575         }
2576         break;
2577
2578     default:
2579         FIXME( "class %u not implemented\n", class );
2580         return STATUS_NOT_IMPLEMENTED;
2581     }
2582     return STATUS_SUCCESS;
2583 }
2584
2585 /***********************************************************************
2586  *              RtlFindActivationContextSectionString (NTDLL.@)
2587  *
2588  * Find information about a string in an activation context.
2589  * FIXME: function signature/prototype may be wrong
2590  */
2591 NTSTATUS WINAPI RtlFindActivationContextSectionString( ULONG flags, const GUID *guid, ULONG section_kind,
2592                                                        const UNICODE_STRING *section_name, PVOID ptr )
2593 {
2594     PACTCTX_SECTION_KEYED_DATA data = ptr;
2595     NTSTATUS status = STATUS_SXS_KEY_NOT_FOUND;
2596
2597     TRACE("%08x %s %u %s %p\n", flags, debugstr_guid(guid), section_kind,
2598           debugstr_us(section_name), data);
2599
2600     if (guid)
2601     {
2602         FIXME("expected guid == NULL\n");
2603         return STATUS_INVALID_PARAMETER;
2604     }
2605     if (flags & ~FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX)
2606     {
2607         FIXME("unknown flags %08x\n", flags);
2608         return STATUS_INVALID_PARAMETER;
2609     }
2610     if (!data || data->cbSize < offsetof(ACTCTX_SECTION_KEYED_DATA, ulAssemblyRosterIndex) ||
2611         !section_name || !section_name->Buffer)
2612     {
2613         WARN("invalid parameter\n");
2614         return STATUS_INVALID_PARAMETER;
2615     }
2616
2617     if (NtCurrentTeb()->ActivationContextStack.ActiveFrame)
2618     {
2619         ACTIVATION_CONTEXT *actctx = check_actctx(NtCurrentTeb()->ActivationContextStack.ActiveFrame->ActivationContext);
2620         if (actctx) status = find_string( actctx, section_kind, section_name, flags, data );
2621     }
2622
2623     if (status != STATUS_SUCCESS)
2624         status = find_string( process_actctx, section_kind, section_name, flags, data );
2625
2626     return status;
2627 }