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