Updates will be applied today, at 5:15 pm EDT (UTC-0500). This should not cause an interruption.

SharedForward.h.in 29.1 KB
Newer Older
1 2
/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
   file Copyright.txt or https://cmake.org/licensing#kwsys for details.  */
3 4 5 6 7 8 9 10 11 12
#ifndef @KWSYS_NAMESPACE@_SharedForward_h
#define @KWSYS_NAMESPACE@_SharedForward_h

/*
  This header is used to create a forwarding executable sets up the
  shared library search path and replaces itself with a real
  executable.  This is useful when creating installations on UNIX with
  shared libraries that will run from any install directory.  Typical
  usage:

13 14 15 16 17 18 19
  #if defined(CMAKE_INTDIR)
  # define CONFIG_DIR_PRE CMAKE_INTDIR "/"
  # define CONFIG_DIR_POST "/" CMAKE_INTDIR
  #else
  # define CONFIG_DIR_PRE ""
  # define CONFIG_DIR_POST ""
  #endif
20
  #define @KWSYS_NAMESPACE@_SHARED_FORWARD_DIR_BUILD "/path/to/foo-build/bin"
21
  #define @KWSYS_NAMESPACE@_SHARED_FORWARD_PATH_BUILD "." CONFIG_DIR_POST
22
  #define @KWSYS_NAMESPACE@_SHARED_FORWARD_PATH_INSTALL "../lib/foo-1.2"
23
  #define @KWSYS_NAMESPACE@_SHARED_FORWARD_EXE_BUILD CONFIG_DIR_PRE "foo-real"
24 25
  #define @KWSYS_NAMESPACE@_SHARED_FORWARD_EXE_INSTALL
  "../lib/foo-1.2/foo-real"
26
  #define @KWSYS_NAMESPACE@_SHARED_FORWARD_OPTION_COMMAND "--command"
27 28 29 30 31
  #define @KWSYS_NAMESPACE@_SHARED_FORWARD_OPTION_PRINT "--print"
  #define @KWSYS_NAMESPACE@_SHARED_FORWARD_OPTION_LDD "--ldd"
  #if defined(CMAKE_INTDIR)
  # define @KWSYS_NAMESPACE@_SHARED_FORWARD_CONFIG_NAME CMAKE_INTDIR
  #endif
32 33 34 35 36
  #include <@KWSYS_NAMESPACE@/SharedForward.h>
  int main(int argc, char** argv)
  {
    return @KWSYS_NAMESPACE@_shared_forward_to_real(argc, argv);
  }
37 38 39 40

  Specify search and executable paths relative to the forwarding
  executable location or as full paths.  Include no trailing slash.
  In the case of a multi-configuration build, when CMAKE_INTDIR is
41 42 43 44 45 46 47
  defined, the DIR_BUILD setting should point at the directory above
  the executable (the one containing the per-configuration
  subdirectory specified by CMAKE_INTDIR).  Then PATH_BUILD entries
  and EXE_BUILD should be specified relative to this location and use
  CMAKE_INTDIR as necessary.  In the above example imagine appending
  the PATH_BUILD or EXE_BUILD setting to the DIR_BUILD setting.  The
  result should form a valid path with per-configuration subdirectory.
48 49

  Additional paths may be specified in the PATH_BUILD and PATH_INSTALL
50
  variables by using comma-separated strings.    For example:
51 52

  #define @KWSYS_NAMESPACE@_SHARED_FORWARD_PATH_BUILD \
53
          "." CONFIG_DIR_POST, "/path/to/bar-build" CONFIG_DIR_POST
54 55 56 57 58
  #define @KWSYS_NAMESPACE@_SHARED_FORWARD_PATH_INSTALL \
          "../lib/foo-1.2", "../lib/bar-4.5"

  See the comments below for specific explanations of each macro.
*/
59

60 61 62
/* Disable -Wcast-qual warnings since they are too hard to fix in a
   cross-platform way.  */
#if defined(__clang__) && defined(__has_warning)
63 64 65 66
#if __has_warning("-Wcast-qual")
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wcast-qual"
#endif
67 68
#endif

69
#if defined(__BORLANDC__) && !defined(__cplusplus)
70 71 72
/* Code has no effect; raised by winnt.h in C (not C++) when ignoring an
   unused parameter using "(param)" syntax (i.e. no cast to void).  */
#pragma warn - 8019
73 74
#endif

75 76 77 78 79
/*--------------------------------------------------------------------------*/

/* Full path to the directory in which this executable is built.  Do
   not include a trailing slash.  */
#if !defined(@KWSYS_NAMESPACE@_SHARED_FORWARD_DIR_BUILD)
80
#error "Must define @KWSYS_NAMESPACE@_SHARED_FORWARD_DIR_BUILD"
81 82
#endif
#if !defined(KWSYS_SHARED_FORWARD_DIR_BUILD)
83 84
#define KWSYS_SHARED_FORWARD_DIR_BUILD                                        \
  @KWSYS_NAMESPACE@_SHARED_FORWARD_DIR_BUILD
85 86 87 88
#endif

