widl: Print large enum constants in hex.
[wine] / dlls / ntdll / env.c
1 /*
2  * Ntdll environment functions
3  *
4  * Copyright 1996, 1998 Alexandre Julliard
5  * Copyright 2003       Eric Pouech
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20  */
21 #include "config.h"
22
23 #include <assert.h>
24 #include <stdarg.h>
25
26 #include "ntstatus.h"
27 #define WIN32_NO_STATUS
28 #include "windef.h"
29 #include "winternl.h"
30 #include "wine/unicode.h"
31 #include "wine/debug.h"
32 #include "ntdll_misc.h"
33 #include "winnt.h"
34
35 WINE_DEFAULT_DEBUG_CHANNEL(environ);
36
37 /******************************************************************************
38  *  NtQuerySystemEnvironmentValue               [NTDLL.@]
39  */
40 NTSYSAPI NTSTATUS WINAPI NtQuerySystemEnvironmentValue(PUNICODE_STRING VariableName,
41                                                        PWCHAR Value,
42                                                        ULONG ValueBufferLength,
43                                                        PULONG RequiredLength)
44 {
45     FIXME("(%s, %p, %u, %p), stub\n", debugstr_us(VariableName), Value, ValueBufferLength, RequiredLength);
46     return STATUS_NOT_IMPLEMENTED;
47 }
48
49 /******************************************************************************
50  *  NtQuerySystemEnvironmentValueEx             [NTDLL.@]
51  */
52 NTSYSAPI NTSTATUS WINAPI NtQuerySystemEnvironmentValueEx(PUNICODE_STRING name, LPGUID vendor,
53                                                          PVOID value, PULONG retlength, PULONG attrib)
54 {
55     FIXME("(%s, %s, %p, %p, %p), stub\n", debugstr_us(name), debugstr_guid(vendor), value, retlength, attrib);
56     return STATUS_NOT_IMPLEMENTED;
57 }
58
59 /******************************************************************************
60  *  RtlCreateEnvironment                [NTDLL.@]
61  */
62 NTSTATUS WINAPI RtlCreateEnvironment(BOOLEAN inherit, PWSTR* env)
63 {
64     NTSTATUS    nts;
65
66     TRACE("(%u,%p)!\n", inherit, env);
67
68     if (inherit)
69     {
70         MEMORY_BASIC_INFORMATION        mbi;
71
72         RtlAcquirePebLock();
73
74         nts = NtQueryVirtualMemory(NtCurrentProcess(),
75                                    NtCurrentTeb()->Peb->ProcessParameters->Environment,
76                                    0, &mbi, sizeof(mbi), NULL);
77         if (nts == STATUS_SUCCESS)
78         {
79             *env = NULL;
80             nts = NtAllocateVirtualMemory(NtCurrentProcess(), (void**)env, 0, &mbi.RegionSize, 
81                                           MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
82             if (nts == STATUS_SUCCESS)
83                 memcpy(*env, NtCurrentTeb()->Peb->ProcessParameters->Environment, mbi.RegionSize);
84             else *env = NULL;
85         }
86         RtlReleasePebLock();
87     }
88     else 
89     {
90         SIZE_T      size = 1;
91         PVOID       addr = NULL;
92         nts = NtAllocateVirtualMemory(NtCurrentProcess(), &addr, 0, &size,
93                                       MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
94         if (nts == STATUS_SUCCESS) *env = addr;
95     }
96
97     return nts;
98 }
99
100 /******************************************************************************
101  *  RtlDestroyEnvironment               [NTDLL.@]
102  */
103 NTSTATUS WINAPI RtlDestroyEnvironment(PWSTR env) 
104 {
105     SIZE_T size = 0;
106
107     TRACE("(%p)!\n", env);
108
109     return NtFreeVirtualMemory(NtCurrentProcess(), (void**)&env, &size, MEM_RELEASE);
110 }
111
112 static LPCWSTR ENV_FindVariable(PCWSTR var, PCWSTR name, unsigned namelen)
113 {
114     for (; *var; var += strlenW(var) + 1)
115     {
116         /* match var names, but avoid setting a var with a name including a '='
117          * (a starting '=' is valid though)
118          */
119         if (strncmpiW(var, name, namelen) == 0 && var[namelen] == '=' &&
120             strchrW(var + 1, '=') == var + namelen) 
121         {
122             return var + namelen + 1;
123         }
124     }
125     return NULL;
126 }
127
128 /******************************************************************
129  *              RtlQueryEnvironmentVariable_U   [NTDLL.@]
130  *
131  * NOTES: when the buffer is too small, the string is not written, but if the
132  *      terminating null char is the only char that cannot be written, then
133  *      all chars (except the null) are written and success is returned
134  *      (behavior of Win2k at least)
135  */
136 NTSTATUS WINAPI RtlQueryEnvironmentVariable_U(PWSTR env,
137                                               PUNICODE_STRING name,
138                                               PUNICODE_STRING value)
139 {
140     NTSTATUS    nts = STATUS_VARIABLE_NOT_FOUND;
141     PCWSTR      var;
142     unsigned    namelen;
143
144     TRACE("%p %s %p\n", env, debugstr_us(name), value);
145
146     value->Length = 0;
147     namelen = name->Length / sizeof(WCHAR);
148     if (!namelen) return nts;
149
150     if (!env)
151     {
152         RtlAcquirePebLock();
153         var = NtCurrentTeb()->Peb->ProcessParameters->Environment;
154     }
155     else var = env;
156
157     var = ENV_FindVariable(var, name->Buffer, namelen);
158     if (var != NULL)
159     {
160         value->Length = strlenW(var) * sizeof(WCHAR);
161
162         if (value->Length <= value->MaximumLength)
163         {
164             memmove(value->Buffer, var, min(value->Length + sizeof(WCHAR), value->MaximumLength));
165             nts = STATUS_SUCCESS;
166         }
167         else nts = STATUS_BUFFER_TOO_SMALL;
168     }
169
170     if (!env) RtlReleasePebLock();
171
172     return nts;
173 }
174
175 /******************************************************************
176  *              RtlSetCurrentEnvironment        [NTDLL.@]
177  *
178  */
179 void WINAPI RtlSetCurrentEnvironment(PWSTR new_env, PWSTR* old_env)
180 {
181     TRACE("(%p %p)\n", new_env, old_env);
182
183     RtlAcquirePebLock();
184
185     if (old_env) *old_env = NtCurrentTeb()->Peb->ProcessParameters->Environment;
186     NtCurrentTeb()->Peb->ProcessParameters->Environment = new_env;
187
188     RtlReleasePebLock();
189 }
190
191
192 /******************************************************************************
193  *  RtlSetEnvironmentVariable           [NTDLL.@]
194  */
195 NTSTATUS WINAPI RtlSetEnvironmentVariable(PWSTR* penv, PUNICODE_STRING name, 
196                                           PUNICODE_STRING value)
197 {
198     INT         len, old_size;
199     LPWSTR      p, env;
200     NTSTATUS    nts = STATUS_VARIABLE_NOT_FOUND;
201     MEMORY_BASIC_INFORMATION mbi;
202
203     TRACE("(%p, %s, %s)\n", penv, debugstr_us(name), debugstr_us(value));
204
205     if (!name || !name->Buffer || !name->Length)
206         return STATUS_INVALID_PARAMETER_1;
207
208     len = name->Length / sizeof(WCHAR);
209
210     /* variable names can't contain a '=' except as a first character */
211     for (p = name->Buffer + 1; p < name->Buffer + len; p++)
212         if (*p == '=') return STATUS_INVALID_PARAMETER;
213
214     if (!penv)
215     {
216         RtlAcquirePebLock();
217         env = NtCurrentTeb()->Peb->ProcessParameters->Environment;
218     } else env = *penv;
219
220     /* compute current size of environment */
221     for (p = env; *p; p += strlenW(p) + 1);
222     old_size = p + 1 - env;
223
224     /* Find a place to insert the string */
225     for (p = env; *p; p += strlenW(p) + 1)
226     {
227         if (!strncmpiW(name->Buffer, p, len) && (p[len] == '=')) break;
228     }
229     if (!value && !*p) goto done;  /* Value to remove doesn't exist */
230
231     /* Realloc the buffer */
232     len = value ? len + value->Length / sizeof(WCHAR) + 2 : 0;
233     if (*p) len -= strlenW(p) + 1;  /* The name already exists */
234
235     if (len < 0)
236     {
237         LPWSTR next = p + strlenW(p) + 1;  /* We know there is a next one */
238         memmove(next + len, next, (old_size - (next - env)) * sizeof(WCHAR));
239     }
240
241     nts = NtQueryVirtualMemory(NtCurrentProcess(), env, 0,
242                                &mbi, sizeof(mbi), NULL);
243     if (nts != STATUS_SUCCESS) goto done;
244
245     if ((old_size + len) * sizeof(WCHAR) > mbi.RegionSize)
246     {
247         LPWSTR  new_env;
248         SIZE_T  new_size = (old_size + len) * sizeof(WCHAR);
249
250         new_env = NULL;
251         nts = NtAllocateVirtualMemory(NtCurrentProcess(), (void**)&new_env, 0,
252                                       &new_size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
253         if (nts != STATUS_SUCCESS) goto done;
254
255         memmove(new_env, env, (p - env) * sizeof(WCHAR));
256         assert(len > 0);
257         memmove(new_env + (p - env) + len, p, (old_size - (p - env)) * sizeof(WCHAR));
258         p = new_env + (p - env);
259
260         RtlDestroyEnvironment(env);
261         if (!penv) NtCurrentTeb()->Peb->ProcessParameters->Environment = new_env;
262         else *penv = new_env;
263     }
264     else
265     {
266         if (len > 0) memmove(p + len, p, (old_size - (p - env)) * sizeof(WCHAR));
267     }
268
269     /* Set the new string */
270     if (value)
271     {
272         memcpy( p, name->Buffer, name->Length );
273         p += name->Length / sizeof(WCHAR);
274         *p++ = '=';
275         memcpy( p, value->Buffer, value->Length );
276         p[value->Length / sizeof(WCHAR)] = 0;
277     }
278 done:
279     if (!penv) RtlReleasePebLock();
280
281     return nts;
282 }
283
284 /******************************************************************
285  *              RtlExpandEnvironmentStrings_U (NTDLL.@)
286  *
287  */
288 NTSTATUS WINAPI RtlExpandEnvironmentStrings_U(PCWSTR renv, const UNICODE_STRING* us_src,
289                                               PUNICODE_STRING us_dst, PULONG plen)
290 {
291     DWORD src_len, len, count, total_size = 1;  /* 1 for terminating '\0' */
292     LPCWSTR     env, src, p, var;
293     LPWSTR      dst;
294
295     src = us_src->Buffer;
296     src_len = us_src->Length / sizeof(WCHAR);
297     count = us_dst->MaximumLength / sizeof(WCHAR);
298     dst = count ? us_dst->Buffer : NULL;
299
300     if (!renv)
301     {
302         RtlAcquirePebLock();
303         env = NtCurrentTeb()->Peb->ProcessParameters->Environment;
304     }
305     else env = renv;
306
307     while (src_len)
308     {
309         if (*src != '%')
310         {
311             if ((p = memchrW( src, '%', src_len ))) len = p - src;
312             else len = src_len;
313             var = src;
314             src += len;
315             src_len -= len;
316         }
317         else  /* we are at the start of a variable */
318         {
319             if ((p = memchrW( src + 1, '%', src_len - 1 )))
320             {
321                 len = p - src - 1;  /* Length of the variable name */
322                 if ((var = ENV_FindVariable( env, src + 1, len )))
323                 {
324                     src += len + 2;  /* Skip the variable name */
325                     src_len -= len + 2;
326                     len = strlenW(var);
327                 }
328                 else
329                 {
330                     var = src;  /* Copy original name instead */
331                     len += 2;
332                     src += len;
333                     src_len -= len;
334                 }
335             }
336             else  /* unfinished variable name, ignore it */
337             {
338                 var = src;
339                 len = src_len;  /* Copy whole string */
340                 src += len;
341                 src_len = 0;
342             }
343         }
344         total_size += len;
345         if (dst)
346         {
347             if (count < len) len = count;
348             memcpy(dst, var, len * sizeof(WCHAR));
349             count -= len;
350             dst += len;
351         }
352     }
353
354     if (!renv) RtlReleasePebLock();
355
356     /* Null-terminate the string */
357     if (dst && count) *dst = '\0';
358
359     us_dst->Length = (dst) ? (dst - us_dst->Buffer) * sizeof(WCHAR) : 0;
360     if (plen) *plen = total_size * sizeof(WCHAR);
361
362     return (count) ? STATUS_SUCCESS : STATUS_BUFFER_TOO_SMALL;
363 }
364
365
366 static inline void normalize( void *base, WCHAR **ptr )
367 {
368     if (*ptr) *ptr = (WCHAR *)((char *)base + (UINT_PTR)*ptr);
369 }
370
371 /******************************************************************************
372  *  RtlNormalizeProcessParams  [NTDLL.@]
373  */
374 PRTL_USER_PROCESS_PARAMETERS WINAPI RtlNormalizeProcessParams( RTL_USER_PROCESS_PARAMETERS *params )
375 {
376     if (params && !(params->Flags & PROCESS_PARAMS_FLAG_NORMALIZED))
377     {
378         normalize( params, &params->CurrentDirectory.DosPath.Buffer );
379         normalize( params, &params->DllPath.Buffer );
380         normalize( params, &params->ImagePathName.Buffer );
381         normalize( params, &params->CommandLine.Buffer );
382         normalize( params, &params->WindowTitle.Buffer );
383         normalize( params, &params->Desktop.Buffer );
384         normalize( params, &params->ShellInfo.Buffer );
385         normalize( params, &params->RuntimeInfo.Buffer );
386         params->Flags |= PROCESS_PARAMS_FLAG_NORMALIZED;
387     }
388     return params;
389 }
390
391
392 static inline void denormalize( const void *base, WCHAR **ptr )
393 {
394     if (*ptr) *ptr = (WCHAR *)(UINT_PTR)((char *)*ptr - (const char *)base);
395 }
396
397 /******************************************************************************
398  *  RtlDeNormalizeProcessParams  [NTDLL.@]
399  */
400 PRTL_USER_PROCESS_PARAMETERS WINAPI RtlDeNormalizeProcessParams( RTL_USER_PROCESS_PARAMETERS *params )
401 {
402     if (params && (params->Flags & PROCESS_PARAMS_FLAG_NORMALIZED))
403     {
404         denormalize( params, &params->CurrentDirectory.DosPath.Buffer );
405         denormalize( params, &params->DllPath.Buffer );
406         denormalize( params, &params->ImagePathName.Buffer );
407         denormalize( params, &params->CommandLine.Buffer );
408         denormalize( params, &params->WindowTitle.Buffer );
409         denormalize( params, &params->Desktop.Buffer );
410         denormalize( params, &params->ShellInfo.Buffer );
411         denormalize( params, &params->RuntimeInfo.Buffer );
412         params->Flags &= ~PROCESS_PARAMS_FLAG_NORMALIZED;
413     }
414     return params;
415 }
416
417
418 /* append a unicode string to the process params data; helper for RtlCreateProcessParameters */
419 static void append_unicode_string( void **data, const UNICODE_STRING *src,
420                                    UNICODE_STRING *dst )
421 {
422     dst->Length = src->Length;
423     dst->MaximumLength = src->MaximumLength;
424     dst->Buffer = *data;
425     memcpy( dst->Buffer, src->Buffer, dst->MaximumLength );
426     *data = (char *)dst->Buffer + dst->MaximumLength;
427 }
428
429
430 /******************************************************************************
431  *  RtlCreateProcessParameters  [NTDLL.@]
432  */
433 NTSTATUS WINAPI RtlCreateProcessParameters( RTL_USER_PROCESS_PARAMETERS **result,
434                                             const UNICODE_STRING *ImagePathName,
435                                             const UNICODE_STRING *DllPath,
436                                             const UNICODE_STRING *CurrentDirectoryName,
437                                             const UNICODE_STRING *CommandLine,
438                                             PWSTR Environment,
439                                             const UNICODE_STRING *WindowTitle,
440                                             const UNICODE_STRING *Desktop,
441                                             const UNICODE_STRING *ShellInfo,
442                                             const UNICODE_STRING *RuntimeInfo )
443 {
444     static WCHAR empty[] = {0};
445     static const UNICODE_STRING empty_str = { 0, sizeof(empty), empty };
446     static const UNICODE_STRING null_str = { 0, 0, NULL };
447
448     const RTL_USER_PROCESS_PARAMETERS *cur_params;
449     SIZE_T size, total_size;
450     void *ptr;
451     NTSTATUS status;
452
453     RtlAcquirePebLock();
454     cur_params = NtCurrentTeb()->Peb->ProcessParameters;
455     if (!DllPath) DllPath = &cur_params->DllPath;
456     if (!CurrentDirectoryName)
457     {
458         if (NtCurrentTeb()->Tib.SubSystemTib)  /* FIXME: hack */
459             CurrentDirectoryName = &((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir.DosPath;
460         else
461             CurrentDirectoryName = &cur_params->CurrentDirectory.DosPath;
462     }
463     if (!CommandLine) CommandLine = ImagePathName;
464     if (!Environment) Environment = cur_params->Environment;
465     if (!WindowTitle) WindowTitle = &empty_str;
466     if (!Desktop) Desktop = &empty_str;
467     if (!ShellInfo) ShellInfo = &empty_str;
468     if (!RuntimeInfo) RuntimeInfo = &null_str;
469
470     size = (sizeof(RTL_USER_PROCESS_PARAMETERS)
471             + ImagePathName->MaximumLength
472             + DllPath->MaximumLength
473             + CurrentDirectoryName->MaximumLength
474             + CommandLine->MaximumLength
475             + WindowTitle->MaximumLength
476             + Desktop->MaximumLength
477             + ShellInfo->MaximumLength
478             + RuntimeInfo->MaximumLength);
479
480     total_size = size;
481     ptr = NULL;
482     if ((status = NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0, &total_size,
483                                            MEM_COMMIT, PAGE_READWRITE )) == STATUS_SUCCESS)
484     {
485         RTL_USER_PROCESS_PARAMETERS *params = ptr;
486         params->AllocationSize = total_size;
487         params->Size           = size;
488         params->Flags          = PROCESS_PARAMS_FLAG_NORMALIZED;
489         params->ConsoleFlags   = cur_params->ConsoleFlags;
490         params->Environment    = Environment;
491         /* all other fields are zero */
492
493         ptr = params + 1;
494         append_unicode_string( &ptr, CurrentDirectoryName, &params->CurrentDirectory.DosPath );
495         append_unicode_string( &ptr, DllPath, &params->DllPath );
496         append_unicode_string( &ptr, ImagePathName, &params->ImagePathName );
497         append_unicode_string( &ptr, CommandLine, &params->CommandLine );
498         append_unicode_string( &ptr, WindowTitle, &params->WindowTitle );
499         append_unicode_string( &ptr, Desktop, &params->Desktop );
500         append_unicode_string( &ptr, ShellInfo, &params->ShellInfo );
501         append_unicode_string( &ptr, RuntimeInfo, &params->RuntimeInfo );
502         *result = RtlDeNormalizeProcessParams( params );
503     }
504     RtlReleasePebLock();
505     return status;
506 }
507
508
509 /******************************************************************************
510  *  RtlDestroyProcessParameters  [NTDLL.@]
511  */
512 void WINAPI RtlDestroyProcessParameters( RTL_USER_PROCESS_PARAMETERS *params )
513 {
514     void *ptr = params;
515     SIZE_T size = 0;
516     NtFreeVirtualMemory( NtCurrentProcess(), &ptr, &size, MEM_RELEASE );
517 }