aboutsummaryrefslogtreecommitdiff
path: root/libiberty/pex-win32.c
blob: 402e07b23a2d0a886e02a54183885a434248e16e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
/* Utilities to execute a program in a subprocess (possibly linked by pipes
   with other subprocesses), and wait for it.  Generic Win32 specialization.
   Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003
   Free Software Foundation, Inc.

This file is part of the libiberty library.
Libiberty is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.

Libiberty is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Library General Public License for more details.

You should have received a copy of the GNU Library General Public
License along with libiberty; see the file COPYING.LIB.  If not,
write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.  */

#include "pex-common.h"

#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <io.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>

static const char *this_program;

#define xclose(fd) do {					\
  if (fd != -1)						\
    {							\
      _close (fd);					\
      fd = -1;						\
    }							\
} while (0)

/* Returns a string containing a text error message, after a Windows
   "system call" failed.  Caller is responsible for deallocating it
   (with LocalFree()).  */
static char *
get_last_error_as_text ()
{
  DWORD last_error = GetLastError();
  LPSTR result;

  /* We assume the error message belongs to 'the system' as opposed
     to some module (which we would have to load, and we don't know
     which one it is).  */
  DWORD flags = (FORMAT_MESSAGE_ALLOCATE_BUFFER
		 | FORMAT_MESSAGE_IGNORE_INSERTS
		 | FORMAT_MESSAGE_FROM_SYSTEM);

  /* Default language.  */
  DWORD langid = MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT);

  /* Yes, you are supposed to cast LPSTR* to LPSTR in the fifth
     argument.  This interface is intrinsically type-unsafe.  */
  FormatMessageA(flags, 0, last_error, langid, (LPSTR) &result, 0, 0);

  return result;
}
  
static char *
argv_to_cmdline(argv)
     char *const *argv;
{
  char *cmdline;
  char *p;
  size_t cmdline_len;
  int i, j;

  cmdline_len = 0;
  for (i = 0; argv[i]; i++)
    {
      /* We quote every last argument.  This simplifies the problem;
	 we need only escape embedded double-quote and backslash
	 characters.  */
      for (j = 0; argv[i][j]; j++)
	if (argv[i][j] == '\\' || argv[i][j] == '"')
	  cmdline_len++;
      cmdline_len += j;
      cmdline_len += 3;  /* for leading and trailing quotes and space */
    }

  cmdline = xmalloc (cmdline_len);
  p = cmdline;
  for (i = 0; argv[i]; i++)
    {
      *p++ = '"';
      for (j = 0; argv[i][j]; j++)
	{
	  if (argv[i][j] == '\\' || argv[i][j] == '"')
	    *p++ = '\\';
	  *p++ = argv[i][j];
	}
      *p++ = '"';
      *p++ = ' ';
    }
  p[-1] = '\0';
  return cmdline;
}

static const char *const
std_suffixes[] = {
  ".com",
  ".exe",
  ".bat",
  ".cmd",
  0
};
static const char *const
no_suffixes[] = {
  "",
  0
};