/* Library search path for build tree.  */
#if !defined(@KWSYS_NAMESPACE@_SHARED_FORWARD_PATH_BUILD)
89
#error "Must define @KWSYS_NAMESPACE@_SHARED_FORWARD_PATH_BUILD"
90 91
#endif
#if !defined(KWSYS_SHARED_FORWARD_PATH_BUILD)
92 93
#define KWSYS_SHARED_FORWARD_PATH_BUILD                                       \
  @KWSYS_NAMESPACE@_SHARED_FORWARD_PATH_BUILD
94 95 96 97
#endif

/* Library search path for install tree.  */
#if !defined(@KWSYS_NAMESPACE@_SHARED_FORWARD_PATH_INSTALL)
98
#error "Must define @KWSYS_NAMESPACE@_SHARED_FORWARD_PATH_INSTALL"
99 100
#endif
#if !defined(KWSYS_SHARED_FORWARD_PATH_INSTALL)
101 102
#define KWSYS_SHARED_FORWARD_PATH_INSTALL                                     \
  @KWSYS_NAMESPACE@_SHARED_FORWARD_PATH_INSTALL
103 104 105 106
#endif

/* The real executable to which to forward in the build tree.  */
#if !defined(@KWSYS_NAMESPACE@_SHARED_FORWARD_EXE_BUILD)
107
#error "Must define @KWSYS_NAMESPACE@_SHARED_FORWARD_EXE_BUILD"
108 109
#endif
#if !defined(KWSYS_SHARED_FORWARD_EXE_BUILD)
110 111
#define KWSYS_SHARED_FORWARD_EXE_BUILD                                        \
  @KWSYS_NAMESPACE@_SHARED_FORWARD_EXE_BUILD
112 113 114 115
#endif

/* The real executable to which to forward in the install tree.  */
#if !defined(@KWSYS_NAMESPACE@_SHARED_FORWARD_EXE_INSTALL)
116
#error "Must define @KWSYS_NAMESPACE@_SHARED_FORWARD_EXE_INSTALL"
117 118
#endif
#if !defined(KWSYS_SHARED_FORWARD_EXE_INSTALL)
119 120
#define KWSYS_SHARED_FORWARD_EXE_INSTALL                                      \
  @KWSYS_NAMESPACE@_SHARED_FORWARD_EXE_INSTALL
121 122
#endif

123 124
/* The configuration name with which this executable was built (Debug/Release).
 */
125
#if defined(@KWSYS_NAMESPACE@_SHARED_FORWARD_CONFIG_NAME)
126 127
#define KWSYS_SHARED_FORWARD_CONFIG_NAME                                      \
  @KWSYS_NAMESPACE@_SHARED_FORWARD_CONFIG_NAME
128
#else
129
#undef KWSYS_SHARED_FORWARD_CONFIG_NAME
130 131
#endif

132 133
/* Create command line option to replace executable.  */
#if defined(@KWSYS_NAMESPACE@_SHARED_FORWARD_OPTION_COMMAND)
134 135 136 137
#if !defined(KWSYS_SHARED_FORWARD_OPTION_COMMAND)
#define KWSYS_SHARED_FORWARD_OPTION_COMMAND                                   \
  @KWSYS_NAMESPACE@_SHARED_FORWARD_OPTION_COMMAND
#endif
138
#else
139
#undef KWSYS_SHARED_FORWARD_OPTION_COMMAND
140 141
#endif

142 143
/* Create command line option to print environment setting and exit.  */
#if defined(@KWSYS_NAMESPACE@_SHARED_FORWARD_OPTION_PRINT)
144 145 146 147
#if !defined(KWSYS_SHARED_FORWARD_OPTION_PRINT)
#define KWSYS_SHARED_FORWARD_OPTION_PRINT                                     \
  @KWSYS_NAMESPACE@_SHARED_FORWARD_OPTION_PRINT
#endif
148
#else
149
#undef KWSYS_SHARED_FORWARD_OPTION_PRINT
150 151 152 153
#endif

/* Create command line option to run ldd or equivalent.  */
#if defined(@KWSYS_NAMESPACE@_SHARED_FORWARD_OPTION_LDD)
154 155 156 157
#if !defined(KWSYS_SHARED_FORWARD_OPTION_LDD)
#define KWSYS_SHARED_FORWARD_OPTION_LDD                                       \
  @KWSYS_NAMESPACE@_SHARED_FORWARD_OPTION_LDD
#endif
158
#else
159
#undef KWSYS_SHARED_FORWARD_OPTION_LDD
160 161 162 163 164
#endif

/*--------------------------------------------------------------------------*/
/* Include needed system headers.  */

165
#include <errno.h>
166
#include <limits.h>
167 168
#include <stddef.h> /* size_t */
#include <stdio.h>
169 170 171
#include <stdlib.h>
#include <string.h>

Brad King's avatar
Brad King committed
172
#if defined(_WIN32) && !defined(__CYGWIN__)
173 174 175 176 177
#include <windows.h>

#include <io.h>
#include <process.h>
#define KWSYS_SHARED_FORWARD_ESCAPE_ARGV /* re-escape argv for execvp */
Brad King's avatar
Brad King committed
178
#else
179 180
#include <sys/stat.h>
#include <unistd.h>
Brad King's avatar
Brad King committed
181 182
#endif

