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