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