Added stubs for msrle32.dll and implemented RLE8 decoder.
[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  * WARNING: there's a Windows incompatibility lurking here !
305  * Win32s always includes the full path of the program file,
306  * whereas Windows NT only returns the full file path plus arguments
307  * in case the program has been started with a full path.
308  * Win9x seems to have inherited NT behaviour.
309  * 
310  * Note that both Start Menu Execute and Explorer start programs with
311  * fully specified quoted app file paths, which is why probably the only case
312  * where you'll see single file names is in case of direct launch
313  * via CreateProcess or WinExec.
314  *
315  * Perhaps we should take care of Win3.1 programs here (Win32s "feature").
316  * 
317  * References: MS KB article q102762.txt (special Win32s handling)
318  */
319 LPSTR WINAPI GetCommandLineA(void)
320 {
321     return current_envdb.cmd_line;
322 }
323
324 /***********************************************************************
325  *           GetCommandLineW      (KERNEL32.@)
326  */
327 LPWSTR WINAPI GetCommandLineW(void)
328 {
329     return cmdlineW;
330 }
331
332
333 /***********************************************************************
334  *           GetEnvironmentStrings    (KERNEL32.@)
335  *           GetEnvironmentStringsA   (KERNEL32.@)
336  */
337 LPSTR WINAPI GetEnvironmentStringsA(void)
338 {
339     return current_envdb.environ;
340 }
341
342
343 /***********************************************************************
344  *           GetEnvironmentStringsW   (KERNEL32.@)
345  */
346 LPWSTR WINAPI GetEnvironmentStringsW(void)
347 {
348     INT size;
349     LPWSTR ret;
350
351     RtlAcquirePebLock();
352     size = HeapSize( GetProcessHeap(), 0, current_envdb.environ );
353     if ((ret = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) )) != NULL)
354     {
355         LPSTR pA = current_envdb.environ;
356         LPWSTR pW = ret;
357         while (size--) *pW++ = (WCHAR)(BYTE)*pA++;
358     }
359     RtlReleasePebLock();
360     return ret;
361 }
362
363
364 /***********************************************************************
365  *           FreeEnvironmentStringsA   (KERNEL32.@)
366  */
367 BOOL WINAPI FreeEnvironmentStringsA( LPSTR ptr )
368 {
369     if (ptr != current_envdb.environ)
370     {
371         SetLastError( ERROR_INVALID_PARAMETER );
372         return FALSE;
373     }
374     return TRUE;
375 }
376
377
378 /***********************************************************************
379  *           FreeEnvironmentStringsW   (KERNEL32.@)
380  */
381 BOOL WINAPI FreeEnvironmentStringsW( LPWSTR ptr )
382 {
383     return HeapFree( GetProcessHeap(), 0, ptr );
384 }
385
386
387 /***********************************************************************
388  *           GetEnvironmentVariableA   (KERNEL32.@)
389  */
390 DWORD WINAPI GetEnvironmentVariableA( LPCSTR name, LPSTR value, DWORD size )
391 {
392     LPCSTR p;
393     INT ret = 0;
394
395     if (!name || !*name)
396     {
397         SetLastError( ERROR_INVALID_PARAMETER );
398         return 0;
399     }
400     RtlAcquirePebLock();
401     if ((p = ENV_FindVariable( current_envdb.environ, name, strlen(name) )))
402     {
403         ret = strlen(p);
404         if (size <= ret)
405         {
406             /* If not enough room, include the terminating null
407              * in the returned size and return an empty string */
408             ret++;
409             if (value) *value = '\0';
410         }
411         else if (value) strcpy( value, p );
412     }
413     RtlReleasePebLock();
414     if (!ret)
415         SetLastError( ERROR_ENVVAR_NOT_FOUND );
416     return ret;
417 }
418
419
420 /***********************************************************************
421  *           GetEnvironmentVariableW   (KERNEL32.@)
422  */
423 DWORD WINAPI GetEnvironmentVariableW( LPCWSTR nameW, LPWSTR valW, DWORD size)
424 {
425     LPSTR name = HEAP_strdupWtoA( GetProcessHeap(), 0, nameW );
426     LPSTR val  = valW ? HeapAlloc( GetProcessHeap(), 0, size ) : NULL;
427     DWORD res  = GetEnvironmentVariableA( name, val, size );
428     HeapFree( GetProcessHeap(), 0, name );
429     if (val)
430     {
431         if (size > 0 && !MultiByteToWideChar( CP_ACP, 0, val, -1, valW, size ))
432             valW[size-1] = 0;
433         HeapFree( GetProcessHeap(), 0, val );
434     }
435     return res;
436 }
437
438
439 /***********************************************************************
440  *           SetEnvironmentVariableA   (KERNEL32.@)
441  */
442 BOOL WINAPI SetEnvironmentVariableA( LPCSTR name, LPCSTR value )
443 {
444     INT old_size, len, res;
445     LPSTR p, env, new_env;
446     BOOL ret = FALSE;
447
448     RtlAcquirePebLock();
449     env = p = current_envdb.environ;
450
451     /* Find a place to insert the string */
452
453     res = -1;
454     len = strlen(name);
455     while (*p)
456     {
457         if (!strncasecmp( name, p, len ) && (p[len] == '=')) break;
458         p += strlen(p) + 1;
459     }
460     if (!value && !*p) goto done;  /* Value to remove doesn't exist */
461
462     /* Realloc the buffer */
463
464     len = value ? strlen(name) + strlen(value) + 2 : 0;
465     if (*p) len -= strlen(p) + 1;  /* The name already exists */
466     old_size = HeapSize( GetProcessHeap(), 0, env );
467     if (len < 0)
468     {
469         LPSTR next = p + strlen(p) + 1;  /* We know there is a next one */
470         memmove( next + len, next, old_size - (next - env) );
471     }
472     if (!(new_env = HeapReAlloc( GetProcessHeap(), 0, env, old_size + len )))
473         goto done;
474     if (env_sel) env_sel = SELECTOR_ReallocBlock( env_sel, new_env, old_size + len );
475     p = new_env + (p - env);
476     if (len > 0) memmove( p + len, p, old_size - (p - new_env) );
477
478     /* Set the new string */
479
480     if (value)
481     {
482         strcpy( p, name );
483         strcat( p, "=" );
484         strcat( p, value );
485     }
486     current_envdb.environ = new_env;
487     ret = TRUE;
488
489 done:
490     RtlReleasePebLock();
491     return ret;
492 }
493
494
495 /***********************************************************************
496  *           SetEnvironmentVariableW   (KERNEL32.@)
497  */
498 BOOL WINAPI SetEnvironmentVariableW( LPCWSTR name, LPCWSTR value )
499 {
500     LPSTR nameA  = HEAP_strdupWtoA( GetProcessHeap(), 0, name );
501     LPSTR valueA = HEAP_strdupWtoA( GetProcessHeap(), 0, value );
502     BOOL ret = SetEnvironmentVariableA( nameA, valueA );
503     HeapFree( GetProcessHeap(), 0, nameA );
504     HeapFree( GetProcessHeap(), 0, valueA );
505     return ret;
506 }
507
508
509 /***********************************************************************
510  *           ExpandEnvironmentStringsA   (KERNEL32.@)
511  *
512  * Note: overlapping buffers are not supported; this is how it should be.
513  */
514 DWORD WINAPI ExpandEnvironmentStringsA( LPCSTR src, LPSTR dst, DWORD count )
515 {
516     DWORD len, total_size = 1;  /* 1 for terminating '\0' */
517     LPCSTR p, var;
518
519     if (!count) dst = NULL;
520     RtlAcquirePebLock();
521
522     while (*src)
523     {
524         if (*src != '%')
525         {
526             if ((p = strchr( src, '%' ))) len = p - src;
527             else len = strlen(src);
528             var = src;
529             src += len;
530         }
531         else  /* we are at the start of a variable */
532         {
533             if ((p = strchr( src + 1, '%' )))
534             {
535                 len = p - src - 1;  /* Length of the variable name */
536                 if ((var = ENV_FindVariable( current_envdb.environ,
537                                              src + 1, len )))
538                 {
539                     src += len + 2;  /* Skip the variable name */
540                     len = strlen(var);
541                 }
542                 else
543                 {
544                     var = src;  /* Copy original name instead */
545                     len += 2;
546                     src += len;
547                 }
548             }
549             else  /* unfinished variable name, ignore it */
550             {
551                 var = src;
552                 len = strlen(src);  /* Copy whole string */
553                 src += len;
554             }
555         }
556         total_size += len;
557         if (dst)
558         {
559             if (count < len) len = count;
560             memcpy( dst, var, len );
561             dst += len;
562             count -= len;
563         }
564     }
565     RtlReleasePebLock();
566
567     /* Null-terminate the string */
568     if (dst)
569     {
570         if (!count) dst--;
571         *dst = '\0';
572     }
573     return total_size;
574 }
575
576
577 /***********************************************************************
578  *           ExpandEnvironmentStringsW   (KERNEL32.@)
579  */
580 DWORD WINAPI ExpandEnvironmentStringsW( LPCWSTR src, LPWSTR dst, DWORD len )
581 {
582     LPSTR srcA = HEAP_strdupWtoA( GetProcessHeap(), 0, src );
583     LPSTR dstA = dst ? HeapAlloc( GetProcessHeap(), 0, len ) : NULL;
584     DWORD ret  = ExpandEnvironmentStringsA( srcA, dstA, len );
585     if (dstA)
586     {
587         ret = MultiByteToWideChar( CP_ACP, 0, dstA, -1, dst, len );
588         HeapFree( GetProcessHeap(), 0, dstA );
589     }
590     HeapFree( GetProcessHeap(), 0, srcA );
591     return ret;
592 }
593
594
595 /***********************************************************************
596  *           GetDOSEnvironment     (KERNEL.131)
597  *           GetDOSEnvironment16   (KERNEL32.@)
598  */
599 SEGPTR WINAPI GetDOSEnvironment16(void)
600 {
601     return MAKESEGPTR( env_sel, 0 );
602 }
603
604
605 /***********************************************************************
606  *           GetStdHandle    (KERNEL32.@)
607  */
608 HANDLE WINAPI GetStdHandle( DWORD std_handle )
609 {
610     switch(std_handle)
611     {
612         case STD_INPUT_HANDLE:  return current_envdb.hStdin;
613         case STD_OUTPUT_HANDLE: return current_envdb.hStdout;
614         case STD_ERROR_HANDLE:  return current_envdb.hStderr;
615     }
616     SetLastError( ERROR_INVALID_PARAMETER );
617     return INVALID_HANDLE_VALUE;
618 }
619
620
621 /***********************************************************************
622  *           SetStdHandle    (KERNEL32.@)
623  */
624 BOOL WINAPI SetStdHandle( DWORD std_handle, HANDLE handle )
625 {
626     switch(std_handle)
627     {
628         case STD_INPUT_HANDLE:  current_envdb.hStdin = handle;  return TRUE;
629         case STD_OUTPUT_HANDLE: current_envdb.hStdout = handle; return TRUE;
630         case STD_ERROR_HANDLE:  current_envdb.hStderr = handle; return TRUE;
631     }
632     SetLastError( ERROR_INVALID_PARAMETER );
633     return FALSE;
634 }
635
636
637 /***********************************************************************
638  *              GetStartupInfoA         (KERNEL32.@)
639  */
640 VOID WINAPI GetStartupInfoA( LPSTARTUPINFOA info )
641 {
642     *info = current_startupinfo;
643 }
644
645
646 /***********************************************************************
647  *              GetStartupInfoW         (KERNEL32.@)
648  */
649 VOID WINAPI GetStartupInfoW( LPSTARTUPINFOW info )
650 {
651     info->cb              = sizeof(STARTUPINFOW);
652     info->dwX             = current_startupinfo.dwX;
653     info->dwY             = current_startupinfo.dwY;
654     info->dwXSize         = current_startupinfo.dwXSize;
655     info->dwXCountChars   = current_startupinfo.dwXCountChars;
656     info->dwYCountChars   = current_startupinfo.dwYCountChars;
657     info->dwFillAttribute = current_startupinfo.dwFillAttribute;
658     info->dwFlags         = current_startupinfo.dwFlags;
659     info->wShowWindow     = current_startupinfo.wShowWindow;
660     info->cbReserved2     = current_startupinfo.cbReserved2;
661     info->lpReserved2     = current_startupinfo.lpReserved2;
662     info->hStdInput       = current_startupinfo.hStdInput;
663     info->hStdOutput      = current_startupinfo.hStdOutput;
664     info->hStdError       = current_startupinfo.hStdError;
665     info->lpReserved = HEAP_strdupAtoW (GetProcessHeap(), 0, current_startupinfo.lpReserved );
666     info->lpDesktop  = HEAP_strdupAtoW (GetProcessHeap(), 0, current_startupinfo.lpDesktop );
667     info->lpTitle    = HEAP_strdupAtoW (GetProcessHeap(), 0, current_startupinfo.lpTitle );
668 }