183 184 185 186
/*--------------------------------------------------------------------------*/
/* Configuration for this platform.  */

/* The path separator for this platform.  */
Brad King's avatar
Brad King committed
187
#if defined(_WIN32) && !defined(__CYGWIN__)
188 189
#define KWSYS_SHARED_FORWARD_PATH_SEP ';'
#define KWSYS_SHARED_FORWARD_PATH_SLASH '\\'
Brad King's avatar
Brad King committed
190
#else
191 192
#define KWSYS_SHARED_FORWARD_PATH_SEP ':'
#define KWSYS_SHARED_FORWARD_PATH_SLASH '/'
Brad King's avatar
Brad King committed
193
#endif
194 195 196 197 198 199
static const char kwsys_shared_forward_path_sep[2] = {
  KWSYS_SHARED_FORWARD_PATH_SEP, 0
};
static const char kwsys_shared_forward_path_slash[2] = {
  KWSYS_SHARED_FORWARD_PATH_SLASH, 0
};
200 201 202

/* The maximum length of a file name.  */
#if defined(PATH_MAX)
203
#define KWSYS_SHARED_FORWARD_MAXPATH PATH_MAX
204
#elif defined(MAXPATHLEN)
205
#define KWSYS_SHARED_FORWARD_MAXPATH MAXPATHLEN
206
#else
207
#define KWSYS_SHARED_FORWARD_MAXPATH 16384
208 209 210 211 212 213 214 215
#endif

/* Select the environment variable holding the shared library runtime
   search path for this platform and build configuration.  Also select
   ldd command equivalent.  */

/* Linux */
#if defined(__linux)
216 217 218
#define KWSYS_SHARED_FORWARD_LDD "ldd"
#define KWSYS_SHARED_FORWARD_LDD_N 1
#define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH"
219

Brad King's avatar
Brad King committed
220
/* FreeBSD */
221
#elif defined(__FreeBSD__)
222 223 224
#define KWSYS_SHARED_FORWARD_LDD "ldd"
#define KWSYS_SHARED_FORWARD_LDD_N 1
#define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH"
Brad King's avatar
Brad King committed
225

226 227
/* OpenBSD */
#elif defined(__OpenBSD__)
228 229 230
#define KWSYS_SHARED_FORWARD_LDD "ldd"
#define KWSYS_SHARED_FORWARD_LDD_N 1
#define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH"
231

232
/* OSX */
233
#elif defined(__APPLE__)
234 235 236
#define KWSYS_SHARED_FORWARD_LDD "otool", "-L"
#define KWSYS_SHARED_FORWARD_LDD_N 2
#define KWSYS_SHARED_FORWARD_LDPATH "DYLD_LIBRARY_PATH"
237 238

/* AIX */
239
#elif defined(_AIX)
240 241 242
#define KWSYS_SHARED_FORWARD_LDD "dump", "-H"
#define KWSYS_SHARED_FORWARD_LDD_N 2
#define KWSYS_SHARED_FORWARD_LDPATH "LIBPATH"
243 244

/* SUN */
245
#elif defined(__sun)
246 247 248 249 250 251 252 253
#define KWSYS_SHARED_FORWARD_LDD "ldd"
#define KWSYS_SHARED_FORWARD_LDD_N 1
#include <sys/isa_defs.h>
#if defined(_ILP32)
#define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH"
#elif defined(_LP64)
#define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH_64"
#endif
254 255

/* HP-UX */
256
#elif defined(__hpux)
257 258 259 260 261 262 263
#define KWSYS_SHARED_FORWARD_LDD "chatr"
#define KWSYS_SHARED_FORWARD_LDD_N 1
#if defined(__LP64__)
#define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH"
#else
#define KWSYS_SHARED_FORWARD_LDPATH "SHLIB_PATH"
#endif
264 265

/* SGI MIPS */
266
#elif defined(__sgi) && defined(_MIPS_SIM)
267 268 269 270 271 272 273 274 275
#define KWSYS_SHARED_FORWARD_LDD "ldd"
#define KWSYS_SHARED_FORWARD_LDD_N 1
#if _MIPS_SIM == _ABIO32
#define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH"
#elif _MIPS_SIM == _ABIN32
#define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARYN32_PATH"
#elif _MIPS_SIM == _ABI64
#define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY64_PATH"
#endif
276

277 278
/* Cygwin */
#elif defined(__CYGWIN__)
279 280 281
#define KWSYS_SHARED_FORWARD_LDD "cygcheck" /* TODO: cygwin 1.7 has ldd */
#define KWSYS_SHARED_FORWARD_LDD_N 1
#define KWSYS_SHARED_FORWARD_LDPATH "PATH"
282

Brad King's avatar
Brad King committed
283
/* Windows */
284
#elif defined(_WIN32)
285
#define KWSYS_SHARED_FORWARD_LDPATH "PATH"
Brad King's avatar
Brad King committed
286

