Fixed some issues found by winapi_check.
[wine] / memory / environ.c
1 /*
2  * Process environment management
3  *
4  * Copyright 1996, 1998 Alexandre Julliard
5  */
6
7 #include <stdlib.h>
8 #include <string.h>
9 #include "wine/port.h"
10 #include "windef.h"
11 #include "winnls.h"
12 #include "winerror.h"
13 #include "ntddk.h"
14 #include "heap.h"
15 #include "selectors.h"
16
17 /* Win32 process environment database */
18 typedef struct _ENVDB
19 {
20     LPSTR            environ;          /* 00 Process environment strings */
21     DWORD            unknown1;         /* 04 Unknown */
22     LPSTR            cmd_line;         /* 08 Command line */
23     LPSTR            cur_dir;          /* 0c Current directory */
24     STARTUPINFOA    *startup_info;     /* 10 Startup information */
25     HANDLE           hStdin;           /* 14 Handle for standard input */
26     HANDLE           hStdout;          /* 18 Handle for standard output */
27     HANDLE           hStderr;          /* 1c Handle for standard error */
28     DWORD            unknown2;         /* 20 Unknown */
29     DWORD            inherit_console;  /* 24 Inherit console flag */
30     DWORD            break_type;       /* 28 Console events flag */
31     void            *break_sem;        /* 2c SetConsoleCtrlHandler semaphore */
32     void            *break_event;      /* 30 SetConsoleCtrlHandler event */
33     void            *break_thread;     /* 34 SetConsoleCtrlHandler thread */
34     void            *break_handlers;   /* 38 List of console handlers */
35 } ENVDB;
36
37
38 /* Format of an environment block:
39  * ASCIIZ   string 1 (xx=yy format)
40  * ...
41  * ASCIIZ   string n
42  * BYTE     0
43  * WORD     1
44  * ASCIIZ   program name (e.g. C:\WINDOWS\SYSTEM\KRNL386.EXE)
45  *
46  * Notes:
47  * - contrary to Microsoft docs, the environment strings do not appear
48  *   to be sorted on Win95 (although they are on NT); so we don't bother
49  *   to sort them either.
50  */
51
52 static const char ENV_program_name[] = "C:\\WINDOWS\\SYSTEM\\KRNL386.EXE";
53
54 /* Maximum length of a Win16 environment string (including NULL) */
55 #define MAX_WIN16_LEN  128
56
57 /* Extra bytes to reserve at the end of an environment */
58 #define EXTRA_ENV_SIZE (sizeof(BYTE) + sizeof(WORD) + sizeof(ENV_program_name))
59
60 /* Fill the extra bytes with the program name and stuff */
61 #define FILL_EXTRA_ENV(p) \
62     *(p) = '\0'; \
63     PUT_UA_WORD( (p) + 1, 1 ); \
64     strcpy( (p) + 3, ENV_program_name );
65
66 STARTUPINFOA current_startupinfo =
67 {
68     sizeof(STARTUPINFOA),    /* cb */
69     0,                       /* lpReserved */
70     0,                       /* lpDesktop */
71     0,                       /* lpTitle */
72     0,                       /* dwX */
73     0,                       /* dwY */
74     0,                       /* dwXSize */
75     0,                       /* dwYSize */
76     0,                       /* dwXCountChars */
77     0,                       /* dwYCountChars */
78     0,                       /* dwFillAttribute */
79     0,                       /* dwFlags */
80     0,                       /* wShowWindow */
81     0,                       /* cbReserved2 */
82     0,                       /* lpReserved2 */
83     0,                       /* hStdInput */
84     0,                       /* hStdOutput */
85     0                        /* hStdError */
86 };
87
88 ENVDB current_envdb =
89 {
90     0,                       /* environ */
91     0,                       /* unknown1 */
92     0,                       /* cmd_line */
93     0,                       /* cur_dir */
94     &current_startupinfo,    /* startup_info */
95     0,                       /* hStdin */
96     0,                       /* hStdout */
97     0,                       /* hStderr */
98     0,                       /* unknown2 */
99     0,                       /* inherit_console */
100     0,                       /* break_type */
101     0,                       /* break_sem */
102     0,                       /* break_event */
103     0,                       /* break_thread */
104     0                        /* break_handlers */
105 };
106
107
108 static WCHAR *cmdlineW;  /* Unicode command line */
109 static WORD env_sel;     /* selector to the environment */
110
111 /***********************************************************************
112  *           ENV_FindVariable
113  *
114  * Find a variable in the environment and return a pointer to the value.
115  * Helper function for GetEnvironmentVariable and ExpandEnvironmentStrings.
116  */
117 static LPCSTR ENV_FindVariable( LPCSTR env, LPCSTR name, INT len )
118 {
119     while (*env)
120     {
121         if (!strncasecmp( name, env, len ) && (env[len] == '='))
122             return env + len + 1;
123         env += strlen(env) + 1;
124     }
125     return NULL;
126 }
127
128
129 /***********************************************************************
130  *           ENV_BuildEnvironment
131  *
132  * Build the environment for the initial process
133  */
134 ENVDB *ENV_BuildEnvironment(void)
135 {
136     extern char **environ;
137     LPSTR p, *e;
138     int size;
139
140     /* Compute the total size of the Unix environment */
141
142     size = EXTRA_ENV_SIZE;
143     for (e = environ; *e; e++) size += strlen(*e) + 1;
144
145     /* Now allocate the environment */
146
147     if (!(p = HeapAlloc( GetProcessHeap(), 0, size ))) return NULL;
148     current_envdb.environ = p;
149     env_sel = SELECTOR_AllocBlock( p, 0x10000, WINE_LDT_FLAGS_DATA );
150
151     /* And fill it with the Unix environment */
152
153     for (e = environ; *e; e++)
154     {
155         strcpy( p, *e );
156         p += strlen(p) + 1;
157     }
158
159     /* Now add the program name */
160
161     FILL_EXTRA_ENV( p );
162     return &current_envdb;
163 }
164
165
166 /***********************************************************************
167  *           ENV_BuildCommandLine
168  *
169  * Build the command line of a process from the argv array.
170  *
171  * Note that it does NOT necessarily include the file name.
172  * Sometimes we don't even have any command line options at all.
173  */
174 BOOL ENV_BuildCommandLine( char **argv )
175 {
176     int len, quote = 0;
177     char *p, **arg;
178
179     for (arg = argv, len = 0; *arg; arg++) len += strlen(*arg) + 1;
180     if ((argv[0]) && (quote = (strchr( argv[0], ' ' ) != NULL))) len += 2;
181     if (!(p = current_envdb.cmd_line = HeapAlloc( GetProcessHeap(), 0, len ))) return FALSE;
182     arg = argv;
183     if (quote)
184     {
185         *p++ = '\"';
186         strcpy( p, *arg );
187         p += strlen(p);
188         *p++ = '\"';
189         *p++ = ' ';
190         arg++;
191     }
192     while (*arg)
193     {
194         strcpy( p, *arg );
195         p += strlen(p);
196         *p++ = ' ';
197         arg++;
198     }
199     if (p > current_envdb.cmd_line) p--;  /* remove last space */
200     *p = 0;
201     /* now allocate the Unicode version */
202     len = MultiByteToWideChar( CP_ACP, 0, current_envdb.cmd_line, -1, NULL, 0 );
203     if (!(cmdlineW = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) )))
204         return FALSE;
205     MultiByteToWideChar( CP_ACP, 0, current_envdb.cmd_line, -1, cmdlineW, len );
206     return TRUE;
207 }
208
209
210 /***********************************************************************
211  *           GetCommandLineA      (KERNEL32.@)
212  */
213 LPSTR WINAPI GetCommandLineA(void)
214 {
215     return current_envdb.cmd_line;
216 }
217
218 /***********************************************************************
219  *           GetCommandLineW      (KERNEL32.@)
220  */
221 LPWSTR WINAPI GetCommandLineW(void)
222 {
223     return cmdlineW;
224 }
225
226
227 /***********************************************************************
228  *           GetEnvironmentStringsA   (KERNEL32.@)
229  *           GetEnvironmentStringsA   (KERNEL32.@)
230  */
231 LPSTR WINAPI GetEnvironmentStringsA(void)
232 {
233     return current_envdb.environ;
234 }
235
236
237 /***********************************************************************
238  *           GetEnvironmentStringsW   (KERNEL32.@)
239  */
240 LPWSTR WINAPI GetEnvironmentStringsW(void)
241 {
242     INT size;
243     LPWSTR ret;
244
245     RtlAcquirePebLock();
246     size = HeapSize( GetProcessHeap(), 0, current_envdb.environ );
247     if ((ret = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) )) != NULL)
248     {
249         LPSTR pA = current_envdb.environ;
250         LPWSTR pW = ret;
251         while (size--) *pW++ = (WCHAR)(BYTE)*pA++;
252     }
253     RtlReleasePebLock();
254     return ret;
255 }
256
257
258 /***********************************************************************
259  *           FreeEnvironmentStringsA   (KERNEL32.@)
260  */
261 BOOL WINAPI FreeEnvironmentStringsA( LPSTR ptr )
262 {
263     if (ptr != current_envdb.environ)
264     {
265         SetLastError( ERROR_INVALID_PARAMETER );
266         return FALSE;
267     }
268     return TRUE;
269 }
270
271
272 /***********************************************************************
273  *           FreeEnvironmentStringsW   (KERNEL32.@)
274  */
275 BOOL WINAPI FreeEnvironmentStringsW( LPWSTR ptr )
276 {
277     return HeapFree( GetProcessHeap(), 0, ptr );
278 }
279
280
281 /***********************************************************************
282  *           GetEnvironmentVariableA   (KERNEL32.@)
283  */
284 DWORD WINAPI GetEnvironmentVariableA( LPCSTR name, LPSTR value, DWORD size )
285 {
286     LPCSTR p;
287     INT ret = 0;
288
289     if (!name || !*name)
290     {
291         SetLastError( ERROR_INVALID_PARAMETER );
292         return 0;
293     }
294     RtlAcquirePebLock();
295     if ((p = ENV_FindVariable( current_envdb.environ, name, strlen(name) )))
296     {
297         ret = strlen(p);
298         if (size <= ret)
299         {
300             /* If not enough room, include the terminating null
301              * in the returned size and return an empty string */
302             ret++;
303             if (value) *value = '\0';
304         }
305         else if (value) strcpy( value, p );
306     }
307     RtlReleasePebLock();
308     if (!ret)
309         SetLastError( ERROR_ENVVAR_NOT_FOUND );
310     return ret;
311 }
312
313
314 /***********************************************************************
315  *           GetEnvironmentVariableW   (KERNEL32.@)
316  */
317 DWORD WINAPI GetEnvironmentVariableW( LPCWSTR nameW, LPWSTR valW, DWORD size)
318 {
319     LPSTR name = HEAP_strdupWtoA( GetProcessHeap(), 0, nameW );
320     LPSTR val  = valW ? HeapAlloc( GetProcessHeap(), 0, size ) : NULL;
321     DWORD res  = GetEnvironmentVariableA( name, val, size );
322     HeapFree( GetProcessHeap(), 0, name );
323     if (val)
324     {
325         if (size > 0 && !MultiByteToWideChar( CP_ACP, 0, val, -1, valW, size ))
326             valW[size-1] = 0;
327         HeapFree( GetProcessHeap(), 0, val );
328     }
329     return res;
330 }
331
332
333 /***********************************************************************
334  *           SetEnvironmentVariableA   (KERNEL32.@)
335  */
336 BOOL WINAPI SetEnvironmentVariableA( LPCSTR name, LPCSTR value )
337 {
338     INT old_size, len, res;
339     LPSTR p, env, new_env;
340     BOOL ret = FALSE;
341
342     RtlAcquirePebLock();
343     env = p = current_envdb.environ;
344
345     /* Find a place to insert the string */
346
347     res = -1;
348     len = strlen(name);
349     while (*p)
350     {
351         if (!strncasecmp( name, p, len ) && (p[len] == '=')) break;
352         p += strlen(p) + 1;
353     }
354     if (!value && !*p) goto done;  /* Value to remove doesn't exist */
355
356     /* Realloc the buffer */
357
358     len = value ? strlen(name) + strlen(value) + 2 : 0;
359     if (*p) len -= strlen(p) + 1;  /* The name already exists */
360     old_size = HeapSize( GetProcessHeap(), 0, env );
361     if (len < 0)
362     {
363         LPSTR next = p + strlen(p) + 1;  /* We know there is a next one */
364         memmove( next + len, next, old_size - (next - env) );
365     }
366     if (!(new_env = HeapReAlloc( GetProcessHeap(), 0, env, old_size + len )))
367         goto done;
368     if (env_sel) env_sel = SELECTOR_ReallocBlock( env_sel, new_env, old_size + len );
369     p = new_env + (p - env);
370     if (len > 0) memmove( p + len, p, old_size - (p - new_env) );
371
372     /* Set the new string */
373
374     if (value)
375     {
376         strcpy( p, name );
377         strcat( p, "=" );
378         strcat( p, value );
379     }
380     current_envdb.environ = new_env;
381     ret = TRUE;
382
383 done:
384     RtlReleasePebLock();
385     return ret;
386 }
387
388
389 /***********************************************************************
390  *           SetEnvironmentVariableW   (KERNEL32.@)
391  */
392 BOOL WINAPI SetEnvironmentVariableW( LPCWSTR name, LPCWSTR value )
393 {
394     LPSTR nameA  = HEAP_strdupWtoA( GetProcessHeap(), 0, name );
395     LPSTR valueA = HEAP_strdupWtoA( GetProcessHeap(), 0, value );
396     BOOL ret = SetEnvironmentVariableA( nameA, valueA );
397     HeapFree( GetProcessHeap(), 0, nameA );
398     HeapFree( GetProcessHeap(), 0, valueA );
399     return ret;
400 }
401
402
403 /***********************************************************************
404  *           ExpandEnvironmentStringsA   (KERNEL32.@)
405  *
406  * Note: overlapping buffers are not supported; this is how it should be.
407  */
408 DWORD WINAPI ExpandEnvironmentStringsA( LPCSTR src, LPSTR dst, DWORD count )
409 {
410     DWORD len, total_size = 1;  /* 1 for terminating '\0' */
411     LPCSTR p, var;
412
413     if (!count) dst = NULL;
414     RtlAcquirePebLock();
415
416     while (*src)
417     {
418         if (*src != '%')
419         {
420             if ((p = strchr( src, '%' ))) len = p - src;
421             else len = strlen(src);
422             var = src;
423             src += len;
424         }
425         else  /* we are at the start of a variable */
426         {
427             if ((p = strchr( src + 1, '%' )))
428             {
429                 len = p - src - 1;  /* Length of the variable name */
430                 if ((var = ENV_FindVariable( current_envdb.environ,
431                                              src + 1, len )))
432                 {
433                     src += len + 2;  /* Skip the variable name */
434                     len = strlen(var);
435                 }
436                 else
437                 {
438                     var = src;  /* Copy original name instead */
439                     len += 2;
440                     src += len;
441                 }
442             }
443             else  /* unfinished variable name, ignore it */
444             {
445                 var = src;
446                 len = strlen(src);  /* Copy whole string */
447                 src += len;
448             }
449         }
450         total_size += len;
451         if (dst)
452         {
453             if (count < len) len = count;
454             memcpy( dst, var, len );
455             dst += len;
456             count -= len;
457         }
458     }
459     RtlReleasePebLock();
460
461     /* Null-terminate the string */
462     if (dst)
463     {
464         if (!count) dst--;
465         *dst = '\0';
466     }
467     return total_size;
468 }
469
470
471 /***********************************************************************
472  *           ExpandEnvironmentStringsW   (KERNEL32.@)
473  */
474 DWORD WINAPI ExpandEnvironmentStringsW( LPCWSTR src, LPWSTR dst, DWORD len )
475 {
476     LPSTR srcA = HEAP_strdupWtoA( GetProcessHeap(), 0, src );
477     LPSTR dstA = dst ? HeapAlloc( GetProcessHeap(), 0, len ) : NULL;
478     DWORD ret  = ExpandEnvironmentStringsA( srcA, dstA, len );
479     if (dstA)
480     {
481         ret = MultiByteToWideChar( CP_ACP, 0, dstA, -1, dst, len );
482         HeapFree( GetProcessHeap(), 0, dstA );
483     }
484     HeapFree( GetProcessHeap(), 0, srcA );
485     return ret;
486 }
487
488
489 /***********************************************************************
490  *           GetDOSEnvironment16   (KERNEL.131)
491  */
492 SEGPTR WINAPI GetDOSEnvironment16(void)
493 {
494     return MAKESEGPTR( env_sel, 0 );
495 }
496
497
498 /***********************************************************************
499  *           GetStdHandle    (KERNEL32.@)
500  */
501 HANDLE WINAPI GetStdHandle( DWORD std_handle )
502 {
503     switch(std_handle)
504     {
505         case STD_INPUT_HANDLE:  return current_envdb.hStdin;
506         case STD_OUTPUT_HANDLE: return current_envdb.hStdout;
507         case STD_ERROR_HANDLE:  return current_envdb.hStderr;
508     }
509     SetLastError( ERROR_INVALID_PARAMETER );
510     return INVALID_HANDLE_VALUE;
511 }
512
513
514 /***********************************************************************
515  *           SetStdHandle    (KERNEL32.@)
516  */
517 BOOL WINAPI SetStdHandle( DWORD std_handle, HANDLE handle )
518 {
519     switch(std_handle)
520     {
521         case STD_INPUT_HANDLE:  current_envdb.hStdin = handle;  return TRUE;
522         case STD_OUTPUT_HANDLE: current_envdb.hStdout = handle; return TRUE;
523         case STD_ERROR_HANDLE:  current_envdb.hStderr = handle; return TRUE;
524     }
525     SetLastError( ERROR_INVALID_PARAMETER );
526     return FALSE;
527 }
528
529
530 /***********************************************************************
531  *              GetStartupInfoA         (KERNEL32.@)
532  */
533 VOID WINAPI GetStartupInfoA( LPSTARTUPINFOA info )
534 {
535     *info = current_startupinfo;
536 }
537
538
539 /***********************************************************************
540  *              GetStartupInfoW         (KERNEL32.@)
541  */
542 VOID WINAPI GetStartupInfoW( LPSTARTUPINFOW info )
543 {
544     info->cb              = sizeof(STARTUPINFOW);
545     info->dwX             = current_startupinfo.dwX;
546     info->dwY             = current_startupinfo.dwY;
547     info->dwXSize         = current_startupinfo.dwXSize;
548     info->dwXCountChars   = current_startupinfo.dwXCountChars;
549     info->dwYCountChars   = current_startupinfo.dwYCountChars;
550     info->dwFillAttribute = current_startupinfo.dwFillAttribute;
551     info->dwFlags         = current_startupinfo.dwFlags;
552     info->wShowWindow     = current_startupinfo.wShowWindow;
553     info->cbReserved2     = current_startupinfo.cbReserved2;
554     info->lpReserved2     = current_startupinfo.lpReserved2;
555     info->hStdInput       = current_startupinfo.hStdInput;
556     info->hStdOutput      = current_startupinfo.hStdOutput;
557     info->hStdError       = current_startupinfo.hStdError;
558     info->lpReserved = HEAP_strdupAtoW (GetProcessHeap(), 0, current_startupinfo.lpReserved );
559     info->lpDesktop  = HEAP_strdupAtoW (GetProcessHeap(), 0, current_startupinfo.lpDesktop );
560     info->lpTitle    = HEAP_strdupAtoW (GetProcessHeap(), 0, current_startupinfo.lpTitle );
561 }