[kdbus] KDBUS_ITEM_PAYLOAD_OFF items are (once again) relative to msg header
[platform/upstream/glib.git] / glib / gspawn-win32-helper.c
1 /* gspawn-win32-helper.c - Helper program for process launching on Win32.
2  *
3  *  Copyright 2000 Red Hat, Inc.
4  *  Copyright 2000 Tor Lillqvist
5  *
6  * GLib is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public License as
8  * published by the Free Software Foundation; either version 2 of the
9  * License, or (at your option) any later version.
10  *
11  * GLib is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with GLib; see the file COPYING.LIB.  If not, write
18  * to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19  * Boston, MA 02111-1307, USA.
20  */
21
22 #include "config.h"
23
24 #include <fcntl.h>
25
26 /* For _CrtSetReportMode, we don't want Windows CRT (2005 and later)
27  * to terminate the process if a bad file descriptor is passed into
28  * _get_osfhandle().  This is necessary because we use _get_osfhandle()
29  * to check the validity of the fd before we try to call close() on
30  * it as attempting to close an invalid fd will cause the Windows CRT
31  * to abort() this program internally.
32  *
33  * Please see http://msdn.microsoft.com/zh-tw/library/ks2530z6%28v=vs.80%29.aspx
34  * for an explanation on this.
35  */
36 #if (defined (_MSC_VER) && _MSC_VER >= 1400)
37 #include <crtdbg.h>
38 #endif
39
40 #undef G_LOG_DOMAIN
41 #include "glib.h"
42 #define GSPAWN_HELPER
43 #include "gspawn-win32.c"       /* For shared definitions */
44
45
46 static void
47 write_err_and_exit (gint    fd,
48                     gintptr msg)
49 {
50   gintptr en = errno;
51   
52   write (fd, &msg, sizeof(gintptr));
53   write (fd, &en, sizeof(gintptr));
54   
55   _exit (1);
56 }
57
58 #ifdef __GNUC__
59 #  ifndef _stdcall
60 #    define _stdcall  __attribute__((stdcall))
61 #  endif
62 #endif
63
64 /* We build gspawn-win32-helper.exe as a Windows GUI application
65  * to avoid any temporarily flashing console windows in case
66  * the gspawn function is invoked by a GUI program. Thus, no main()
67  * but a WinMain().
68  */
69
70 /* Info peeked from mingw runtime's source code. __wgetmainargs() is a
71  * function to get the program's argv in wide char format.
72  */
73
74 typedef struct {
75   int newmode;
76 } _startupinfo;
77
78 extern void __wgetmainargs(int *argc,
79                            wchar_t ***wargv,
80                            wchar_t ***wenviron,
81                            int expand_wildcards,
82                            _startupinfo *startupinfo);
83
84 /* Copy of protect_argv that handles wchar_t strings */
85
86 static gint
87 protect_wargv (wchar_t  **wargv,
88                wchar_t ***new_wargv)
89 {
90   gint i;
91   gint argc = 0;
92   
93   while (wargv[argc])
94     ++argc;
95   *new_wargv = g_new (wchar_t *, argc+1);
96
97   /* Quote each argv element if necessary, so that it will get
98    * reconstructed correctly in the C runtime startup code.  Note that
99    * the unquoting algorithm in the C runtime is really weird, and
100    * rather different than what Unix shells do. See stdargv.c in the C
101    * runtime sources (in the Platform SDK, in src/crt).
102    *
103    * Note that an new_wargv[0] constructed by this function should
104    * *not* be passed as the filename argument to a _wspawn* or _wexec*
105    * family function. That argument should be the real file name
106    * without any quoting.
107    */
108   for (i = 0; i < argc; i++)
109     {
110       wchar_t *p = wargv[i];
111       wchar_t *q;
112       gint len = 0;
113       gboolean need_dblquotes = FALSE;
114       while (*p)
115         {
116           if (*p == ' ' || *p == '\t')
117             need_dblquotes = TRUE;
118           else if (*p == '"')
119             len++;
120           else if (*p == '\\')
121             {
122               wchar_t *pp = p;
123               while (*pp && *pp == '\\')
124                 pp++;
125               if (*pp == '"')
126                 len++;
127             }
128           len++;
129           p++;
130         }
131
132       q = (*new_wargv)[i] = g_new (wchar_t, len + need_dblquotes*2 + 1);
133       p = wargv[i];
134
135       if (need_dblquotes)
136         *q++ = '"';
137
138       while (*p)
139         {
140           if (*p == '"')
141             *q++ = '\\';
142           else if (*p == '\\')
143             {
144               wchar_t *pp = p;
145               while (*pp && *pp == '\\')
146                 pp++;
147               if (*pp == '"')
148                 *q++ = '\\';
149             }
150           *q++ = *p;
151           p++;
152         }
153
154       if (need_dblquotes)
155         *q++ = '"';
156       *q++ = '\0';
157     }
158   (*new_wargv)[argc] = NULL;
159
160   return argc;
161 }
162
163 #if (defined (_MSC_VER) && _MSC_VER >= 1400)
164 /*
165  * This is the (empty) invalid parameter handler
166  * that is used for Visual C++ 2005 (and later) builds
167  * so that we can use this instead of the system automatically
168  * aborting the process.
169  *
170  * This is necessary as we use _get_oshandle() to check the validity
171  * of the file descriptors as we close them, so when an invalid file
172  * descriptor is passed into that function as we check on it, we get
173  * -1 as the result, instead of the gspawn helper program aborting.
174  *
175  * Please see http://msdn.microsoft.com/zh-tw/library/ks2530z6%28v=vs.80%29.aspx
176  * for an explanation on this.
177  */
178 void myInvalidParameterHandler(
179    const wchar_t * expression,
180    const wchar_t * function,
181    const wchar_t * file,
182    unsigned int line,
183    uintptr_t pReserved
184 )
185 {
186   return;
187 }
188 #endif
189
190
191 #ifndef HELPER_CONSOLE
192 int _stdcall
193 WinMain (struct HINSTANCE__ *hInstance,
194          struct HINSTANCE__ *hPrevInstance,
195          char               *lpszCmdLine,
196          int                 nCmdShow)
197 #else
198 int
199 main (int ignored_argc, char **ignored_argv)
200 #endif
201 {
202   int child_err_report_fd = -1;
203   int helper_sync_fd = -1;
204   int i;
205   int fd;
206   int mode;
207   gintptr handle;
208   int saved_errno;
209   gintptr no_error = CHILD_NO_ERROR;
210   gint argv_zero_offset = ARG_PROGRAM;
211   wchar_t **new_wargv;
212   int argc;
213   char **argv;
214   wchar_t **wargv, **wenvp;
215   _startupinfo si = { 0 };
216   char c;
217
218 #if (defined (_MSC_VER) && _MSC_VER >= 1400)
219   /* set up our empty invalid parameter handler */
220   _invalid_parameter_handler oldHandler, newHandler;
221   newHandler = myInvalidParameterHandler;
222   oldHandler = _set_invalid_parameter_handler(newHandler);
223
224   /* Disable the message box for assertions. */
225   _CrtSetReportMode(_CRT_ASSERT, 0);
226 #endif
227
228   /* Fetch the wide-char argument vector */
229   __wgetmainargs (&argc, &wargv, &wenvp, 0, &si);
230
231   g_assert (argc >= ARG_COUNT);
232
233   /* Convert unicode wargs to utf8 */
234   argv = g_new(char *, argc + 1);
235   for (i = 0; i < argc; i++)
236     argv[i] = g_utf16_to_utf8(wargv[i], -1, NULL, NULL, NULL);
237   argv[i] = NULL;
238
239   /* argv[ARG_CHILD_ERR_REPORT] is the file descriptor number onto
240    * which write error messages.
241    */
242   child_err_report_fd = atoi (argv[ARG_CHILD_ERR_REPORT]);
243
244   /* Hack to implement G_SPAWN_FILE_AND_ARGV_ZERO. If
245    * argv[ARG_CHILD_ERR_REPORT] is suffixed with a '#' it means we get
246    * the program to run and its argv[0] separately.
247    */
248   if (argv[ARG_CHILD_ERR_REPORT][strlen (argv[ARG_CHILD_ERR_REPORT]) - 1] == '#')
249     argv_zero_offset++;
250
251   /* argv[ARG_HELPER_SYNC] is the file descriptor number we read a
252    * byte that tells us it is OK to exit. We have to wait until the
253    * parent allows us to exit, so that the parent has had time to
254    * duplicate the process handle we sent it. Duplicating a handle
255    * from another process works only if that other process exists.
256    */
257   helper_sync_fd = atoi (argv[ARG_HELPER_SYNC]);
258
259   /* argv[ARG_STDIN..ARG_STDERR] are the file descriptor numbers that
260    * should be dup2'd to 0, 1 and 2. '-' if the corresponding fd
261    * should be left alone, and 'z' if it should be connected to the
262    * bit bucket NUL:.
263    */
264   if (argv[ARG_STDIN][0] == '-')
265     ; /* Nothing */
266   else if (argv[ARG_STDIN][0] == 'z')
267     {
268       fd = open ("NUL:", O_RDONLY);
269       if (fd != 0)
270         {
271           dup2 (fd, 0);
272           close (fd);
273         }
274     }
275   else
276     {
277       fd = atoi (argv[ARG_STDIN]);
278       if (fd != 0)
279         {
280           dup2 (fd, 0);
281           close (fd);
282         }
283     }
284
285   if (argv[ARG_STDOUT][0] == '-')
286     ; /* Nothing */
287   else if (argv[ARG_STDOUT][0] == 'z')
288     {
289       fd = open ("NUL:", O_WRONLY);
290       if (fd != 1)
291         {
292           dup2 (fd, 1);
293           close (fd);
294         }
295     }
296   else
297     {
298       fd = atoi (argv[ARG_STDOUT]);
299       if (fd != 1)
300         {
301           dup2 (fd, 1);
302           close (fd);
303         }
304     }
305
306   if (argv[ARG_STDERR][0] == '-')
307     ; /* Nothing */
308   else if (argv[ARG_STDERR][0] == 'z')
309     {
310       fd = open ("NUL:", O_WRONLY);
311       if (fd != 2)
312         {
313           dup2 (fd, 2);
314           close (fd);
315         }
316     }
317   else
318     {
319       fd = atoi (argv[ARG_STDERR]);
320       if (fd != 2)
321         {
322           dup2 (fd, 2);
323           close (fd);
324         }
325     }
326
327   /* argv[ARG_WORKING_DIRECTORY] is the directory in which to run the
328    * process.  If "-", don't change directory.
329    */
330   if (argv[ARG_WORKING_DIRECTORY][0] == '-' &&
331       argv[ARG_WORKING_DIRECTORY][1] == 0)
332     ; /* Nothing */
333   else if (_wchdir (wargv[ARG_WORKING_DIRECTORY]) < 0)
334     write_err_and_exit (child_err_report_fd, CHILD_CHDIR_FAILED);
335
336   /* argv[ARG_CLOSE_DESCRIPTORS] is "y" if file descriptors from 3
337    *  upwards should be closed
338    */
339   if (argv[ARG_CLOSE_DESCRIPTORS][0] == 'y')
340     for (i = 3; i < 1000; i++)  /* FIXME real limit? */
341       if (i != child_err_report_fd && i != helper_sync_fd)
342         if (_get_osfhandle (i) != -1)
343           close (i);
344
345   /* We don't want our child to inherit the error report and
346    * helper sync fds.
347    */
348   child_err_report_fd = dup_noninherited (child_err_report_fd, _O_WRONLY);
349   helper_sync_fd = dup_noninherited (helper_sync_fd, _O_RDONLY);
350
351   /* argv[ARG_WAIT] is "w" to wait for the program to exit */
352   if (argv[ARG_WAIT][0] == 'w')
353     mode = P_WAIT;
354   else
355     mode = P_NOWAIT;
356
357   /* argv[ARG_USE_PATH] is "y" to use PATH, otherwise not */
358
359   /* argv[ARG_PROGRAM] is executable file to run,
360    * argv[argv_zero_offset]... is its argv. argv_zero_offset equals
361    * ARG_PROGRAM unless G_SPAWN_FILE_AND_ARGV_ZERO was used, in which
362    * case we have a separate executable name and argv[0].
363    */
364
365   /* For the program name passed to spawnv(), don't use the quoted
366    * version.
367    */
368   protect_wargv (wargv + argv_zero_offset, &new_wargv);
369
370   if (argv[ARG_USE_PATH][0] == 'y')
371     handle = _wspawnvp (mode, wargv[ARG_PROGRAM], (const wchar_t **) new_wargv);
372   else
373     handle = _wspawnv (mode, wargv[ARG_PROGRAM], (const wchar_t **) new_wargv);
374
375   saved_errno = errno;
376
377   if (handle == -1 && saved_errno != 0)
378     write_err_and_exit (child_err_report_fd, CHILD_SPAWN_FAILED);
379
380   write (child_err_report_fd, &no_error, sizeof (no_error));
381   write (child_err_report_fd, &handle, sizeof (handle));
382
383   read (helper_sync_fd, &c, 1);
384
385   g_strfreev (argv);
386
387   return 0;
388 }