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