287
/* Guess on this unknown system.  */
288
#else
289 290 291
#define KWSYS_SHARED_FORWARD_LDD "ldd"
#define KWSYS_SHARED_FORWARD_LDD_N 1
#define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH"
292 293
#endif

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
#ifdef KWSYS_SHARED_FORWARD_ESCAPE_ARGV
/*--------------------------------------------------------------------------*/
typedef struct kwsys_sf_arg_info_s
{
  const char* arg;
  int size;
  int quote;
} kwsys_sf_arg_info;

/*--------------------------------------------------------------------------*/
static kwsys_sf_arg_info kwsys_sf_get_arg_info(const char* in)
{
  /* Initialize information.  */
  kwsys_sf_arg_info info;

  /* String iterator.  */
  const char* c;

  /* Keep track of how many backslashes have been encountered in a row.  */
  int windows_backslashes = 0;

  /* Start with the length of the original argument, plus one for
     either a terminating null or a separating space.  */
  info.arg = in;
  info.size = (int)strlen(in) + 1;
  info.quote = 0;

  /* Scan the string for characters that require escaping or quoting.  */
322
  for (c = in; *c; ++c) {
323
    /* Check whether this character needs quotes.  */
324
    if (strchr(" \t?'#&<>|^", *c)) {
325
      info.quote = 1;
326
    }
327 328

    /* On Windows only backslashes and double-quotes need escaping.  */
329
    if (*c == '\\') {
330 331
      /* Found a backslash.  It may need to be escaped later.  */
      ++windows_backslashes;
332
    } else if (*c == '"') {
333 334 335 336
      /* Found a double-quote.  We need to escape it and all
         immediately preceding backslashes.  */
      info.size += windows_backslashes + 1;
      windows_backslashes = 0;
337
    } else {
338 339 340 341 342
      /* Found another character.  This eliminates the possibility
         that any immediately preceding backslashes will be
         escaped.  */
      windows_backslashes = 0;
    }
343
  }
344 345

  /* Check whether the argument needs surrounding quotes.  */
346
  if (info.quote) {
347 348 349 350 351
    /* Surrounding quotes are needed.  Allocate space for them.  */
    info.size += 2;

    /* We must escape all ending backslashes when quoting on windows.  */
    info.size += windows_backslashes;
352
  }
353 354 355 356 357 358 359 360 361 362 363 364 365 366

  return info;
}

/*--------------------------------------------------------------------------*/
static char* kwsys_sf_get_arg(kwsys_sf_arg_info info, char* out)
{
  /* String iterator.  */
  const char* c;

  /* Keep track of how many backslashes have been encountered in a row.  */
  int windows_backslashes = 0;

  /* Whether the argument must be quoted.  */
367
  if (info.quote) {
368 369
    /* Add the opening quote for this argument.  */
    *out++ = '"';
370
  }
371 372

  /* Scan the string for characters that require escaping or quoting.  */
373
  for (c = info.arg; *c; ++c) {
374
    /* On Windows only backslashes and double-quotes need escaping.  */
375
    if (*c == '\\') {
376 377
      /* Found a backslash.  It may need to be escaped later.  */
      ++windows_backslashes;
378
    } else if (*c == '"') {
379 380
      /* Found a double-quote.  Escape all immediately preceding
         backslashes.  */
381
      while (windows_backslashes > 0) {
382 383
        --windows_backslashes;
        *out++ = '\\';
384
      }
385 386 387

      /* Add the backslash to escape the double-quote.  */
      *out++ = '\\';
388
    } else {
389 390 391
      /* We encountered a normal character.  This eliminates any
         escaping needed for preceding backslashes.  */
      windows_backslashes = 0;
392
    }
393 394 395

    /* Store this character.  */
    *out++ = *c;
396
  }
397

398
  if (info.quote) {
399
    /* Add enough backslashes to escape any trailing ones.  */
400
    while (windows_backslashes > 0) {
401 402
      --windows_backslashes;
      *out++ = '\\';
403
    }
404 405 406

    /* Add the closing quote for this argument.  */
    *out++ = '"';
407
  }
408 409 410 411 412 413 414 415

  /* Store a terminating null without incrementing.  */
  *out = 0;

  return out;
}
#endif

Brad King's avatar
Brad King committed
416 417 418 419 420 421
/*--------------------------------------------------------------------------*/
/* Function to convert a logical or relative path to a physical full path.  */
static int kwsys_shared_forward_realpath(const char* in_path, char* out_path)
{
#if defined(_WIN32) && !defined(__CYGWIN__)
  /* Implementation for Windows.  */
422 423
  DWORD n =
    GetFullPathNameA(in_path, KWSYS_SHARED_FORWARD_MAXPATH, out_path, 0);
Brad King's avatar
Brad King committed
424 425 426 427 428 429 430
  return n > 0 && n <= KWSYS_SHARED_FORWARD_MAXPATH;
#else
  /* Implementation for UNIX.  */
  return realpath(in_path, out_path) != 0;
#endif
}

