Converted process creation to Unicode.
[wine/wine64.git] / dlls / ntdll / env.c
blob9097d696507bf7bf7d1b9ae52ea3d681d0200b47
1 /*
2 * Ntdll environment functions
4 * Copyright 1996, 1998 Alexandre Julliard
5 * Copyright 2003 Eric Pouech
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.
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.
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 #include "config.h"
23 #include <assert.h>
24 #include <stdarg.h>
26 #include "windef.h"
27 #include "winbase.h"
28 #include "winreg.h"
29 #include "winternl.h"
30 #include "wine/unicode.h"
31 #include "wine/debug.h"
32 #include "ntdll_misc.h"
34 WINE_DEFAULT_DEBUG_CHANNEL(environ);
36 /******************************************************************************
37 * RtlCreateEnvironment [NTDLL.@]
39 NTSTATUS WINAPI RtlCreateEnvironment(BOOLEAN inherit, PWSTR* env)
41 NTSTATUS nts;
43 TRACE("(%u,%p)!\n", inherit, env);
45 if (inherit)
47 MEMORY_BASIC_INFORMATION mbi;
49 RtlAcquirePebLock();
51 nts = NtQueryVirtualMemory(NtCurrentProcess(), ntdll_get_process_pmts()->Environment,
52 0, &mbi, sizeof(mbi), NULL);
53 if (nts == STATUS_SUCCESS)
55 *env = NULL;
56 nts = NtAllocateVirtualMemory(NtCurrentProcess(), (void**)env, 0, &mbi.RegionSize,
57 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
58 if (nts == STATUS_SUCCESS)
59 memcpy(*env, ntdll_get_process_pmts()->Environment, mbi.RegionSize);
60 else *env = NULL;
62 RtlReleasePebLock();
64 else
66 ULONG size = 1;
67 nts = NtAllocateVirtualMemory(NtCurrentProcess(), (void**)env, 0, &size,
68 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
69 if (nts == STATUS_SUCCESS)
70 memset(*env, 0, size);
73 return nts;
76 /******************************************************************************
77 * RtlDestroyEnvironment [NTDLL.@]
79 NTSTATUS WINAPI RtlDestroyEnvironment(PWSTR env)
81 ULONG size = 0;
83 TRACE("(%p)!\n", env);
85 return NtFreeVirtualMemory(NtCurrentProcess(), (void**)&env, &size, MEM_RELEASE);
88 static LPCWSTR ENV_FindVariable(PCWSTR var, PCWSTR name, unsigned namelen)
90 for (; *var; var += strlenW(var) + 1)
92 /* match var names, but avoid setting a var with a name including a '='
93 * (a starting '=' is valid though)
95 if (strncmpiW(var, name, namelen) == 0 && var[namelen] == '=' &&
96 strchrW(var + 1, '=') == var + namelen)
98 return var + namelen + 1;
101 return NULL;
104 /******************************************************************
105 * RtlQueryEnvironmentVariable_U [NTDLL.@]
107 * NOTES: when the buffer is too small, the string is not written, but if the
108 * terminating null char is the only char that cannot be written, then
109 * all chars (except the null) are written and success is returned
110 * (behavior of Win2k at least)
112 NTSTATUS WINAPI RtlQueryEnvironmentVariable_U(PWSTR env,
113 PUNICODE_STRING name,
114 PUNICODE_STRING value)
116 NTSTATUS nts = STATUS_VARIABLE_NOT_FOUND;
117 PCWSTR var;
118 unsigned namelen;
120 TRACE("%s %s %p\n", debugstr_w(env), debugstr_w(name->Buffer), value);
122 value->Length = 0;
123 namelen = name->Length / sizeof(WCHAR);
124 if (!namelen) return nts;
126 if (!env)
128 RtlAcquirePebLock();
129 var = ntdll_get_process_pmts()->Environment;
131 else var = env;
133 var = ENV_FindVariable(var, name->Buffer, namelen);
134 if (var != NULL)
136 value->Length = strlenW(var) * sizeof(WCHAR);
138 if (value->Length <= value->MaximumLength)
140 memmove(value->Buffer, var, min(value->Length + sizeof(WCHAR), value->MaximumLength));
141 nts = STATUS_SUCCESS;
143 else nts = STATUS_BUFFER_TOO_SMALL;
146 if (!env) RtlReleasePebLock();
148 return nts;
151 /******************************************************************
152 * RtlSetCurrentEnvironment [NTDLL.@]
155 void WINAPI RtlSetCurrentEnvironment(PWSTR new_env, PWSTR* old_env)
157 TRACE("(%p %p)\n", new_env, old_env);
159 RtlAcquirePebLock();
161 if (old_env) *old_env = ntdll_get_process_pmts()->Environment;
162 ntdll_get_process_pmts()->Environment = new_env;
164 RtlReleasePebLock();
168 /******************************************************************************
169 * RtlSetEnvironmentVariable [NTDLL.@]
171 NTSTATUS WINAPI RtlSetEnvironmentVariable(PWSTR* penv, PUNICODE_STRING name,
172 PUNICODE_STRING value)
174 INT len, old_size;
175 LPWSTR p, env;
176 NTSTATUS nts = STATUS_VARIABLE_NOT_FOUND;
177 MEMORY_BASIC_INFORMATION mbi;
179 TRACE("(%p,%s,%s)\n",
180 penv, debugstr_w(name->Buffer),
181 value ? debugstr_w(value->Buffer) : "--nil--");
183 if (!name || !name->Buffer || !name->Buffer[0])
184 return STATUS_INVALID_PARAMETER_1;
185 /* variable names can't contain a '=' except as a first character */
186 if (strchrW(name->Buffer + 1, '=')) return STATUS_INVALID_PARAMETER;
188 if (!penv)
190 RtlAcquirePebLock();
191 env = ntdll_get_process_pmts()->Environment;
192 } else env = *penv;
194 len = name->Length / sizeof(WCHAR);
196 /* compute current size of environment */
197 for (p = env; *p; p += strlenW(p) + 1);
198 old_size = p + 1 - env;
200 /* Find a place to insert the string */
201 for (p = env; *p; p += strlenW(p) + 1)
203 if (!strncmpiW(name->Buffer, p, len) && (p[len] == '=')) break;
205 if (!value && !*p) goto done; /* Value to remove doesn't exist */
207 /* Realloc the buffer */
208 len = value ? len + value->Length / sizeof(WCHAR) + 2 : 0;
209 if (*p) len -= strlenW(p) + 1; /* The name already exists */
211 if (len < 0)
213 LPWSTR next = p + strlenW(p) + 1; /* We know there is a next one */
214 memmove(next + len, next, (old_size - (next - env)) * sizeof(WCHAR));
217 nts = NtQueryVirtualMemory(NtCurrentProcess(), env, 0,
218 &mbi, sizeof(mbi), NULL);
219 if (nts != STATUS_SUCCESS) goto done;
221 if ((old_size + len) * sizeof(WCHAR) > mbi.RegionSize)
223 LPWSTR new_env;
224 ULONG new_size = (old_size + len) * sizeof(WCHAR);
226 new_env = NULL;
227 nts = NtAllocateVirtualMemory(NtCurrentProcess(), (void**)&new_env, 0,
228 &new_size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
229 if (nts != STATUS_SUCCESS) goto done;
231 memmove(new_env, env, (p - env) * sizeof(WCHAR));
232 assert(len > 0);
233 memmove(new_env + (p - env) + len, p, (old_size - (p - env)) * sizeof(WCHAR));
234 p = new_env + (p - env);
236 RtlDestroyEnvironment(env);
237 if (!penv) ntdll_get_process_pmts()->Environment = new_env;
238 else *penv = new_env;
239 env = new_env;
241 else
243 if (len > 0) memmove(p + len, p, (old_size - (p - env)) * sizeof(WCHAR));
246 /* Set the new string */
247 if (value)
249 static const WCHAR equalW[] = {'=',0};
251 strcpyW(p, name->Buffer);
252 strcatW(p, equalW);
253 strcatW(p, value->Buffer);
255 done:
256 if (!penv) RtlReleasePebLock();
258 return nts;
261 /******************************************************************
262 * RtlExpandEnvironmentStrings_U (NTDLL.@)
265 NTSTATUS WINAPI RtlExpandEnvironmentStrings_U(PWSTR renv, const UNICODE_STRING* us_src,
266 PUNICODE_STRING us_dst, PULONG plen)
268 DWORD len, count, total_size = 1; /* 1 for terminating '\0' */
269 LPCWSTR env, src, p, var;
270 LPWSTR dst;
272 src = us_src->Buffer;
273 count = us_dst->MaximumLength / sizeof(WCHAR);
274 dst = count ? us_dst->Buffer : NULL;
276 if (!renv)
278 RtlAcquirePebLock();
279 env = ntdll_get_process_pmts()->Environment;
281 else env = renv;
283 while (*src)
285 if (*src != '%')
287 if ((p = strchrW( src, '%' ))) len = p - src;
288 else len = strlenW(src);
289 var = src;
290 src += len;
292 else /* we are at the start of a variable */
294 if ((p = strchrW( src + 1, '%' )))
296 len = p - src - 1; /* Length of the variable name */
297 if ((var = ENV_FindVariable( env, src + 1, len )))
299 src += len + 2; /* Skip the variable name */
300 len = strlenW(var);
302 else
304 var = src; /* Copy original name instead */
305 len += 2;
306 src += len;
309 else /* unfinished variable name, ignore it */
311 var = src;
312 len = strlenW(src); /* Copy whole string */
313 src += len;
316 total_size += len;
317 if (dst)
319 if (count < len) len = count;
320 memcpy(dst, var, len * sizeof(WCHAR));
321 count -= len;
322 dst += len;
326 if (!renv) RtlReleasePebLock();
328 /* Null-terminate the string */
329 if (dst && count) *dst = '\0';
331 us_dst->Length = (dst) ? (dst - us_dst->Buffer) * sizeof(WCHAR) : 0;
332 if (plen) *plen = total_size * sizeof(WCHAR);
334 return (count) ? STATUS_SUCCESS : STATUS_BUFFER_TOO_SMALL;
338 static inline void normalize( void *base, WCHAR **ptr )
340 if (*ptr) *ptr = (WCHAR *)((char *)base + (UINT_PTR)*ptr);
343 /******************************************************************************
344 * RtlNormalizeProcessParams [NTDLL.@]
346 PRTL_USER_PROCESS_PARAMETERS WINAPI RtlNormalizeProcessParams( RTL_USER_PROCESS_PARAMETERS *params )
348 if (params && !(params->Flags & PROCESS_PARAMS_FLAG_NORMALIZED))
350 normalize( params, &params->CurrentDirectoryName.Buffer );
351 normalize( params, &params->DllPath.Buffer );
352 normalize( params, &params->ImagePathName.Buffer );
353 normalize( params, &params->CommandLine.Buffer );
354 normalize( params, &params->WindowTitle.Buffer );
355 normalize( params, &params->Desktop.Buffer );
356 normalize( params, &params->ShellInfo.Buffer );
357 normalize( params, &params->RuntimeInfo.Buffer );
358 params->Flags |= PROCESS_PARAMS_FLAG_NORMALIZED;
360 return params;
364 static inline void denormalize( void *base, WCHAR **ptr )
366 if (*ptr) *ptr = (WCHAR *)(UINT_PTR)((char *)*ptr - (char *)base);
369 /******************************************************************************
370 * RtlDeNormalizeProcessParams [NTDLL.@]
372 PRTL_USER_PROCESS_PARAMETERS WINAPI RtlDeNormalizeProcessParams( RTL_USER_PROCESS_PARAMETERS *params )
374 if (params && (params->Flags & PROCESS_PARAMS_FLAG_NORMALIZED))
376 denormalize( params, &params->CurrentDirectoryName.Buffer );
377 denormalize( params, &params->DllPath.Buffer );
378 denormalize( params, &params->ImagePathName.Buffer );
379 denormalize( params, &params->CommandLine.Buffer );
380 denormalize( params, &params->WindowTitle.Buffer );
381 denormalize( params, &params->Desktop.Buffer );
382 denormalize( params, &params->ShellInfo.Buffer );
383 denormalize( params, &params->RuntimeInfo.Buffer );
384 params->Flags &= ~PROCESS_PARAMS_FLAG_NORMALIZED;
386 return params;
390 /* append a unicode string to the process params data; helper for RtlCreateProcessParameters */
391 static void append_unicode_string( void **data, const UNICODE_STRING *src,
392 UNICODE_STRING *dst )
394 dst->Length = src->Length;
395 dst->MaximumLength = src->MaximumLength;
396 dst->Buffer = *data;
397 memcpy( dst->Buffer, src->Buffer, dst->MaximumLength );
398 *data = (char *)dst->Buffer + dst->MaximumLength;
402 /******************************************************************************
403 * RtlCreateProcessParameters [NTDLL.@]
405 NTSTATUS WINAPI RtlCreateProcessParameters( RTL_USER_PROCESS_PARAMETERS **result,
406 const UNICODE_STRING *ImagePathName,
407 const UNICODE_STRING *DllPath,
408 const UNICODE_STRING *CurrentDirectoryName,
409 const UNICODE_STRING *CommandLine,
410 PWSTR Environment,
411 const UNICODE_STRING *WindowTitle,
412 const UNICODE_STRING *Desktop,
413 const UNICODE_STRING *ShellInfo,
414 const UNICODE_STRING *RuntimeInfo )
416 static const WCHAR empty[] = {0};
417 static const UNICODE_STRING empty_str = { 0, sizeof(empty), (WCHAR *)empty };
419 const RTL_USER_PROCESS_PARAMETERS *cur_params;
420 ULONG size, total_size;
421 void *ptr;
422 NTSTATUS status;
424 RtlAcquirePebLock();
425 cur_params = NtCurrentTeb()->Peb->ProcessParameters;
426 if (!DllPath) DllPath = &cur_params->DllPath;
427 if (!CurrentDirectoryName) CurrentDirectoryName = &cur_params->CurrentDirectoryName;
428 if (!CommandLine) CommandLine = ImagePathName;
429 if (!Environment) Environment = cur_params->Environment;
430 if (!WindowTitle) WindowTitle = &empty_str;
431 if (!Desktop) Desktop = &empty_str;
432 if (!ShellInfo) ShellInfo = &empty_str;
433 if (!RuntimeInfo) RuntimeInfo = &empty_str;
435 size = (sizeof(RTL_USER_PROCESS_PARAMETERS)
436 + ImagePathName->MaximumLength
437 + DllPath->MaximumLength
438 + CurrentDirectoryName->MaximumLength
439 + CommandLine->MaximumLength
440 + WindowTitle->MaximumLength
441 + Desktop->MaximumLength
442 + ShellInfo->MaximumLength
443 + RuntimeInfo->MaximumLength);
445 total_size = size;
446 if ((status = NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, NULL, &total_size,
447 MEM_COMMIT, PAGE_READWRITE )) == STATUS_SUCCESS)
449 RTL_USER_PROCESS_PARAMETERS *params = ptr;
450 params->AllocationSize = total_size;
451 params->Size = size;
452 params->Flags = PROCESS_PARAMS_FLAG_NORMALIZED;
453 params->ProcessGroup = cur_params->ProcessGroup;
454 params->Environment = Environment;
455 /* all other fields are zero */
457 ptr = params + 1;
458 append_unicode_string( &ptr, CurrentDirectoryName, &params->CurrentDirectoryName );
459 append_unicode_string( &ptr, DllPath, &params->DllPath );
460 append_unicode_string( &ptr, ImagePathName, &params->ImagePathName );
461 append_unicode_string( &ptr, CommandLine, &params->CommandLine );
462 append_unicode_string( &ptr, WindowTitle, &params->WindowTitle );
463 append_unicode_string( &ptr, Desktop, &params->Desktop );
464 append_unicode_string( &ptr, ShellInfo, &params->ShellInfo );
465 append_unicode_string( &ptr, RuntimeInfo, &params->RuntimeInfo );
466 *result = RtlDeNormalizeProcessParams( params );
468 RtlReleasePebLock();
469 return status;
473 /******************************************************************************
474 * RtlDestroyProcessParameters [NTDLL.@]
476 void WINAPI RtlDestroyProcessParameters( RTL_USER_PROCESS_PARAMETERS *params )
478 void *ptr = params;
479 ULONG size = 0;
480 NtFreeVirtualMemory( NtCurrentProcess(), &ptr, &size, MEM_RELEASE );
484 /***********************************************************************
485 * set_library_argv
487 * Set the Wine library argc/argv global variables.
489 static void set_library_argv( char **argv )
491 int argc;
492 WCHAR *p;
493 WCHAR **wargv;
494 DWORD total = 0, len, reslen;
496 for (argc = 0; argv[argc]; argc++)
498 len = strlen(argv[argc]) + 1;
499 RtlMultiByteToUnicodeN(NULL, 0, &reslen, argv[argc], len);
500 total += reslen;
502 wargv = RtlAllocateHeap( ntdll_get_process_heap(), 0,
503 total + (argc + 1) * sizeof(*wargv) );
504 p = (WCHAR *)(wargv + argc + 1);
505 for (argc = 0; argv[argc]; argc++)
507 len = strlen(argv[argc]) + 1;
508 RtlMultiByteToUnicodeN(p, total, &reslen, argv[argc], len);
509 wargv[argc] = p;
510 p += reslen / sizeof(WCHAR);
511 total -= reslen;
513 wargv[argc] = NULL;
515 __wine_main_argc = argc;
516 __wine_main_argv = argv;
517 __wine_main_wargv = wargv;
520 /***********************************************************************
521 * build_command_line
523 * Build the command line of a process from the argv array.
525 * Note that it does NOT necessarily include the file name.
526 * Sometimes we don't even have any command line options at all.
528 * We must quote and escape characters so that the argv array can be rebuilt
529 * from the command line:
530 * - spaces and tabs must be quoted
531 * 'a b' -> '"a b"'
532 * - quotes must be escaped
533 * '"' -> '\"'
534 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
535 * resulting in an odd number of '\' followed by a '"'
536 * '\"' -> '\\\"'
537 * '\\"' -> '\\\\\"'
538 * - '\'s that are not followed by a '"' can be left as is
539 * 'a\b' == 'a\b'
540 * 'a\\b' == 'a\\b'
542 BOOL build_command_line( char **argv )
544 int len;
545 char **arg;
546 LPWSTR p;
547 RTL_USER_PROCESS_PARAMETERS* rupp;
549 set_library_argv( argv );
551 rupp = ntdll_get_process_pmts();
552 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
554 len = 0;
555 for (arg = argv; *arg; arg++)
557 int has_space,bcount;
558 char* a;
560 has_space=0;
561 bcount=0;
562 a=*arg;
563 if( !*a ) has_space=1;
564 while (*a!='\0') {
565 if (*a=='\\') {
566 bcount++;
567 } else {
568 if (*a==' ' || *a=='\t') {
569 has_space=1;
570 } else if (*a=='"') {
571 /* doubling of '\' preceeding a '"',
572 * plus escaping of said '"'
574 len+=2*bcount+1;
576 bcount=0;
578 a++;
580 len+=(a-*arg)+1 /* for the separating space */;
581 if (has_space)
582 len+=2; /* for the quotes */
585 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( ntdll_get_process_heap(), 0, len * sizeof(WCHAR))))
586 return FALSE;
588 p = rupp->CommandLine.Buffer;
589 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
590 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
591 for (arg = argv; *arg; arg++)
593 int has_space,has_quote;
594 char* a;
596 /* Check for quotes and spaces in this argument */
597 has_space=has_quote=0;
598 a=*arg;
599 if( !*a ) has_space=1;
600 while (*a!='\0') {
601 if (*a==' ' || *a=='\t') {
602 has_space=1;
603 if (has_quote)
604 break;
605 } else if (*a=='"') {
606 has_quote=1;
607 if (has_space)
608 break;
610 a++;
613 /* Now transfer it to the command line */
614 if (has_space)
615 *p++='"';
616 if (has_quote) {
617 int bcount;
618 char* a;
620 bcount=0;
621 a=*arg;
622 while (*a!='\0') {
623 if (*a=='\\') {
624 *p++=*a;
625 bcount++;
626 } else {
627 if (*a=='"') {
628 int i;
630 /* Double all the '\\' preceeding this '"', plus one */
631 for (i=0;i<=bcount;i++)
632 *p++='\\';
633 *p++='"';
634 } else {
635 *p++=*a;
637 bcount=0;
639 a++;
641 } else {
642 char* x = *arg;
643 while ((*p=*x++)) p++;
645 if (has_space)
646 *p++='"';
647 *p++=' ';
649 if (p > rupp->CommandLine.Buffer)
650 p--; /* remove last space */
651 *p = '\0';
653 return TRUE;