static char *
find_executable (program, search)
     const char *program;
     int search;
{
  char *full_executable;
  char *e;
  size_t fe_len;
  const char *path = 0;
  const char *const *ext;
  const char *p, *q;
  size_t proglen = strlen (program);
  int has_extension = !!strchr (program, '.');
  int has_slash = (strchr (program, '/') || strchr (program, '\\'));
  HANDLE h;

  if (has_slash)
    search = 0;

  if (search)
    path = getenv ("PATH");
  if (!path)
    path = "";

  fe_len = 0;
  for (p = path; *p; p = q)
    {
      q = p;
      while (*q != ';' && *q != '\0')
	q++;
      if ((size_t)(q - p) > fe_len)
	fe_len = q - p;
      if (*q == ';')
	q++;
    }
  fe_len = fe_len + 1 + proglen + (has_extension ? 1 : 5);
  full_executable = xmalloc (fe_len);

  p = path;
  do
    {
      q = p;
      while (*q != ';' && *q != '\0')
	q++;

      e = full_executable;
      memcpy (e, p, q - p);
      e += (q - p);
      if (q - p)
	*e++ = '\\';
      strcpy (e, program);

      if (*q == ';')
	q++;

      for (e = full_executable; *e; e++)
	if (*e == '/')
	  *e = '\\';

      /* At this point, e points to the terminating NUL character for
         full_executable.  */
      for (ext = has_extension ? no_suffixes : std_suffixes; *ext; ext++)
	{
	  /* Remove any current extension.  */
	  *e = '\0';
	  /* Add the new one.  */
	  strcat (full_executable, *ext);

	  /* Attempt to open this file.  */
	  h = CreateFile (full_executable, GENERIC_READ,
			  FILE_SHARE_READ | FILE_SHARE_WRITE,
			  0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
	  if (h != INVALID_HANDLE_VALUE)
	    goto found;
	}
      p = q;
    }
  while (*p);
  free (full_executable);
  return 0;

 found:
  CloseHandle (h);
  return full_executable;
}

int
pexec (program, argv, search, stdin_fd, stdout_fd, stderr_fd)
     const char *program;
     char *const *argv;
     int search;
     int stdin_fd;
     int stdout_fd;
     int stderr_fd;
{
  char *cmdline = argv_to_cmdline (argv);
  char *executable = find_executable (program, search);
  STARTUPINFO si;
  PROCESS_INFORMATION pinf;
  HANDLE me;

  /* Canonicalize file descriptor arguments.  */
  stdin_fd  = (stdin_fd == STDIN_FILE_NO)   ? -1 : stdin_fd;
  stdout_fd = (stdout_fd == STDOUT_FILE_NO) ? -1 : stdout_fd;
  stderr_fd = (stderr_fd == STDERR_FILE_NO) ? -1 : stderr_fd;

  memset (&si, 0, sizeof si);
  si.cb = sizeof si;
  si.dwFlags = STARTF_USESTDHANDLES;

  me = GetCurrentProcess();

  if (!DuplicateHandle (me,
		        (stdin_fd == -1)
			? GetStdHandle (STD_INPUT_HANDLE)
			: (HANDLE)_get_osfhandle (stdin_fd),
			me, &si.hStdInput,
			0, TRUE, DUPLICATE_SAME_ACCESS))
    goto cleanup;
  if (!DuplicateHandle (me,
			(stdout_fd == -1)
			? GetStdHandle (STD_OUTPUT_HANDLE)
			: (HANDLE)_get_osfhandle (stdout_fd),
			me, &si.hStdOutput,
			0, TRUE, DUPLICATE_SAME_ACCESS))
    goto cleanup;
  if (!DuplicateHandle (me,
			(stderr_fd == -1)
			? GetStdHandle (STD_ERROR_HANDLE)
			: (HANDLE)_get_osfhandle (stderr_fd),
			me, &si.hStdError,
			0, TRUE, DUPLICATE_SAME_ACCESS))
    goto cleanup;

 
  if (!CreateProcess (executable, cmdline,
		     0, 0, TRUE, 0, 0, 0,
		     &si, &pinf))
    goto cleanup;

  CloseHandle (pinf.hProcess);
  CloseHandle (pinf.hThread);
  
 done:
  /* Close file descriptors passed to the child (whether or not we
     managed to create a child).  */
  xclose (stdin_fd);
  xclose (stdout_fd);
  xclose (stderr_fd);

  free (executable);
  free (cmdline);

  return pinf.dwProcessId;

 cleanup:
  {
    /* Error strings on win32 include newlines.  */
    char *errstr = get_last_error_as_text ();
    fprintf (stderr, "%s tried to spawn %s but failed: %s",
	     this_program, program, errstr);
    LocalFree (errstr);
  }
  CloseHandle (si.hStdInput);
  CloseHandle (si.hStdOutput);
  CloseHandle (si.hStdError);
  pinf.dwProcessId = -1;
  goto done;
}

/* MSVCRT's _pipe() creates pipes that can be inherited, which is not
   what we want, so we go directly to CreatePipe().  */
int
pmkpipe (thepipe)
     int thepipe[2];
{
  HANDLE read_port;
  HANDLE write_port;

  if (!CreatePipe (&read_port, &write_port, 0, 0))
    return -1;

  thepipe[0] = _open_osfhandle ((long)read_port, _O_RDONLY);
  thepipe[1] = _open_osfhandle ((long)write_port, _O_WRONLY);
  if (thepipe[0] == -1 || thepipe[1] == -1)
    {
      if (thepipe[0] == -1)
	CloseHandle (read_port);
      else
	_close (thepipe[0]);
      if (thepipe[1] == -1)
	CloseHandle (write_port);
      else
	_close (thepipe[1]);
      return -1;
    }
  return 0;
}

int
pexecute (program, argv, this_pname, temp_base, errmsg_fmt, errmsg_arg, flags)
     const char *program;
     char * const *argv;
     const char *this_pname ATTRIBUTE_UNUSED;
     const char *temp_base ATTRIBUTE_UNUSED;
     char **errmsg_fmt, **errmsg_arg;
     int flags;
{
  /* Pipe waiting from last process, to be used as input for the next
     one.  Value is -1 if no pipe is waiting (i.e. the next command is
     the first of a group).  */
  static int last_pipe_input = -1;

  int pid;
  int pdesc[2];
  int serrno;
  int child_stdin = -2, child_stdout = -2;

  /* If this is the first process, last_pipe_input ought to be -1.  */
  if (flags & PEXECUTE_FIRST)
    if (last_pipe_input != -1)
      abort ();

  child_stdin = last_pipe_input;

  /* If this is the last process, don't do anything with its output
     pipe.  */
  if (flags & PEXECUTE_LAST)
    child_stdout = -1;
  else
    {
      /* Create a pipe to go between this process and the next one in
	 the pipeline.  */
      if (pmkpipe (pdesc))
	{
	  *errmsg_fmt = "pipe";
	  *errmsg_arg = NULL;
	  return -1;
	}
      last_pipe_input = pdesc[READ_PORT];
      child_stdout = pdesc[WRITE_PORT];
    }

  pid = pexec (program, argv, (flags & PEXECUTE_SEARCH),
	       child_stdin, child_stdout, -1);

  serrno = errno;
  xclose (child_stdin);
  xclose (child_stdout);

  /* To prevent a file descriptor leak, close last_pipe_input if pexec
     failed.  */
  if (pid == -1)
    xclose (last_pipe_input);

  errno = serrno;

  if (pid == -1)
    {
      *errmsg_fmt = "spawn";
      *errmsg_arg = NULL;
    }

  return pid;
}

int
pwait (pid, status, flags)
     int pid;
     int *status;
     int flags ATTRIBUTE_UNUSED;
{
  HANDLE proch = OpenProcess (SYNCHRONIZE | PROCESS_QUERY_INFORMATION,
			      FALSE, pid);
  if (proch == 0)
    return -1;
  if (WaitForSingleObject (proch, INFINITE) != WAIT_OBJECT_0)
    {
      CloseHandle (proch);
      return -1;
    }

  GetExitCodeProcess (proch, (DWORD *)status);
  CloseHandle (proch);
  return pid;
}

void
pexec_set_program_name (name)
     const char *name;
{
  this_program = name;
}