user32: Change the desktop colour and pattern to match win2k.
[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 assembly_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 assembly_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 assembly_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 assembly_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     int unicode_tests;
1488
1489     TRACE( "parsing manifest loaded from %s base dir %s\n", debugstr_w(filename), debugstr_w(directory) );
1490
1491     if (!(assembly = add_assembly(acl->actctx, ASSEMBLY_MANIFEST)))
1492         return STATUS_SXS_CANT_GEN_ACTCTX;
1493
1494     if (directory && !(assembly->directory = strdupW(directory)))
1495         return STATUS_NO_MEMORY;
1496
1497     if (filename) assembly->manifest.info = strdupW( filename + 4 /* skip \??\ prefix */ );
1498     assembly->manifest.type = assembly->manifest.info ? ACTIVATION_CONTEXT_PATH_TYPE_WIN32_FILE
1499                                                       : ACTIVATION_CONTEXT_PATH_TYPE_NONE;
1500
1501     unicode_tests = IS_TEXT_UNICODE_SIGNATURE | IS_TEXT_UNICODE_REVERSE_SIGNATURE;
1502     if (RtlIsTextUnicode( buffer, size, &unicode_tests ))
1503     {
1504         xmlbuf.ptr = buffer;
1505         xmlbuf.end = xmlbuf.ptr + size / sizeof(WCHAR);
1506         status = parse_manifest_buffer( acl, assembly, ai, &xmlbuf );
1507     }
1508     else if (unicode_tests & IS_TEXT_UNICODE_REVERSE_SIGNATURE)
1509     {
1510         const WCHAR *buf = buffer;
1511         WCHAR *new_buff;
1512         unsigned int i;
1513
1514         if (!(new_buff = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1515             return STATUS_NO_MEMORY;
1516         for (i = 0; i < size / sizeof(WCHAR); i++)
1517             new_buff[i] = RtlUshortByteSwap( buf[i] );
1518         xmlbuf.ptr = new_buff;
1519         xmlbuf.end = xmlbuf.ptr + size / sizeof(WCHAR);
1520         status = parse_manifest_buffer( acl, assembly, ai, &xmlbuf );
1521         RtlFreeHeap( GetProcessHeap(), 0, new_buff );
1522     }
1523     else
1524     {
1525         /* let's assume utf-8 for now */
1526         int len = wine_utf8_mbstowcs( 0, buffer, size, NULL, 0 );
1527         WCHAR *new_buff;
1528
1529         if (len == -1)
1530         {
1531             FIXME( "utf-8 conversion failed\n" );
1532             return STATUS_SXS_CANT_GEN_ACTCTX;
1533         }
1534         if (!(new_buff = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR) )))
1535             return STATUS_NO_MEMORY;
1536         wine_utf8_mbstowcs( 0, buffer, size, new_buff, len );
1537         xmlbuf.ptr = new_buff;
1538         xmlbuf.end = xmlbuf.ptr + len;
1539         status = parse_manifest_buffer( acl, assembly, ai, &xmlbuf );
1540         RtlFreeHeap( GetProcessHeap(), 0, new_buff );
1541     }
1542     return status;
1543 }
1544
1545 static NTSTATUS open_nt_file( HANDLE *handle, UNICODE_STRING *name )
1546 {
1547     OBJECT_ATTRIBUTES attr;
1548     IO_STATUS_BLOCK io;
1549
1550     attr.Length = sizeof(attr);
1551     attr.RootDirectory = 0;
1552     attr.Attributes = OBJ_CASE_INSENSITIVE;
1553     attr.ObjectName = name;
1554     attr.SecurityDescriptor = NULL;
1555     attr.SecurityQualityOfService = NULL;
1556     return NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ, FILE_SYNCHRONOUS_IO_ALERT );
1557 }
1558
1559 static NTSTATUS get_module_filename( HMODULE module, UNICODE_STRING *str, unsigned int extra_len )
1560 {
1561     NTSTATUS status;
1562     ULONG magic;
1563     LDR_MODULE *pldr;
1564
1565     LdrLockLoaderLock(0, NULL, &magic);
1566     status = LdrFindEntryForAddress( module, &pldr );
1567     if (status == STATUS_SUCCESS)
1568     {
1569         if ((str->Buffer = RtlAllocateHeap( GetProcessHeap(), 0,
1570                                             pldr->FullDllName.Length + extra_len + sizeof(WCHAR) )))
1571         {
1572             memcpy( str->Buffer, pldr->FullDllName.Buffer, pldr->FullDllName.Length + sizeof(WCHAR) );
1573             str->Length = pldr->FullDllName.Length;
1574             str->MaximumLength = pldr->FullDllName.Length + extra_len + sizeof(WCHAR);
1575         }
1576         else status = STATUS_NO_MEMORY;
1577     }
1578     LdrUnlockLoaderLock(0, magic);
1579     return status;
1580 }
1581
1582 static NTSTATUS get_manifest_in_module( struct actctx_loader* acl, struct assembly_identity* ai,
1583                                         LPCWSTR filename, LPCWSTR directory, HANDLE hModule,
1584                                         LPCWSTR resname, ULONG lang )
1585 {
1586     NTSTATUS status;
1587     UNICODE_STRING nameW;
1588     LDR_RESOURCE_INFO info;
1589     const IMAGE_RESOURCE_DATA_ENTRY* entry = NULL;
1590     void *ptr;
1591
1592     if (TRACE_ON(actctx))
1593     {
1594         if (!filename && !get_module_filename( hModule, &nameW, 0 ))
1595         {
1596             TRACE( "looking for res %s in module %p %s\n", debugstr_w(resname),
1597                    hModule, debugstr_w(nameW.Buffer) );
1598             RtlFreeUnicodeString( &nameW );
1599         }
1600         else TRACE( "looking for res %s in module %p %s\n", debugstr_w(resname),
1601                     hModule, debugstr_w(filename) );
1602     }
1603
1604     if (!resname) return STATUS_INVALID_PARAMETER;
1605
1606     info.Type = RT_MANIFEST;
1607     info.Language = lang;
1608     if (!((ULONG_PTR)resname >> 16))
1609     {
1610         info.Name = (ULONG_PTR)resname;
1611         status = LdrFindResource_U(hModule, &info, 3, &entry);
1612     }
1613     else if (resname[0] == '#')
1614     {
1615         ULONG value;
1616         RtlInitUnicodeString(&nameW, resname + 1);
1617         if (RtlUnicodeStringToInteger(&nameW, 10, &value) != STATUS_SUCCESS || HIWORD(value))
1618             return STATUS_INVALID_PARAMETER;
1619         info.Name = value;
1620         status = LdrFindResource_U(hModule, &info, 3, &entry);
1621     }
1622     else
1623     {
1624         RtlCreateUnicodeString(&nameW, resname);
1625         RtlUpcaseUnicodeString(&nameW, &nameW, FALSE);
1626         info.Name = (ULONG_PTR)nameW.Buffer;
1627         status = LdrFindResource_U(hModule, &info, 3, &entry);
1628         RtlFreeUnicodeString(&nameW);
1629     }
1630     if (status == STATUS_SUCCESS) status = LdrAccessResource(hModule, entry, &ptr, NULL);
1631
1632     if (status == STATUS_SUCCESS)
1633         status = parse_manifest(acl, ai, filename, directory, ptr, entry->Size);
1634
1635     return status;
1636 }
1637
1638 static NTSTATUS get_manifest_in_pe_file( struct actctx_loader* acl, struct assembly_identity* ai,
1639                                          LPCWSTR filename, LPCWSTR directory, HANDLE file,
1640                                          LPCWSTR resname, ULONG lang )
1641 {
1642     HANDLE              mapping;
1643     OBJECT_ATTRIBUTES   attr;
1644     LARGE_INTEGER       size;
1645     LARGE_INTEGER       offset;
1646     NTSTATUS            status;
1647     SIZE_T              count;
1648     void               *base;
1649
1650     TRACE( "looking for res %s in %s\n", debugstr_w(resname), debugstr_w(filename) );
1651
1652     attr.Length                   = sizeof(attr);
1653     attr.RootDirectory            = 0;
1654     attr.ObjectName               = NULL;
1655     attr.Attributes               = OBJ_CASE_INSENSITIVE | OBJ_OPENIF;
1656     attr.SecurityDescriptor       = NULL;
1657     attr.SecurityQualityOfService = NULL;
1658
1659     size.QuadPart = 0;
1660     status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
1661                               &attr, &size, PAGE_READONLY, SEC_COMMIT, file );
1662     if (status != STATUS_SUCCESS) return status;
1663
1664     offset.QuadPart = 0;
1665     count = 0;
1666     base = NULL;
1667     status = NtMapViewOfSection( mapping, GetCurrentProcess(), &base, 0, 0, &offset,
1668                                  &count, ViewShare, 0, PAGE_READONLY );
1669     NtClose( mapping );
1670     if (status != STATUS_SUCCESS) return status;
1671
1672     if (RtlImageNtHeader(base)) /* we got a PE file */
1673     {
1674         HANDLE module = (HMODULE)((ULONG_PTR)base | 1);  /* make it a LOAD_LIBRARY_AS_DATAFILE handle */
1675         status = get_manifest_in_module( acl, ai, filename, directory, module, resname, lang );
1676     }
1677     else status = STATUS_INVALID_IMAGE_FORMAT;
1678
1679     NtUnmapViewOfSection( GetCurrentProcess(), base );
1680     return status;
1681 }
1682
1683 static NTSTATUS get_manifest_in_manifest_file( struct actctx_loader* acl, struct assembly_identity* ai,
1684                                                LPCWSTR filename, LPCWSTR directory, HANDLE file )
1685 {
1686     FILE_END_OF_FILE_INFORMATION info;
1687     IO_STATUS_BLOCK io;
1688     HANDLE              mapping;
1689     OBJECT_ATTRIBUTES   attr;
1690     LARGE_INTEGER       size;
1691     LARGE_INTEGER       offset;
1692     NTSTATUS            status;
1693     SIZE_T              count;
1694     void               *base;
1695
1696     TRACE( "loading manifest file %s\n", debugstr_w(filename) );
1697
1698     attr.Length                   = sizeof(attr);
1699     attr.RootDirectory            = 0;
1700     attr.ObjectName               = NULL;
1701     attr.Attributes               = OBJ_CASE_INSENSITIVE | OBJ_OPENIF;
1702     attr.SecurityDescriptor       = NULL;
1703     attr.SecurityQualityOfService = NULL;
1704
1705     size.QuadPart = 0;
1706     status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
1707                               &attr, &size, PAGE_READONLY, SEC_COMMIT, file );
1708     if (status != STATUS_SUCCESS) return status;
1709
1710     offset.QuadPart = 0;
1711     count = 0;
1712     base = NULL;
1713     status = NtMapViewOfSection( mapping, GetCurrentProcess(), &base, 0, 0, &offset,
1714                                  &count, ViewShare, 0, PAGE_READONLY );
1715     NtClose( mapping );
1716     if (status != STATUS_SUCCESS) return status;
1717
1718     status = NtQueryInformationFile( file, &io, &info, sizeof(info), FileEndOfFileInformation );
1719     if (status == STATUS_SUCCESS)
1720         status = parse_manifest(acl, ai, filename, directory, base, info.EndOfFile.QuadPart);
1721
1722     NtUnmapViewOfSection( GetCurrentProcess(), base );
1723     return status;
1724 }
1725
1726 /* try to load the .manifest file associated to the file */
1727 static NTSTATUS get_manifest_in_associated_manifest( struct actctx_loader* acl, struct assembly_identity* ai,
1728                                                      LPCWSTR filename, LPCWSTR directory, HMODULE module, LPCWSTR resname )
1729 {
1730     static const WCHAR fmtW[] = { '.','%','l','u',0 };
1731     WCHAR *buffer;
1732     NTSTATUS status;
1733     UNICODE_STRING nameW;
1734     HANDLE file;
1735     ULONG_PTR resid = CREATEPROCESS_MANIFEST_RESOURCE_ID;
1736
1737     if (!((ULONG_PTR)resname >> 16)) resid = (ULONG_PTR)resname & 0xffff;
1738
1739     TRACE( "looking for manifest associated with %s id %lu\n", debugstr_w(filename), resid );
1740
1741     if (module) /* use the module filename */
1742     {
1743         UNICODE_STRING name;
1744
1745         if (!(status = get_module_filename( module, &name, sizeof(dotManifestW) + 10*sizeof(WCHAR) )))
1746         {
1747             if (resid != 1) sprintfW( name.Buffer + strlenW(name.Buffer), fmtW, resid );
1748             strcatW( name.Buffer, dotManifestW );
1749             if (!RtlDosPathNameToNtPathName_U( name.Buffer, &nameW, NULL, NULL ))
1750                 status = STATUS_RESOURCE_DATA_NOT_FOUND;
1751             RtlFreeUnicodeString( &name );
1752         }
1753         if (status) return status;
1754     }
1755     else
1756     {
1757         if (!(buffer = RtlAllocateHeap( GetProcessHeap(), 0,
1758                                         (strlenW(filename) + 10) * sizeof(WCHAR) + sizeof(dotManifestW) )))
1759             return STATUS_NO_MEMORY;
1760         strcpyW( buffer, filename );
1761         if (resid != 1) sprintfW( buffer + strlenW(buffer), fmtW, resid );
1762         strcatW( buffer, dotManifestW );
1763         RtlInitUnicodeString( &nameW, buffer );
1764     }
1765
1766     if (!open_nt_file( &file, &nameW ))
1767     {
1768         status = get_manifest_in_manifest_file( acl, ai, nameW.Buffer, directory, file );
1769         NtClose( file );
1770     }
1771     else status = STATUS_RESOURCE_DATA_NOT_FOUND;
1772     RtlFreeUnicodeString( &nameW );
1773     return status;
1774 }
1775
1776 static WCHAR *lookup_manifest_file( HANDLE dir, struct assembly_identity *ai )
1777 {
1778     static const WCHAR lookup_fmtW[] =
1779         {'%','s','_','%','s','_','%','s','_','%','u','.','%','u','.','*','.','*','_',
1780          '*', /* FIXME */
1781          '.','m','a','n','i','f','e','s','t',0};
1782
1783     WCHAR *lookup, *ret = NULL;
1784     UNICODE_STRING lookup_us;
1785     IO_STATUS_BLOCK io;
1786     unsigned int data_pos = 0, data_len;
1787     char buffer[8192];
1788
1789     if (!(lookup = RtlAllocateHeap( GetProcessHeap(), 0,
1790                                     (strlenW(ai->arch) + strlenW(ai->name)
1791                                      + strlenW(ai->public_key) + 20) * sizeof(WCHAR)
1792                                     + sizeof(lookup_fmtW) )))
1793         return NULL;
1794
1795     sprintfW( lookup, lookup_fmtW, ai->arch, ai->name, ai->public_key, ai->version.major, ai->version.minor);
1796     RtlInitUnicodeString( &lookup_us, lookup );
1797
1798     NtQueryDirectoryFile( dir, 0, NULL, NULL, &io, buffer, sizeof(buffer),
1799                           FileBothDirectoryInformation, FALSE, &lookup_us, TRUE );
1800     if (io.u.Status == STATUS_SUCCESS)
1801     {
1802         FILE_BOTH_DIR_INFORMATION *dir_info;
1803         WCHAR *tmp;
1804         ULONG build, revision;
1805
1806         data_len = io.Information;
1807
1808         for (;;)
1809         {
1810             if (data_pos >= data_len)
1811             {
1812                 NtQueryDirectoryFile( dir, 0, NULL, NULL, &io, buffer, sizeof(buffer),
1813                                       FileBothDirectoryInformation, FALSE, &lookup_us, FALSE );
1814                 if (io.u.Status != STATUS_SUCCESS) break;
1815                 data_len = io.Information;
1816                 data_pos = 0;
1817             }
1818             dir_info = (FILE_BOTH_DIR_INFORMATION*)(buffer + data_pos);
1819
1820             if (dir_info->NextEntryOffset) data_pos += dir_info->NextEntryOffset;
1821             else data_pos = data_len;
1822
1823             tmp = (WCHAR *)dir_info->FileName + (strchrW(lookup, '*') - lookup);
1824             build = atoiW(tmp);
1825             if (build < ai->version.build) continue;
1826             tmp = strchrW(tmp, '.') + 1;
1827             revision = atoiW(tmp);
1828             if (build == ai->version.build && revision < ai->version.revision)
1829                 continue;
1830             ai->version.build = build;
1831             ai->version.revision = revision;
1832             if ((ret = RtlAllocateHeap( GetProcessHeap(), 0, dir_info->FileNameLength + sizeof(WCHAR) )))
1833             {
1834                 memcpy( ret, dir_info->FileName, dir_info->FileNameLength );
1835                 ret[dir_info->FileNameLength/sizeof(WCHAR)] = 0;
1836             }
1837             break;
1838         }
1839     }
1840     else WARN("no matching file for %s\n", debugstr_w(lookup));
1841     RtlFreeHeap( GetProcessHeap(), 0, lookup );
1842     return ret;
1843 }
1844
1845 static NTSTATUS lookup_winsxs(struct actctx_loader* acl, struct assembly_identity* ai)
1846 {
1847     struct assembly_identity    sxs_ai;
1848     UNICODE_STRING              path_us;
1849     OBJECT_ATTRIBUTES           attr;
1850     IO_STATUS_BLOCK             io;
1851     WCHAR *path, *file = NULL;
1852     HANDLE handle;
1853
1854     static const WCHAR manifest_dirW[] =
1855         {'\\','w','i','n','s','x','s','\\','m','a','n','i','f','e','s','t','s',0};
1856
1857     if (!ai->arch || !ai->name || !ai->public_key) return STATUS_NO_SUCH_FILE;
1858
1859     if (!(path = RtlAllocateHeap( GetProcessHeap(), 0, windows_dir.Length + sizeof(manifest_dirW) )))
1860         return STATUS_NO_MEMORY;
1861
1862     memcpy( path, windows_dir.Buffer, windows_dir.Length );
1863     memcpy( path + windows_dir.Length/sizeof(WCHAR), manifest_dirW, sizeof(manifest_dirW) );
1864
1865     if (!RtlDosPathNameToNtPathName_U( path, &path_us, NULL, NULL ))
1866     {
1867         RtlFreeHeap( GetProcessHeap(), 0, path );
1868         return STATUS_NO_SUCH_FILE;
1869     }
1870     RtlFreeHeap( GetProcessHeap(), 0, path );
1871
1872     attr.Length = sizeof(attr);
1873     attr.RootDirectory = 0;
1874     attr.Attributes = OBJ_CASE_INSENSITIVE;
1875     attr.ObjectName = &path_us;
1876     attr.SecurityDescriptor = NULL;
1877     attr.SecurityQualityOfService = NULL;
1878
1879     if (!NtOpenFile( &handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ | FILE_SHARE_WRITE,
1880                      FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT ))
1881     {
1882         sxs_ai = *ai;
1883         file = lookup_manifest_file( handle, &sxs_ai );
1884         NtClose( handle );
1885     }
1886     if (!file)
1887     {
1888         RtlFreeUnicodeString( &path_us );
1889         return STATUS_NO_SUCH_FILE;
1890     }
1891
1892     /* append file name to directory path */
1893     if (!(path = RtlReAllocateHeap( GetProcessHeap(), 0, path_us.Buffer,
1894                                     path_us.Length + (strlenW(file) + 2) * sizeof(WCHAR) )))
1895     {
1896         RtlFreeHeap( GetProcessHeap(), 0, file );
1897         RtlFreeUnicodeString( &path_us );
1898         return STATUS_NO_MEMORY;
1899     }
1900
1901     path[path_us.Length/sizeof(WCHAR)] = '\\';
1902     strcpyW( path + path_us.Length/sizeof(WCHAR) + 1, file );
1903     RtlInitUnicodeString( &path_us, path );
1904     *strrchrW(file, '.') = 0;  /* remove .manifest extension */
1905
1906     if (!open_nt_file( &handle, &path_us ))
1907     {
1908         io.u.Status = get_manifest_in_manifest_file(acl, &sxs_ai, path_us.Buffer, file, handle);
1909         NtClose( handle );
1910     }
1911     else io.u.Status = STATUS_NO_SUCH_FILE;
1912
1913     RtlFreeHeap( GetProcessHeap(), 0, file );
1914     RtlFreeUnicodeString( &path_us );
1915     return io.u.Status;
1916 }
1917
1918 static NTSTATUS lookup_assembly(struct actctx_loader* acl,
1919                                 struct assembly_identity* ai)
1920 {
1921     static const WCHAR dotDllW[] = {'.','d','l','l',0};
1922     unsigned int i;
1923     WCHAR *buffer, *p, *directory;
1924     NTSTATUS status;
1925     UNICODE_STRING nameW;
1926     HANDLE file;
1927
1928     TRACE( "looking for name=%s version=%s arch=%s\n",
1929            debugstr_w(ai->name), debugstr_version(&ai->version), debugstr_w(ai->arch) );
1930
1931     if ((status = lookup_winsxs(acl, ai)) != STATUS_NO_SUCH_FILE) return status;
1932
1933     /* FIXME: add support for language specific lookup */
1934
1935     nameW.Buffer = NULL;
1936     if (!(buffer = RtlAllocateHeap( GetProcessHeap(), 0,
1937                                     (strlenW(acl->actctx->appdir.info) + 2 * strlenW(ai->name) + 2) * sizeof(WCHAR) + sizeof(dotManifestW) )))
1938         return STATUS_NO_MEMORY;
1939
1940     if (!(directory = build_assembly_dir( ai )))
1941     {
1942         RtlFreeHeap( GetProcessHeap(), 0, buffer );
1943         return STATUS_NO_MEMORY;
1944     }
1945
1946     /* lookup in appdir\name.dll
1947      *           appdir\name.manifest
1948      *           appdir\name\name.dll
1949      *           appdir\name\name.manifest
1950      */
1951     strcpyW( buffer, acl->actctx->appdir.info );
1952     p = buffer + strlenW(buffer);
1953     for (i = 0; i < 2; i++)
1954     {
1955         *p++ = '\\';
1956         strcpyW( p, ai->name );
1957         p += strlenW(p);
1958
1959         strcpyW( p, dotDllW );
1960         if (RtlDosPathNameToNtPathName_U( buffer, &nameW, NULL, NULL ))
1961         {
1962             status = open_nt_file( &file, &nameW );
1963             if (!status)
1964             {
1965                 status = get_manifest_in_pe_file( acl, ai, nameW.Buffer, directory, file,
1966                                                   (LPCWSTR)CREATEPROCESS_MANIFEST_RESOURCE_ID, 0 );
1967                 NtClose( file );
1968                 break;
1969             }
1970             RtlFreeUnicodeString( &nameW );
1971         }
1972
1973         strcpyW( p, dotManifestW );
1974         if (RtlDosPathNameToNtPathName_U( buffer, &nameW, NULL, NULL ))
1975         {
1976             status = open_nt_file( &file, &nameW );
1977             if (!status)
1978             {
1979                 status = get_manifest_in_manifest_file( acl, ai, nameW.Buffer, directory, file );
1980                 NtClose( file );
1981                 break;
1982             }
1983             RtlFreeUnicodeString( &nameW );
1984         }
1985         status = STATUS_SXS_ASSEMBLY_NOT_FOUND;
1986     }
1987     RtlFreeUnicodeString( &nameW );
1988     RtlFreeHeap( GetProcessHeap(), 0, directory );
1989     RtlFreeHeap( GetProcessHeap(), 0, buffer );
1990     return status;
1991 }
1992
1993 static NTSTATUS parse_depend_manifests(struct actctx_loader* acl)
1994 {
1995     NTSTATUS status = STATUS_SUCCESS;
1996     unsigned int i;
1997
1998     for (i = 0; i < acl->num_dependencies; i++)
1999     {
2000         if (lookup_assembly(acl, &acl->dependencies[i]) != STATUS_SUCCESS)
2001         {
2002             if (!acl->dependencies[i].optional)
2003             {
2004                 FIXME( "Could not find dependent assembly %s\n", debugstr_w(acl->dependencies[i].name) );
2005                 status = STATUS_SXS_CANT_GEN_ACTCTX;
2006                 break;
2007             }
2008         }
2009     }
2010     /* FIXME should now iterate through all refs */
2011     return status;
2012 }
2013
2014 /* find the appropriate activation context for RtlQueryInformationActivationContext */
2015 static NTSTATUS find_query_actctx( HANDLE *handle, DWORD flags )
2016 {
2017     NTSTATUS status = STATUS_SUCCESS;
2018
2019     if (flags & QUERY_ACTCTX_FLAG_USE_ACTIVE_ACTCTX)
2020     {
2021         if (NtCurrentTeb()->ActivationContextStack.ActiveFrame)
2022             *handle = NtCurrentTeb()->ActivationContextStack.ActiveFrame->ActivationContext;
2023     }
2024     else if (flags & (QUERY_ACTCTX_FLAG_ACTCTX_IS_ADDRESS|QUERY_ACTCTX_FLAG_ACTCTX_IS_HMODULE))
2025     {
2026         ULONG magic;
2027         LDR_MODULE *pldr;
2028
2029         LdrLockLoaderLock( 0, NULL, &magic );
2030         if (!LdrFindEntryForAddress( *handle, &pldr ))
2031         {
2032             if ((flags & QUERY_ACTCTX_FLAG_ACTCTX_IS_HMODULE) && *handle != pldr->BaseAddress)
2033                 status = STATUS_DLL_NOT_FOUND;
2034             else
2035                 *handle = pldr->ActivationContext;
2036         }
2037         else status = STATUS_DLL_NOT_FOUND;
2038         LdrUnlockLoaderLock( 0, magic );
2039     }
2040     else if (!*handle) *handle = process_actctx;
2041
2042     return status;
2043 }
2044
2045 static NTSTATUS fill_keyed_data(PACTCTX_SECTION_KEYED_DATA data, PVOID v1, PVOID v2, unsigned int i)
2046 {
2047     data->ulDataFormatVersion = 1;
2048     data->lpData = v1;
2049     data->ulLength = 20; /* FIXME */
2050     data->lpSectionGlobalData = NULL; /* FIXME */
2051     data->ulSectionGlobalDataLength = 0; /* FIXME */
2052     data->lpSectionBase = v2;
2053     data->ulSectionTotalLength = 0; /* FIXME */
2054     data->hActCtx = NULL;
2055     if (data->cbSize >= offsetof(ACTCTX_SECTION_KEYED_DATA, ulAssemblyRosterIndex) + sizeof(ULONG))
2056         data->ulAssemblyRosterIndex = i + 1;
2057
2058     return STATUS_SUCCESS;
2059 }
2060
2061 static NTSTATUS find_dll_redirection(ACTIVATION_CONTEXT* actctx, const UNICODE_STRING *section_name,
2062                                      PACTCTX_SECTION_KEYED_DATA data)
2063 {
2064     unsigned int i, j, snlen = section_name->Length / sizeof(WCHAR);
2065
2066     for (i = 0; i < actctx->num_assemblies; i++)
2067     {
2068         struct assembly *assembly = &actctx->assemblies[i];
2069         for (j = 0; j < assembly->num_dlls; j++)
2070         {
2071             struct dll_redirect *dll = &assembly->dlls[j];
2072             if (!strncmpiW(section_name->Buffer, dll->name, snlen) && !dll->name[snlen])
2073                 return fill_keyed_data(data, dll, assembly, i);
2074         }
2075     }
2076     return STATUS_SXS_KEY_NOT_FOUND;
2077 }
2078
2079 static NTSTATUS find_window_class(ACTIVATION_CONTEXT* actctx, const UNICODE_STRING *section_name,
2080                                   PACTCTX_SECTION_KEYED_DATA data)
2081 {
2082     unsigned int i, j, k, snlen = section_name->Length / sizeof(WCHAR);
2083
2084     for (i = 0; i < actctx->num_assemblies; i++)
2085     {
2086         struct assembly *assembly = &actctx->assemblies[i];
2087         for (j = 0; j < assembly->num_dlls; j++)
2088         {
2089             struct dll_redirect *dll = &assembly->dlls[j];
2090             for (k = 0; k < dll->entities.num; k++)
2091             {
2092                 struct entity *entity = &dll->entities.base[k];
2093                 if (entity->kind == ACTIVATION_CONTEXT_SECTION_WINDOW_CLASS_REDIRECTION)
2094                 {
2095                     if (!strncmpiW(section_name->Buffer, entity->u.class.name, snlen) && !entity->u.class.name[snlen])
2096                         return fill_keyed_data(data, entity, dll, i);
2097                 }
2098             }
2099         }
2100     }
2101     return STATUS_SXS_KEY_NOT_FOUND;
2102 }
2103
2104 static NTSTATUS find_string(ACTIVATION_CONTEXT* actctx, ULONG section_kind,
2105                             const UNICODE_STRING *section_name,
2106                             DWORD flags, PACTCTX_SECTION_KEYED_DATA data)
2107 {
2108     NTSTATUS status;
2109
2110     switch (section_kind)
2111     {
2112     case ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION:
2113         status = find_dll_redirection(actctx, section_name, data);
2114         break;
2115     case ACTIVATION_CONTEXT_SECTION_WINDOW_CLASS_REDIRECTION:
2116         status = find_window_class(actctx, section_name, data);
2117         break;
2118     case ACTIVATION_CONTEXT_SECTION_COM_SERVER_REDIRECTION:
2119     case ACTIVATION_CONTEXT_SECTION_COM_INTERFACE_REDIRECTION:
2120     case ACTIVATION_CONTEXT_SECTION_COM_TYPE_LIBRARY_REDIRECTION:
2121     case ACTIVATION_CONTEXT_SECTION_COM_PROGID_REDIRECTION:
2122     case ACTIVATION_CONTEXT_SECTION_GLOBAL_OBJECT_RENAME_TABLE:
2123     case ACTIVATION_CONTEXT_SECTION_CLR_SURROGATES:
2124         FIXME("Unsupported yet section_kind %x\n", section_kind);
2125         return STATUS_SXS_SECTION_NOT_FOUND;
2126     default:
2127         WARN("Unknown section_kind %x\n", section_kind);
2128         return STATUS_SXS_SECTION_NOT_FOUND;
2129     }
2130
2131     if (status != STATUS_SUCCESS) return status;
2132
2133     if (flags & FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX)
2134     {
2135         actctx_addref(actctx);
2136         data->hActCtx = actctx;
2137     }
2138     return STATUS_SUCCESS;
2139 }
2140
2141 /* initialize the activation context for the current process */
2142 void actctx_init(void)
2143 {
2144     ACTCTXW ctx;
2145     HANDLE handle;
2146
2147     ctx.cbSize   = sizeof(ctx);
2148     ctx.lpSource = NULL;
2149     ctx.dwFlags  = ACTCTX_FLAG_RESOURCE_NAME_VALID | ACTCTX_FLAG_HMODULE_VALID;
2150     ctx.hModule  = NtCurrentTeb()->Peb->ImageBaseAddress;
2151     ctx.lpResourceName = (LPCWSTR)CREATEPROCESS_MANIFEST_RESOURCE_ID;
2152
2153     if (!RtlCreateActivationContext( &handle, &ctx )) process_actctx = check_actctx(handle);
2154 }
2155
2156
2157 /***********************************************************************
2158  * RtlCreateActivationContext (NTDLL.@)
2159  *
2160  * Create an activation context.
2161  *
2162  * FIXME: function signature/prototype is wrong
2163  */
2164 NTSTATUS WINAPI RtlCreateActivationContext( HANDLE *handle, const void *ptr )
2165 {
2166     const ACTCTXW *pActCtx = ptr;  /* FIXME: not the right structure */
2167     const WCHAR *directory = NULL;
2168     ACTIVATION_CONTEXT *actctx;
2169     UNICODE_STRING nameW;
2170     ULONG lang = 0;
2171     NTSTATUS status = STATUS_NO_MEMORY;
2172     HANDLE file = 0;
2173     struct actctx_loader acl;
2174
2175     TRACE("%p %08x\n", pActCtx, pActCtx ? pActCtx->dwFlags : 0);
2176
2177     if (!pActCtx || pActCtx->cbSize < sizeof(*pActCtx) ||
2178         (pActCtx->dwFlags & ~ACTCTX_FLAGS_ALL))
2179         return STATUS_INVALID_PARAMETER;
2180
2181     if (!(actctx = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*actctx) )))
2182         return STATUS_NO_MEMORY;
2183
2184     actctx->magic = ACTCTX_MAGIC;
2185     actctx->ref_count = 1;
2186     actctx->config.type = ACTIVATION_CONTEXT_PATH_TYPE_NONE;
2187     actctx->config.info = NULL;
2188     actctx->appdir.type = ACTIVATION_CONTEXT_PATH_TYPE_WIN32_FILE;
2189     if (pActCtx->dwFlags & ACTCTX_FLAG_APPLICATION_NAME_VALID)
2190     {
2191         if (!(actctx->appdir.info = strdupW( pActCtx->lpApplicationName ))) goto error;
2192     }
2193     else
2194     {
2195         UNICODE_STRING dir;
2196         WCHAR *p;
2197
2198         if ((status = get_module_filename( NtCurrentTeb()->Peb->ImageBaseAddress, &dir, 0 )))
2199             goto error;
2200         if ((p = strrchrW( dir.Buffer, '\\' ))) p[1] = 0;
2201         actctx->appdir.info = dir.Buffer;
2202     }
2203
2204     nameW.Buffer = NULL;
2205     if (pActCtx->lpSource)
2206     {
2207         if (!RtlDosPathNameToNtPathName_U(pActCtx->lpSource, &nameW, NULL, NULL))
2208         {
2209             status = STATUS_NO_SUCH_FILE;
2210             goto error;
2211         }
2212         status = open_nt_file( &file, &nameW );
2213         if (status)
2214         {
2215             RtlFreeUnicodeString( &nameW );
2216             goto error;
2217         }
2218     }
2219
2220     acl.actctx = actctx;
2221     acl.dependencies = NULL;
2222     acl.num_dependencies = 0;
2223     acl.allocated_dependencies = 0;
2224
2225     if (pActCtx->dwFlags & ACTCTX_FLAG_LANGID_VALID) lang = pActCtx->wLangId;
2226     if (pActCtx->dwFlags & ACTCTX_FLAG_ASSEMBLY_DIRECTORY_VALID) directory = pActCtx->lpAssemblyDirectory;
2227
2228     if (pActCtx->dwFlags & ACTCTX_FLAG_RESOURCE_NAME_VALID)
2229     {
2230         /* if we have a resource it's a PE file */
2231         if (pActCtx->dwFlags & ACTCTX_FLAG_HMODULE_VALID)
2232         {
2233             status = get_manifest_in_module( &acl, NULL, NULL, directory, pActCtx->hModule,
2234                                              pActCtx->lpResourceName, lang );
2235             if (status && status != STATUS_SXS_CANT_GEN_ACTCTX)
2236                 /* FIXME: what to do if pActCtx->lpSource is set */
2237                 status = get_manifest_in_associated_manifest( &acl, NULL, NULL, directory,
2238                                                               pActCtx->hModule, pActCtx->lpResourceName );
2239         }
2240         else if (pActCtx->lpSource)
2241         {
2242             status = get_manifest_in_pe_file( &acl, NULL, nameW.Buffer, directory,
2243                                               file, pActCtx->lpResourceName, lang );
2244             if (status && status != STATUS_SXS_CANT_GEN_ACTCTX)
2245                 status = get_manifest_in_associated_manifest( &acl, NULL, nameW.Buffer, directory,
2246                                                               NULL, pActCtx->lpResourceName );
2247         }
2248         else status = STATUS_INVALID_PARAMETER;
2249     }
2250     else
2251     {
2252         status = get_manifest_in_manifest_file( &acl, NULL, nameW.Buffer, directory, file );
2253     }
2254
2255     if (file) NtClose( file );
2256     RtlFreeUnicodeString( &nameW );
2257
2258     if (status == STATUS_SUCCESS) status = parse_depend_manifests(&acl);
2259     free_depend_manifests( &acl );
2260
2261     if (status == STATUS_SUCCESS) *handle = actctx;
2262     else actctx_release( actctx );
2263     return status;
2264
2265 error:
2266     if (file) NtClose( file );
2267     actctx_release( actctx );
2268     return status;
2269 }
2270
2271
2272 /***********************************************************************
2273  *              RtlAddRefActivationContext (NTDLL.@)
2274  */
2275 void WINAPI RtlAddRefActivationContext( HANDLE handle )
2276 {
2277     ACTIVATION_CONTEXT *actctx;
2278
2279     if ((actctx = check_actctx( handle ))) actctx_addref( actctx );
2280 }
2281
2282
2283 /******************************************************************
2284  *              RtlReleaseActivationContext (NTDLL.@)
2285  */
2286 void WINAPI RtlReleaseActivationContext( HANDLE handle )
2287 {
2288     ACTIVATION_CONTEXT *actctx;
2289
2290     if ((actctx = check_actctx( handle ))) actctx_release( actctx );
2291 }
2292
2293
2294 /******************************************************************
2295  *              RtlActivateActivationContext (NTDLL.@)
2296  */
2297 NTSTATUS WINAPI RtlActivateActivationContext( ULONG unknown, HANDLE handle, PULONG_PTR cookie )
2298 {
2299     RTL_ACTIVATION_CONTEXT_STACK_FRAME *frame;
2300
2301     if (!(frame = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*frame) )))
2302         return STATUS_NO_MEMORY;
2303
2304     frame->Previous = NtCurrentTeb()->ActivationContextStack.ActiveFrame;
2305     frame->ActivationContext = handle;
2306     frame->Flags = 0;
2307     NtCurrentTeb()->ActivationContextStack.ActiveFrame = frame;
2308     RtlAddRefActivationContext( handle );
2309
2310     *cookie = (ULONG_PTR)frame;
2311     TRACE( "%p cookie=%lx\n", handle, *cookie );
2312     return STATUS_SUCCESS;
2313 }
2314
2315
2316 /***********************************************************************
2317  *              RtlDeactivateActivationContext (NTDLL.@)
2318  */
2319 void WINAPI RtlDeactivateActivationContext( ULONG flags, ULONG_PTR cookie )
2320 {
2321     RTL_ACTIVATION_CONTEXT_STACK_FRAME *frame, *top;
2322
2323     TRACE( "%x cookie=%lx\n", flags, cookie );
2324
2325     /* find the right frame */
2326     top = NtCurrentTeb()->ActivationContextStack.ActiveFrame;
2327     for (frame = top; frame; frame = frame->Previous)
2328         if ((ULONG_PTR)frame == cookie) break;
2329
2330     if (!frame)
2331         RtlRaiseStatus( STATUS_SXS_INVALID_DEACTIVATION );
2332
2333     if (frame != top && !(flags & DEACTIVATE_ACTCTX_FLAG_FORCE_EARLY_DEACTIVATION))
2334         RtlRaiseStatus( STATUS_SXS_EARLY_DEACTIVATION );
2335
2336     /* pop everything up to and including frame */
2337     NtCurrentTeb()->ActivationContextStack.ActiveFrame = frame->Previous;
2338
2339     while (top != NtCurrentTeb()->ActivationContextStack.ActiveFrame)
2340     {
2341         frame = top->Previous;
2342         RtlReleaseActivationContext( top->ActivationContext );
2343         RtlFreeHeap( GetProcessHeap(), 0, top );
2344         top = frame;
2345     }
2346 }
2347
2348
2349 /******************************************************************
2350  *              RtlFreeThreadActivationContextStack (NTDLL.@)
2351  */
2352 void WINAPI RtlFreeThreadActivationContextStack(void)
2353 {
2354     RTL_ACTIVATION_CONTEXT_STACK_FRAME *frame;
2355
2356     frame = NtCurrentTeb()->ActivationContextStack.ActiveFrame;
2357     while (frame)
2358     {
2359         RTL_ACTIVATION_CONTEXT_STACK_FRAME *prev = frame->Previous;
2360         RtlReleaseActivationContext( frame->ActivationContext );
2361         RtlFreeHeap( GetProcessHeap(), 0, frame );
2362         frame = prev;
2363     }
2364     NtCurrentTeb()->ActivationContextStack.ActiveFrame = NULL;
2365 }
2366
2367
2368 /******************************************************************
2369  *              RtlGetActiveActivationContext (NTDLL.@)
2370  */
2371 NTSTATUS WINAPI RtlGetActiveActivationContext( HANDLE *handle )
2372 {
2373     if (NtCurrentTeb()->ActivationContextStack.ActiveFrame)
2374     {
2375         *handle = NtCurrentTeb()->ActivationContextStack.ActiveFrame->ActivationContext;
2376         RtlAddRefActivationContext( *handle );
2377     }
2378     else
2379         *handle = 0;
2380
2381     return STATUS_SUCCESS;
2382 }
2383
2384
2385 /******************************************************************
2386  *              RtlIsActivationContextActive (NTDLL.@)
2387  */
2388 BOOLEAN WINAPI RtlIsActivationContextActive( HANDLE handle )
2389 {
2390     RTL_ACTIVATION_CONTEXT_STACK_FRAME *frame;
2391
2392     for (frame = NtCurrentTeb()->ActivationContextStack.ActiveFrame; frame; frame = frame->Previous)
2393         if (frame->ActivationContext == handle) return TRUE;
2394     return FALSE;
2395 }
2396
2397
2398 /***********************************************************************
2399  *              RtlQueryInformationActivationContext (NTDLL.@)
2400  *
2401  * Get information about an activation context.
2402  * FIXME: function signature/prototype may be wrong
2403  */
2404 NTSTATUS WINAPI RtlQueryInformationActivationContext( ULONG flags, HANDLE handle, PVOID subinst,
2405                                                       ULONG class, PVOID buffer,
2406                                                       SIZE_T bufsize, SIZE_T *retlen )
2407 {
2408     ACTIVATION_CONTEXT *actctx;
2409     NTSTATUS status;
2410
2411     TRACE("%08x %p %p %u %p %ld %p\n", flags, handle,
2412           subinst, class, buffer, bufsize, retlen);
2413
2414     if ((status = find_query_actctx( &handle, flags ))) return status;
2415
2416     switch (class)
2417     {
2418     case ActivationContextBasicInformation:
2419         {
2420             ACTIVATION_CONTEXT_BASIC_INFORMATION *info = buffer;
2421
2422             if (retlen) *retlen = sizeof(*info);
2423             if (!info || bufsize < sizeof(*info)) return STATUS_BUFFER_TOO_SMALL;
2424
2425             info->hActCtx = handle;
2426             info->dwFlags = 0;  /* FIXME */
2427             if (!(flags & QUERY_ACTCTX_FLAG_NO_ADDREF)) RtlAddRefActivationContext( handle );
2428         }
2429         break;
2430
2431     case ActivationContextDetailedInformation:
2432         {
2433             ACTIVATION_CONTEXT_DETAILED_INFORMATION *acdi = buffer;
2434             struct assembly *assembly = NULL;
2435             SIZE_T len, manifest_len = 0, config_len = 0, appdir_len = 0;
2436             LPWSTR ptr;
2437
2438             if (!(actctx = check_actctx(handle))) return STATUS_INVALID_PARAMETER;
2439
2440             if (actctx->num_assemblies) assembly = actctx->assemblies;
2441
2442             if (assembly && assembly->manifest.info)
2443                 manifest_len = strlenW(assembly->manifest.info) + 1;
2444             if (actctx->config.info) config_len = strlenW(actctx->config.info) + 1;
2445             if (actctx->appdir.info) appdir_len = strlenW(actctx->appdir.info) + 1;
2446             len = sizeof(*acdi) + (manifest_len + config_len + appdir_len) * sizeof(WCHAR);
2447
2448             if (retlen) *retlen = len;
2449             if (!buffer || bufsize < len) return STATUS_BUFFER_TOO_SMALL;
2450
2451             acdi->dwFlags = 0;
2452             acdi->ulFormatVersion = assembly ? 1 : 0; /* FIXME */
2453             acdi->ulAssemblyCount = actctx->num_assemblies;
2454             acdi->ulRootManifestPathType = assembly ? assembly->manifest.type : 0 /* FIXME */;
2455             acdi->ulRootManifestPathChars = assembly && assembly->manifest.info ? manifest_len - 1 : 0;
2456             acdi->ulRootConfigurationPathType = actctx->config.type;
2457             acdi->ulRootConfigurationPathChars = actctx->config.info ? config_len - 1 : 0;
2458             acdi->ulAppDirPathType = actctx->appdir.type;
2459             acdi->ulAppDirPathChars = actctx->appdir.info ? appdir_len - 1 : 0;
2460             ptr = (LPWSTR)(acdi + 1);
2461             if (manifest_len)
2462             {
2463                 acdi->lpRootManifestPath = ptr;
2464                 memcpy(ptr, assembly->manifest.info, manifest_len * sizeof(WCHAR));
2465                 ptr += manifest_len;
2466             }
2467             else acdi->lpRootManifestPath = NULL;
2468             if (config_len)
2469             {
2470                 acdi->lpRootConfigurationPath = ptr;
2471                 memcpy(ptr, actctx->config.info, config_len * sizeof(WCHAR));
2472                 ptr += config_len;
2473             }
2474             else acdi->lpRootConfigurationPath = NULL;
2475             if (appdir_len)
2476             {
2477                 acdi->lpAppDirPath = ptr;
2478                 memcpy(ptr, actctx->appdir.info, appdir_len * sizeof(WCHAR));
2479             }
2480             else acdi->lpAppDirPath = NULL;
2481         }
2482         break;
2483
2484     case AssemblyDetailedInformationInActivationContext:
2485         {
2486             ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION *afdi = buffer;
2487             struct assembly *assembly;
2488             WCHAR *assembly_id;
2489             DWORD index;
2490             SIZE_T len, id_len = 0, ad_len = 0, path_len = 0;
2491             LPWSTR ptr;
2492
2493             if (!(actctx = check_actctx(handle))) return STATUS_INVALID_PARAMETER;
2494             if (!subinst) return STATUS_INVALID_PARAMETER;
2495
2496             index = *(DWORD*)subinst;
2497             if (!index || index > actctx->num_assemblies) return STATUS_INVALID_PARAMETER;
2498
2499             assembly = &actctx->assemblies[index - 1];
2500
2501             if (!(assembly_id = build_assembly_id( &assembly->id ))) return STATUS_NO_MEMORY;
2502             id_len = strlenW(assembly_id) + 1;
2503             if (assembly->directory) ad_len = strlenW(assembly->directory) + 1;
2504
2505             if (assembly->manifest.info && assembly->type == ASSEMBLY_MANIFEST)
2506                 path_len  = strlenW(assembly->manifest.info) + 1;
2507
2508             len = sizeof(*afdi) + (id_len + ad_len + path_len) * sizeof(WCHAR);
2509
2510             if (retlen) *retlen = len;
2511             if (!buffer || bufsize < len)
2512             {
2513                 RtlFreeHeap( GetProcessHeap(), 0, assembly_id );
2514                 return STATUS_BUFFER_TOO_SMALL;
2515             }
2516
2517             afdi->ulFlags = 0;  /* FIXME */
2518             afdi->ulEncodedAssemblyIdentityLength = (id_len - 1) * sizeof(WCHAR);
2519             afdi->ulManifestPathType = assembly->manifest.type;
2520             afdi->ulManifestPathLength = assembly->manifest.info ? (path_len - 1) * sizeof(WCHAR) : 0;
2521             /* FIXME afdi->liManifestLastWriteTime = 0; */
2522             afdi->ulPolicyPathType = ACTIVATION_CONTEXT_PATH_TYPE_NONE; /* FIXME */
2523             afdi->ulPolicyPathLength = 0;
2524             /* FIXME afdi->liPolicyLastWriteTime = 0; */
2525             afdi->ulMetadataSatelliteRosterIndex = 0; /* FIXME */
2526             afdi->ulManifestVersionMajor = 1;
2527             afdi->ulManifestVersionMinor = 0;
2528             afdi->ulPolicyVersionMajor = 0; /* FIXME */
2529             afdi->ulPolicyVersionMinor = 0; /* FIXME */
2530             afdi->ulAssemblyDirectoryNameLength = ad_len ? (ad_len - 1) * sizeof(WCHAR) : 0;
2531             ptr = (LPWSTR)(afdi + 1);
2532             afdi->lpAssemblyEncodedAssemblyIdentity = ptr;
2533             memcpy( ptr, assembly_id, id_len * sizeof(WCHAR) );
2534             ptr += id_len;
2535             if (path_len)
2536             {
2537                 afdi->lpAssemblyManifestPath = ptr;
2538                 memcpy(ptr, assembly->manifest.info, path_len * sizeof(WCHAR));
2539                 ptr += path_len;
2540             } else afdi->lpAssemblyManifestPath = NULL;
2541             afdi->lpAssemblyPolicyPath = NULL; /* FIXME */
2542             if (ad_len)
2543             {
2544                 afdi->lpAssemblyDirectoryName = ptr;
2545                 memcpy(ptr, assembly->directory, ad_len * sizeof(WCHAR));
2546                 ptr += ad_len;
2547             }
2548             else afdi->lpAssemblyDirectoryName = NULL;
2549             RtlFreeHeap( GetProcessHeap(), 0, assembly_id );
2550         }
2551         break;
2552
2553     case FileInformationInAssemblyOfAssemblyInActivationContext:
2554         {
2555             const ACTIVATION_CONTEXT_QUERY_INDEX *acqi = subinst;
2556             ASSEMBLY_FILE_DETAILED_INFORMATION *afdi = buffer;
2557             struct assembly *assembly;
2558             struct dll_redirect *dll;
2559             SIZE_T len, dll_len = 0;
2560             LPWSTR ptr;
2561
2562             if (!(actctx = check_actctx(handle))) return STATUS_INVALID_PARAMETER;
2563             if (!acqi) return STATUS_INVALID_PARAMETER;
2564
2565             if (acqi->ulAssemblyIndex >= actctx->num_assemblies)
2566                 return STATUS_INVALID_PARAMETER;
2567             assembly = &actctx->assemblies[acqi->ulAssemblyIndex];
2568
2569             if (acqi->ulFileIndexInAssembly >= assembly->num_dlls)
2570                 return STATUS_INVALID_PARAMETER;
2571             dll = &assembly->dlls[acqi->ulFileIndexInAssembly];
2572
2573             if (dll->name) dll_len = strlenW(dll->name) + 1;
2574             len = sizeof(*afdi) + dll_len * sizeof(WCHAR);
2575
2576             if (!buffer || bufsize < len)
2577             {
2578                 if (retlen) *retlen = len;
2579                 return STATUS_BUFFER_TOO_SMALL;
2580             }
2581             if (retlen) *retlen = 0; /* yes that's what native does !! */
2582             afdi->ulFlags = ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION;
2583             afdi->ulFilenameLength = dll_len ? (dll_len - 1) * sizeof(WCHAR) : 0;
2584             afdi->ulPathLength = 0; /* FIXME */
2585             ptr = (LPWSTR)(afdi + 1);
2586             if (dll_len)
2587             {
2588                 afdi->lpFileName = ptr;
2589                 memcpy( ptr, dll->name, dll_len * sizeof(WCHAR) );
2590             } else afdi->lpFileName = NULL;
2591             afdi->lpFilePath = NULL; /* FIXME */
2592         }
2593         break;
2594
2595     default:
2596         FIXME( "class %u not implemented\n", class );
2597         return STATUS_NOT_IMPLEMENTED;
2598     }
2599     return STATUS_SUCCESS;
2600 }
2601
2602 /***********************************************************************
2603  *              RtlFindActivationContextSectionString (NTDLL.@)
2604  *
2605  * Find information about a string in an activation context.
2606  * FIXME: function signature/prototype may be wrong
2607  */
2608 NTSTATUS WINAPI RtlFindActivationContextSectionString( ULONG flags, const GUID *guid, ULONG section_kind,
2609                                                        const UNICODE_STRING *section_name, PVOID ptr )
2610 {
2611     PACTCTX_SECTION_KEYED_DATA data = ptr;
2612     NTSTATUS status = STATUS_SXS_KEY_NOT_FOUND;
2613
2614     TRACE("%08x %s %u %s %p\n", flags, debugstr_guid(guid), section_kind,
2615           debugstr_us(section_name), data);
2616
2617     if (guid)
2618     {
2619         FIXME("expected guid == NULL\n");
2620         return STATUS_INVALID_PARAMETER;
2621     }
2622     if (flags & ~FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX)
2623     {
2624         FIXME("unknown flags %08x\n", flags);
2625         return STATUS_INVALID_PARAMETER;
2626     }
2627     if (!data || data->cbSize < offsetof(ACTCTX_SECTION_KEYED_DATA, ulAssemblyRosterIndex) ||
2628         !section_name || !section_name->Buffer)
2629     {
2630         WARN("invalid parameter\n");
2631         return STATUS_INVALID_PARAMETER;
2632     }
2633
2634     if (NtCurrentTeb()->ActivationContextStack.ActiveFrame)
2635     {
2636         ACTIVATION_CONTEXT *actctx = check_actctx(NtCurrentTeb()->ActivationContextStack.ActiveFrame->ActivationContext);
2637         if (actctx) status = find_string( actctx, section_kind, section_name, flags, data );
2638     }
2639
2640     if (status != STATUS_SUCCESS)
2641         status = find_string( process_actctx, section_kind, section_name, flags, data );
2642
2643     return status;
2644 }