431 432 433 434 435
/*--------------------------------------------------------------------------*/
static int kwsys_shared_forward_samepath(const char* file1, const char* file2)
{
#if defined(_WIN32)
  int result = 0;
436
  HANDLE h1 = CreateFileA(file1, GENERIC_READ, FILE_SHARE_READ, NULL,
437
                          OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
438
  HANDLE h2 = CreateFileA(file2, GENERIC_READ, FILE_SHARE_READ, NULL,
439 440
                          OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
  if (h1 != INVALID_HANDLE_VALUE && h2 != INVALID_HANDLE_VALUE) {
441 442 443 444 445 446 447
    BY_HANDLE_FILE_INFORMATION fi1;
    BY_HANDLE_FILE_INFORMATION fi2;
    GetFileInformationByHandle(h1, &fi1);
    GetFileInformationByHandle(h2, &fi2);
    result = (fi1.dwVolumeSerialNumber == fi2.dwVolumeSerialNumber &&
              fi1.nFileIndexHigh == fi2.nFileIndexHigh &&
              fi1.nFileIndexLow == fi2.nFileIndexLow);
448 449 450 451
  }
  CloseHandle(h1);
  CloseHandle(h2);
  return result;
452 453 454 455 456 457 458 459 460
#else
  struct stat fs1, fs2;
  return (stat(file1, &fs1) == 0 && stat(file2, &fs2) == 0 &&
          memcmp(&fs2.st_dev, &fs1.st_dev, sizeof(fs1.st_dev)) == 0 &&
          memcmp(&fs2.st_ino, &fs1.st_ino, sizeof(fs1.st_ino)) == 0 &&
          fs2.st_size == fs1.st_size);
#endif
}

Brad King's avatar
Brad King committed
461 462 463 464 465 466 467
/*--------------------------------------------------------------------------*/
/* Function to report a system error message.  */
static void kwsys_shared_forward_strerror(char* message)
{
#if defined(_WIN32) && !defined(__CYGWIN__)
  /* Implementation for Windows.  */
  DWORD original = GetLastError();
468 469 470 471 472
  DWORD length =
    FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
                   0, original, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                   message, KWSYS_SHARED_FORWARD_MAXPATH, 0);
  if (length < 1 || length > KWSYS_SHARED_FORWARD_MAXPATH) {
Brad King's avatar
Brad King committed
473 474
    /* FormatMessage failed.  Use a default message.  */
    _snprintf(message, KWSYS_SHARED_FORWARD_MAXPATH,
475 476 477
              "Error 0x%X (FormatMessage failed with error 0x%X)", original,
              GetLastError());
  }
Brad King's avatar
Brad King committed
478 479 480 481 482 483 484 485
#else
  /* Implementation for UNIX.  */
  strcpy(message, strerror(errno));
#endif
}

/*--------------------------------------------------------------------------*/
/* Functions to execute a child process.  */
486 487
static void kwsys_shared_forward_execvp(const char* cmd,
                                        char const* const* argv)
Brad King's avatar
Brad King committed
488
{
489 490 491 492
#ifdef KWSYS_SHARED_FORWARD_ESCAPE_ARGV
  /* Count the number of arguments.  */
  int argc = 0;
  {
493 494 495
    char const* const* argvc;
    for (argvc = argv; *argvc; ++argvc, ++argc) {
    }
496 497 498 499
  }

  /* Create the escaped arguments.  */
  {
500 501 502 503 504 505
    char** nargv = (char**)malloc((argc + 1) * sizeof(char*));
    int i;
    for (i = 0; i < argc; ++i) {
      kwsys_sf_arg_info info = kwsys_sf_get_arg_info(argv[i]);
      nargv[i] = (char*)malloc(info.size);
      kwsys_sf_get_arg(info, nargv[i]);
506
    }
507
    nargv[argc] = 0;
508

509 510
    /* Replace the command line to be used.  */
    argv = (char const* const*)nargv;
511 512 513
  }
#endif

514
/* Invoke the child process.  */
Brad King's avatar
Brad King committed
515 516
#if defined(_MSC_VER)
  _execvp(cmd, argv);
517
#elif defined(__MINGW32__) && !defined(__MINGW64__)
Brad King's avatar
Brad King committed
518
  execvp(cmd, argv);
519 520
#else
  execvp(cmd, (char* const*)argv);
Brad King's avatar
Brad King committed
521 522 523
#endif
}

524 525 526 527 528 529 530
/*--------------------------------------------------------------------------*/
/* Function to get the directory containing the given file or directory.  */
static void kwsys_shared_forward_dirname(const char* begin, char* result)
{
  /* Find the location of the last slash.  */
  int last_slash_index = -1;
  const char* end = begin + strlen(begin);
531 532 533
  for (; begin <= end && last_slash_index < 0; --end) {
    if (*end == '/' || *end == '\\') {
      last_slash_index = (int)(end - begin);
534
    }
535
  }
536 537

  /* Handle each case of the index of the last slash.  */
538
  if (last_slash_index < 0) {
539 540
    /* No slashes.  */
    strcpy(result, ".");
541
  } else if (last_slash_index == 0) {
542
    /* Only one leading slash.  */
Brad King's avatar
Brad King committed
543
    strcpy(result, kwsys_shared_forward_path_slash);
544
  }
Brad King's avatar
Brad King committed
545
#if defined(_WIN32)
546
  else if (last_slash_index == 2 && begin[1] == ':') {
Brad King's avatar
Brad King committed
547
    /* Only one leading drive letter and slash.  */
548
    strncpy(result, begin, (size_t)last_slash_index);
549
    result[last_slash_index] = KWSYS_SHARED_FORWARD_PATH_SLASH;
550 551
    result[last_slash_index + 1] = 0;
  }
Brad King's avatar
Brad King committed
552
#endif
553
  else {
554
    /* A non-leading slash.  */
555
    strncpy(result, begin, (size_t)last_slash_index);
556
    result[last_slash_index] = 0;
557
  }
558 559
}

Brad King's avatar
Brad King committed
560 561 562 563 564
/*--------------------------------------------------------------------------*/
/* Function to check if a file exists and is executable.  */
static int kwsys_shared_forward_is_executable(const char* f)
{
#if defined(_MSC_VER)
565
#define KWSYS_SHARED_FORWARD_ACCESS _access
Brad King's avatar
Brad King committed
566
#else
567
#define KWSYS_SHARED_FORWARD_ACCESS access
Brad King's avatar
Brad King committed
568 569
#endif
#if defined(X_OK)
570
#define KWSYS_SHARED_FORWARD_ACCESS_OK X_OK
Brad King's avatar
Brad King committed
571
#else
572
#define KWSYS_SHARED_FORWARD_ACCESS_OK 04
Brad King's avatar
Brad King committed
573
#endif
574
  if (KWSYS_SHARED_FORWARD_ACCESS(f, KWSYS_SHARED_FORWARD_ACCESS_OK) == 0) {
Brad King's avatar
Brad King committed
575
    return 1;
576
  } else {
Brad King's avatar
Brad King committed
577
    return 0;
578
  }
Brad King's avatar
Brad King committed
579 580
}

581 582 583 584 585 586 587
/*--------------------------------------------------------------------------*/
/* Function to locate the executable currently running.  */
static int kwsys_shared_forward_self_path(const char* argv0, char* result)
{
  /* Check whether argv0 has a slash.  */
  int has_slash = 0;
  const char* p = argv0;
588 589
  for (; *p && !has_slash; ++p) {
    if (*p == '/' || *p == '\\') {
590 591
      has_slash = 1;
    }
592
  }
593

594
  if (has_slash) {
595 596 597
    /* There is a slash.  Use the dirname of the given location.  */
    kwsys_shared_forward_dirname(argv0, result);
    return 1;
598
  } else {
599 600 601
    /* There is no slash.  Search the PATH for the executable.  */
    const char* path = getenv("PATH");
    const char* begin = path;
602
    const char* end = begin + (begin ? strlen(begin) : 0);
603
    const char* first = begin;
604
    while (first != end) {
605 606 607 608
      /* Store the end of this path entry.  */
      const char* last;

      /* Skip all path separators.  */
609 610
      for (; *first && *first == KWSYS_SHARED_FORWARD_PATH_SEP; ++first)
        ;
611 612

      /* Find the next separator.  */
613 614 615
      for (last = first; *last && *last != KWSYS_SHARED_FORWARD_PATH_SEP;
           ++last)
        ;
616 617

      /* If we got a non-empty directory, look for the executable there.  */
618
      if (first < last) {
619
        /* Determine the length without trailing slash.  */
620 621
        size_t length = (size_t)(last - first);
        if (*(last - 1) == '/' || *(last - 1) == '\\') {
622
          --length;
623
        }
624 625 626

        /* Construct the name of the executable in this location.  */
        strncpy(result, first, length);
Brad King's avatar
Brad King committed
627
        result[length] = KWSYS_SHARED_FORWARD_PATH_SLASH;
628
        strcpy(result + (length) + 1, argv0);
629

Brad King's avatar
Brad King committed
630
        /* Check if it exists and is executable.  */
631
        if (kwsys_shared_forward_is_executable(result)) {
632 633 634 635
          /* Found it.  */
          result[length] = 0;
          return 1;
        }
636
      }
637 638 639 640

      /* Move to the next directory in the path.  */
      first = last;
    }
641
  }
642 643 644 645 646 647 648 649 650

  /* We could not find the executable.  */
  return 0;
}

/*--------------------------------------------------------------------------*/
/* Function to convert a specified path to a full path.  If it is not
   already full, it is taken relative to the self path.  */
static int kwsys_shared_forward_fullpath(const char* self_path,
651
                                         const char* in_path, char* result,
652 653 654
                                         const char* desc)
{
  /* Check the specified path type.  */
655
  if (in_path[0] == '/') {
656 657
    /* Already a full path.  */
    strcpy(result, in_path);
658
  }
Brad King's avatar
Brad King committed
659
#if defined(_WIN32)
660
  else if (in_path[0] && in_path[1] == ':') {
Brad King's avatar
Brad King committed
661 662
    /* Already a full path.  */
    strcpy(result, in_path);
663
  }
Brad King's avatar
Brad King committed
664
#endif
665
  else {
666 667 668
    /* Relative to self path.  */
    char temp_path[KWSYS_SHARED_FORWARD_MAXPATH];
    strcpy(temp_path, self_path);
Brad King's avatar
Brad King committed
669
    strcat(temp_path, kwsys_shared_forward_path_slash);
670
    strcat(temp_path, in_path);
671 672
    if (!kwsys_shared_forward_realpath(temp_path, result)) {
      if (desc) {
Brad King's avatar
Brad King committed
673 674
        char msgbuf[KWSYS_SHARED_FORWARD_MAXPATH];
        kwsys_shared_forward_strerror(msgbuf);
675 676
        fprintf(stderr, "Error converting %s \"%s\" to real path: %s\n", desc,
                temp_path, msgbuf);
677
      }
678
      return 0;
679
    }
680
  }
681 682 683 684 685 686 687 688 689 690
  return 1;
}

/*--------------------------------------------------------------------------*/
/* Function to compute the library search path and executable name
   based on the self path.  */
static int kwsys_shared_forward_get_settings(const char* self_path,
                                             char* ldpath, char* exe)
{
  /* Possible search paths.  */
691 692 693 694 695
  static const char* search_path_build[] = { KWSYS_SHARED_FORWARD_PATH_BUILD,
                                             0 };
  static const char* search_path_install[] = {
    KWSYS_SHARED_FORWARD_PATH_INSTALL, 0
  };
696 697 698 699 700

  /* Chosen paths.  */
  const char** search_path;
  const char* exe_path;

701
/* Get the real name of the build and self paths.  */
702
#if defined(KWSYS_SHARED_FORWARD_CONFIG_NAME)
703 704
  char build_path[] =
    KWSYS_SHARED_FORWARD_DIR_BUILD "/" KWSYS_SHARED_FORWARD_CONFIG_NAME;
Brad King's avatar
Brad King committed
705 706 707 708 709 710
  char self_path_logical[KWSYS_SHARED_FORWARD_MAXPATH];
#else
  char build_path[] = KWSYS_SHARED_FORWARD_DIR_BUILD;
  const char* self_path_logical = self_path;
#endif
  char build_path_real[KWSYS_SHARED_FORWARD_MAXPATH];
711
  char self_path_real[KWSYS_SHARED_FORWARD_MAXPATH];
712
  if (!kwsys_shared_forward_realpath(self_path, self_path_real)) {
Brad King's avatar
Brad King committed
713 714
    char msgbuf[KWSYS_SHARED_FORWARD_MAXPATH];
    kwsys_shared_forward_strerror(msgbuf);
715
    fprintf(stderr, "Error converting self path \"%s\" to real path: %s\n",
Brad King's avatar
Brad King committed
716
            self_path, msgbuf);
717
    return 0;
718
  }
719 720

  /* Check whether we are running in the build tree or an install tree.  */
721 722
  if (kwsys_shared_forward_realpath(build_path, build_path_real) &&
      kwsys_shared_forward_samepath(self_path_real, build_path_real)) {
723 724
    /* Running in build tree.  Use the build path and exe.  */
    search_path = search_path_build;
Brad King's avatar
Brad King committed
725 726 727
#if defined(_WIN32)
    exe_path = KWSYS_SHARED_FORWARD_EXE_BUILD ".exe";
#else
728
    exe_path = KWSYS_SHARED_FORWARD_EXE_BUILD;
Brad King's avatar
Brad King committed
729 730
#endif

731
#if defined(KWSYS_SHARED_FORWARD_CONFIG_NAME)
Brad King's avatar
Brad King committed
732 733 734
    /* Remove the configuration directory from self_path.  */
    kwsys_shared_forward_dirname(self_path, self_path_logical);
#endif
735
  } else {
736 737
    /* Running in install tree.  Use the install path and exe.  */
    search_path = search_path_install;
Brad King's avatar
Brad King committed
738 739 740
#if defined(_WIN32)
    exe_path = KWSYS_SHARED_FORWARD_EXE_INSTALL ".exe";
#else
741
    exe_path = KWSYS_SHARED_FORWARD_EXE_INSTALL;
Brad King's avatar
Brad King committed
742 743
#endif

744
#if defined(KWSYS_SHARED_FORWARD_CONFIG_NAME)
Brad King's avatar
Brad King committed
745 746 747
    /* Use the original self path directory.  */
    strcpy(self_path_logical, self_path);
#endif
748
  }
749 750 751

  /* Construct the runtime search path.  */
  {
752 753 754 755 756
    const char** dir;
    for (dir = search_path; *dir; ++dir) {
      /* Add separator between path components.  */
      if (dir != search_path) {
        strcat(ldpath, kwsys_shared_forward_path_sep);
757 758
      }

759 760 761 762 763
      /* Add this path component.  */
      if (!kwsys_shared_forward_fullpath(self_path_logical, *dir,
                                         ldpath + strlen(ldpath),
                                         "runtime path entry")) {
        return 0;
764 765 766 767 768
      }
    }
  }

  /* Construct the executable location.  */
769 770
  if (!kwsys_shared_forward_fullpath(self_path_logical, exe_path, exe,
                                     "executable file")) {
771
    return 0;
772
  }
773 774 775 776 777
  return 1;
}

/*--------------------------------------------------------------------------*/
/* Function to print why execution of a command line failed.  */
778
static void kwsys_shared_forward_print_failure(char const* const* argv)
779
{
Brad King's avatar
Brad King committed
780
  char msg[KWSYS_SHARED_FORWARD_MAXPATH];
781
  char const* const* arg = argv;
Brad King's avatar
Brad King committed
782
  kwsys_shared_forward_strerror(msg);
783
  fprintf(stderr, "Error running");
784
  for (; *arg; ++arg) {
785
    fprintf(stderr, " \"%s\"", *arg);
786
  }
787 788 789 790
  fprintf(stderr, ": %s\n", msg);
}

/* Static storage space to store the updated environment variable.  */
791 792
static char kwsys_shared_forward_ldpath[65535] =
  KWSYS_SHARED_FORWARD_LDPATH "=";
793 794 795

/*--------------------------------------------------------------------------*/
/* Main driver function to be called from main.  */
796
static int @KWSYS_NAMESPACE@_shared_forward_to_real(int argc, char** argv_in)
797
{
798
  char const** argv = (char const**)argv_in;
799 800
  /* Get the directory containing this executable.  */
  char self_path[KWSYS_SHARED_FORWARD_MAXPATH];
801
  if (kwsys_shared_forward_self_path(argv[0], self_path)) {
802 803
    /* Found this executable.  Use it to get the library directory.  */
    char exe[KWSYS_SHARED_FORWARD_MAXPATH];
804 805
    if (kwsys_shared_forward_get_settings(self_path,
                                          kwsys_shared_forward_ldpath, exe)) {
806 807
      /* Append the old runtime search path.  */
      const char* old_ldpath = getenv(KWSYS_SHARED_FORWARD_LDPATH);
808
      if (old_ldpath) {
809 810
        strcat(kwsys_shared_forward_ldpath, kwsys_shared_forward_path_sep);
        strcat(kwsys_shared_forward_ldpath, old_ldpath);
811
      }
812 813 814 815

      /* Store the environment variable.  */
      putenv(kwsys_shared_forward_ldpath);

816 817
#if defined(KWSYS_SHARED_FORWARD_OPTION_COMMAND)
      /* Look for the command line replacement option.  */
818 819 820
      if (argc > 1 &&
          strcmp(argv[1], KWSYS_SHARED_FORWARD_OPTION_COMMAND) == 0) {
        if (argc > 2) {
821 822 823 824
          /* Use the command line given.  */
          strcpy(exe, argv[2]);
          argv += 2;
          argc -= 2;
825
        } else {
826 827
          /* The option was not given an executable.  */
          fprintf(stderr, "Option " KWSYS_SHARED_FORWARD_OPTION_COMMAND
828
                          " must be followed by a command line.\n");
829 830
          return 1;
        }
831
      }
832 833
#endif

834 835
#if defined(KWSYS_SHARED_FORWARD_OPTION_PRINT)
      /* Look for the print command line option.  */
836 837
      if (argc > 1 &&
          strcmp(argv[1], KWSYS_SHARED_FORWARD_OPTION_PRINT) == 0) {
838 839 840
        fprintf(stdout, "%s\n", kwsys_shared_forward_ldpath);
        fprintf(stdout, "%s\n", exe);
        return 0;
841
      }
842 843 844 845
#endif

#if defined(KWSYS_SHARED_FORWARD_OPTION_LDD)
      /* Look for the ldd command line option.  */
846 847
      if (argc > 1 && strcmp(argv[1], KWSYS_SHARED_FORWARD_OPTION_LDD) == 0) {
#if defined(KWSYS_SHARED_FORWARD_LDD)
848
        /* Use the named ldd-like executable and arguments.  */
849
        char const* ldd_argv[] = { KWSYS_SHARED_FORWARD_LDD, 0, 0 };
850
        ldd_argv[KWSYS_SHARED_FORWARD_LDD_N] = exe;
Brad King's avatar
Brad King committed
851
        kwsys_shared_forward_execvp(ldd_argv[0], ldd_argv);
852 853

        /* Report why execution failed.  */
Brad King's avatar
Brad King committed
854
        kwsys_shared_forward_print_failure(ldd_argv);
855
        return 1;
856
#else
857 858 859
        /* We have no ldd-like executable available on this platform.  */
        fprintf(stderr, "No ldd-like tool is known to this executable.\n");
        return 1;
860 861
#endif
      }
862 863 864 865
#endif

      /* Replace this process with the real executable.  */
      argv[0] = exe;
866
      kwsys_shared_forward_execvp(argv[0], argv);
867 868

      /* Report why execution failed.  */
Brad King's avatar
Brad King committed
869
      kwsys_shared_forward_print_failure(argv);
870
    } else {
871 872
      /* Could not convert self path to the library directory.  */
    }
873
  } else {
874
    /* Could not find this executable.  */
Brad King's avatar
Brad King committed
875
    fprintf(stderr, "Error locating executable \"%s\".\n", argv[0]);
876
  }
877 878 879 880 881 882 883 884

  /* Avoid unused argument warning.  */
  (void)argc;

  /* Exit with failure.  */
  return 1;
}

885 886
/* Restore warning stack.  */
#if defined(__clang__) && defined(__has_warning)
887 888 889
#if __has_warning("-Wcast-qual")
#pragma clang diagnostic pop
#endif
890 891
#endif

892
#else
893
#error "@KWSYS_NAMESPACE@/SharedForward.h should be included only once."
894
#endif