예제 #1
0
파일: cygw32.c 프로젝트: Wilfred/emacs
static Lisp_Object
conv_filename_from_w32_unicode (const wchar_t* in, int absolute_p)
{
  ssize_t converted_len;
  Lisp_Object converted;
  unsigned flags;
  int count = SPECPDL_INDEX ();

  chdir_to_default_directory ();

  flags = CCP_WIN_W_TO_POSIX;
  if (!absolute_p) {
    flags |= CCP_RELATIVE;
  }

  converted_len = cygwin_conv_path (flags, in, NULL, 0);
  if (converted_len < 1)
    error ("cygwin_conv_path: %s", strerror (errno));

  converted = make_uninit_string (converted_len - 1 /*subtract terminator*/);
  if (cygwin_conv_path (flags, in, SDATA (converted), converted_len))
    error ("cygwin_conv_path: %s", strerror (errno));

  return unbind_to (count, DECODE_FILE (converted));
}
예제 #2
0
    void validate(boost::any& v,
            const std::vector<std::string>& values,
            input_path*, int)
    {
        std::string path
            = boost::program_options::validators::get_single_string(values);

#if defined(BOOST_WINDOWS_PATH)
        cygwin_conv_path_t flags = CCP_POSIX_TO_WIN_A | CCP_RELATIVE;
#elif defined(BOOST_POSIX_PATH)
        cygwin_conv_path_t flags = CCP_WIN_A_TO_POSIX | CCP_RELATIVE;
#else
#    error "Boost filesystem path type doesn't seem to be set."
#endif

        ssize_t size = cygwin_conv_path(flags, path.c_str(), NULL, 0);
        
        if (size < 0) {
            throw boost::program_options::validation_error(
                boost::program_options::validation_error::invalid_option_value);
        }

        boost::scoped_array<char> result(new char[size]);

        if(cygwin_conv_path(flags, path.c_str(), result.get(), size)) {
            throw boost::program_options::validation_error(
                boost::program_options::validation_error::invalid_option_value);
        }

        v = input_path(result.get());
    }
예제 #3
0
파일: cygw32.c 프로젝트: Wilfred/emacs
static Lisp_Object
conv_filename_to_w32_unicode (Lisp_Object in, int absolute_p)
{
  ssize_t converted_len;
  Lisp_Object converted;
  unsigned flags;
  int count = SPECPDL_INDEX ();

  chdir_to_default_directory ();

  flags = CCP_POSIX_TO_WIN_W;
  if (!absolute_p) {
    flags |= CCP_RELATIVE;
  }

  in = ENCODE_FILE (in);

  converted_len = cygwin_conv_path (flags, SDATA (in), NULL, 0);
  if (converted_len < 2)
    error ("cygwin_conv_path: %s", strerror (errno));

  converted = make_uninit_string (converted_len - 1);
  if (cygwin_conv_path (flags, SDATA (in),
                        SDATA (converted), converted_len))
    error ("cygwin_conv_path: %s", strerror (errno));

  return unbind_to (count, converted);
}
예제 #4
0
void WatcherData::updatePaths()
{
    // printf("updating paths...\n");
    {
        std::lock_guard<std::mutex> updateLocker(updateMutex);
        handleToPath.clear();
        pathToHandle.clear();
        pathData.clear();
    }
    for (HANDLE& h : changes) {
        //printf("closing %d\n", h);
        FindCloseChangeNotification(h);
    }
    changes.clear();

    std::lock_guard<std::mutex> locker(changeMutex);
    for(const Path& path : paths) {
#ifdef HAVE_CYGWIN
        const ssize_t len = cygwin_conv_path(CCP_POSIX_TO_WIN_A | CCP_ABSOLUTE, path.constData(), 0, 0);
        //printf("win path size %d\n", len);
        String winPath(len, '\0');
        cygwin_conv_path(CCP_POSIX_TO_WIN_A | CCP_ABSOLUTE, path.constData(), winPath.data(), winPath.size());
        //printf("hello %s\n", winPath.constData());
        const HANDLE h = FindFirstChangeNotification(winPath.constData(), TRUE,
                                                     FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE);
#else
        const HANDLE h = FindFirstChangeNotification(path.constData(), TRUE,
                                                     FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE);
#endif
        if (h == INVALID_HANDLE_VALUE) {
            fprintf(stderr, "Unable to watch: %lu (%s)\n",
                    static_cast<unsigned long>(GetLastError()), path.constData());
        } else {
            changes.push_back(h);

            std::lock_guard<std::mutex> updateLocker(updateMutex);
            handleToPath[h] = path;
            pathToHandle[path] = h;
            PathData& data = pathData[path];
            path.visit([&data](const Path &p) {
                    if (p.isFile()) {
                        data.modified[p] = p.lastModifiedMs();
                        return Path::Continue;
                    }
                    return Path::Recurse;
                });
        }
    }
}
예제 #5
0
static void
win32_add_one_solib (const char *name, CORE_ADDR load_addr)
{
  char buf[MAX_PATH + 1];
  char buf2[MAX_PATH + 1];

#ifdef _WIN32_WCE
  WIN32_FIND_DATA w32_fd;
  WCHAR wname[MAX_PATH + 1];
  mbstowcs (wname, name, MAX_PATH);
  HANDLE h = FindFirstFile (wname, &w32_fd);
#else
  WIN32_FIND_DATAA w32_fd;
  HANDLE h = FindFirstFileA (name, &w32_fd);
#endif

  /* The symbols in a dll are offset by 0x1000, which is the
     offset from 0 of the first byte in an image - because
     of the file header and the section alignment. */
  load_addr += 0x1000;

  if (h == INVALID_HANDLE_VALUE)
    strcpy (buf, name);
  else
    {
      FindClose (h);
      strcpy (buf, name);
#ifndef _WIN32_WCE
      {
	char cwd[MAX_PATH + 1];
	char *p;
	if (GetCurrentDirectoryA (MAX_PATH + 1, cwd))
	  {
	    p = strrchr (buf, '\\');
	    if (p)
	      p[1] = '\0';
	    SetCurrentDirectoryA (buf);
	    GetFullPathNameA (w32_fd.cFileName, MAX_PATH, buf, &p);
	    SetCurrentDirectoryA (cwd);
	  }
      }
#endif
    }

#ifndef _WIN32_WCE
  if (strcasecmp (buf, "ntdll.dll") == 0)
    {
      GetSystemDirectoryA (buf, sizeof (buf));
      strcat (buf, "\\ntdll.dll");
    }
#endif

#ifdef __CYGWIN__
  cygwin_conv_path (CCP_WIN_A_TO_POSIX, buf, buf2, sizeof (buf2));
#else
  strcpy (buf2, buf);
#endif

  loaded_dll (buf2, load_addr);
}
예제 #6
0
파일: sysfwin.c 프로젝트: webushka/reduce
const char *CSLtmpdir()
{
#ifdef __CYGWIN__
    /* First try the Windows path to "/tmp" */
    char *p;
    if (cygwin_conv_path(CCP_POSIX_TO_WIN_A,
                         "/tmp", tempname, sizeof(tempname)) != 0)
    {   DWORD n = GetTempPath(sizeof(tempname), tempname);
        if (n == 0 || n > sizeof(tempname)) return ".";
        tempname[n-1] = 0; /* Remove trailing "\" */
    }
    for (p=tempname; *p!=0; p++)
        if (*p == '\\') *p = '/';
    return tempname;
#else
#if defined WIN32
    DWORD n = GetTempPath(sizeof(tempname), tempname);
    if (n == 0 || n > sizeof(tempname)) return ".";
    tempname[n-1] = 0; /* Remove trailing "\" */
    return tempname;
#else
    return "/tmp";
#endif
#endif
}
예제 #7
0
    ostream::string path_to_stream(fs::path const& path)
    {
        cygwin_conv_path_t flags = CCP_WIN_W_TO_POSIX | CCP_RELATIVE;

        ssize_t size = cygwin_conv_path(flags, path.native().c_str(), NULL, 0);
        
        if (size < 0)
            throw conversion_error("Error converting windows path to cygwin.");

        boost::scoped_array<char> result(new char[size]);

        if(cygwin_conv_path(flags, path.native().c_str(), result.get(), size))
            throw conversion_error("Error converting windows path to cygwin.");

        return std::string(result.get());
    }
예제 #8
0
/**
 * open library (basic open)
 */
int slib_llopen(slib_t *lib) {
#if defined(LNX_EXTLIB)
  lib->handle = dlopen(lib->fullname, RTLD_NOW);
  if (lib->handle == NULL) {
    log_printf("lib: error on loading %s\n%s", lib->name, dlerror());
  }
  return (lib->handle != NULL);
#elif defined(__CYGWIN__)
  char win32Path[1024];
  cygwin_conv_path(CCP_POSIX_TO_WIN_A, lib->fullname, win32Path, sizeof(win32Path));
  lib->handle = LoadLibrary(win32Path);
  if (lib->handle == NULL) {
    log_printf("lib: error on loading %s\n", win32Path);
  }
  return (lib->handle != NULL);
#elif defined(WIN_EXTLIB)
  lib->handle = LoadLibrary(lib->fullname);
  if (lib->handle == NULL) {
    log_printf("lib: error on loading %s\n", lib->name);
  }
  return (lib->handle != NULL);
#else
  return 0;
#endif
}
예제 #9
0
파일: log.c 프로젝트: hanhandan/testdisk
FILE *log_open_default(const char*default_filename, const int mode, int *errsv)
{
  char*filename;
  char *path;
  if(log_handle != NULL)
    return log_handle;
  path = getenv("USERPROFILE");
  if (path == NULL)
    path = getenv("HOMEPATH");
  if(path == NULL)
    return log_open(default_filename, mode, errsv);
  /* Check to avoid buffer overflow may not be 100% bullet proof */
  if(strlen(path)+strlen(default_filename)+2 > 4096)
    return log_open(default_filename, mode, errsv);
  filename=(char*)MALLOC(4096);
#ifdef __CYGWIN__
  cygwin_conv_path(CCP_WIN_A_TO_POSIX, path, filename, 4096);
#else
  strcpy(filename, path);
#endif
  strcat(filename, "/");
  strcat(filename, default_filename);
  log_open(filename, mode, errsv);
  free(filename);
  return log_handle;
}
예제 #10
0
    fs::path command_line_to_path(command_line_string const& path)
    {
        cygwin_conv_path_t flags = CCP_POSIX_TO_WIN_W | CCP_RELATIVE;

        ssize_t size = cygwin_conv_path(flags, path.c_str(), NULL, 0);
        
        if (size < 0)
            throw conversion_error("Error converting cygwin path to windows.");

        boost::scoped_array<char> result(new char[size]);
        void* ptr = result.get();

        if(cygwin_conv_path(flags, path.c_str(), ptr, size))
            throw conversion_error("Error converting cygwin path to windows.");

        return fs::path(static_cast<wchar_t*>(ptr));
    }
예제 #11
0
    fs::path input_to_path(input_string const& path)
    {
        cygwin_conv_path_t flags = CCP_POSIX_TO_WIN_W | CCP_RELATIVE;

        ssize_t size = cygwin_conv_path(flags, path.c_str(), NULL, 0);
        
        if (size < 0)
            throw conversion_error("Error converting cygwin path to windows.");

        // TODO: size is in bytes.
        boost::scoped_array<wchar_t> result(new wchar_t[size]);

        if(cygwin_conv_path(flags, path.c_str(), result.get(), size))
            throw conversion_error("Error converting cygwin path to windows.");

        return fs::path(result.get());
    }
예제 #12
0
파일: srlua.c 프로젝트: Chingliu/srlua
char* getprog() {
  int nsize = _PATH_MAX + 1;
  char* progdir = malloc(nsize * sizeof(char));
  char *lb;
  int n = 0;
#if defined(__CYGWIN__)
  char win_buff[_PATH_MAX + 1];
  GetModuleFileNameA(NULL, win_buff, nsize);
  cygwin_conv_path(CCP_WIN_A_TO_POSIX, win_buff, progdir, nsize);
  n = strlen(progdir);
#elif defined(_WIN32)
  n = GetModuleFileNameA(NULL, progdir, nsize);
#elif defined(__linux__)
  n = readlink("/proc/self/exe", progdir, nsize);
  if (n > 0) progdir[n] = 0;
#elif defined(__sun)
  pid_t pid = getpid();
  char linkname[256];
  sprintf(linkname, "/proc/%d/path/a.out", pid);
  n = readlink(linkname, progdir, nsize);
  if (n > 0) progdir[n] = 0;  
#elif defined(__FreeBSD__)
  int mib[4];
  mib[0] = CTL_KERN;
  mib[1] = KERN_PROC;
  mib[2] = KERN_PROC_PATHNAME;
  mib[3] = -1;
  size_t cb = nsize;
  sysctl(mib, 4, progdir, &cb, NULL, 0);
  n = cb;
#elif defined(__BSD__)
  n = readlink("/proc/curproc/file", progdir, nsize);
  if (n > 0) progdir[n] = 0;
#elif defined(__APPLE__)
  uint32_t nsize_apple = nsize;
  if (_NSGetExecutablePath(progdir, &nsize_apple) == 0)
    n = strlen(progdir);
#else
  // FALLBACK
  // Use 'lsof' ... should work on most UNIX systems (incl. OSX)
  // lsof will list open files, this captures the 1st file listed (usually the executable)
  int pid;
  FILE* fd;
  char cmd[80];
  pid = getpid();

  sprintf(cmd, "lsof -p %d | awk '{if ($5==\"REG\") { print $9 ; exit}}' 2> /dev/null", pid);
  fd = popen(cmd, "r");
  n = fread(progdir, 1, nsize, fd);
  pclose(fd);

  // remove newline
  if (n > 1) progdir[--n] = '\0';
#endif
  if (n == 0 || n == nsize || (lb = strrchr(progdir, (int)LUA_DIRSEP[0])) == NULL)
    return NULL;
  return (progdir);
}
예제 #13
0
/*=======================================================================
     cygwin_path_to_windows
     Converts a unix path to native windows format, reversing directory
     separators, etc. The caller must free the string returned.
========================================================================*/
char *cygwin_path_to_windows (const char *unix_path)
  {
  char *result = malloc (PATH_MAX);
#ifdef WIN64
  cygwin_conv_path (CCP_POSIX_TO_WIN_A, unix_path, result, PATH_MAX -1 );
#else
  cygwin_conv_to_win32_path (unix_path, result);
#endif
  return result;
  }
예제 #14
0
파일: misc.c 프로젝트: Firef0x/burg-new
/* Convert POSIX path to Win32 path,
   remove drive letter, replace backslashes.  */
static char *
get_win32_path (const char *path)
{
  char winpath[PATH_MAX];
  if (cygwin_conv_path (CCP_POSIX_TO_WIN_A, path, winpath, sizeof(winpath)))
    grub_util_error ("cygwin_conv_path() failed");

  int len = strlen (winpath);
  int offs = (len > 2 && winpath[1] == ':' ? 2 : 0);

  int i;
  for (i = offs; i < len; i++)
    if (winpath[i] == '\\')
      winpath[i] = '/';
  return xstrdup (winpath + offs);
}
예제 #15
0
파일: plugin.c 프로젝트: 1100101/inadyn
int plugin_register(ddns_system_t *plugin)
{
	if (!plugin) {
		errno = EINVAL;
		return 1;
	}

	if (!plugin->name) {
		char *dli_fname = NULL;
#ifdef __CYGWIN__
		char posix_path[MAX_PATH];
		char path[MAX_PATH];
		MEMORY_BASIC_INFORMATION mbi;

		VirtualQuery((void*)&plugin, &mbi, sizeof(mbi));
		GetModuleFileNameA((HINSTANCE)mbi.AllocationBase, path, MAX_PATH);
		cygwin_conv_path(CCP_WIN_A_TO_POSIX | CCP_RELATIVE, path, posix_path, MAX_PATH);
		dli_fname = posix_path;
#else
		Dl_info info;

		if (dladdr(plugin, &info))
			dli_fname = (char *)info.dli_fname;
#endif

		if (!dli_fname)
			plugin->name = "unknown";
		else
			plugin->name = (char *)dli_fname;
	}

	/* Already registered? */
	if (plugin_find(plugin->name)) {
		logit(LOG_DEBUG, "... %s already loaded.", plugin->name);
		return 0;
	}

	TAILQ_INSERT_TAIL(&plugins, plugin, link);

	return 0;
}
예제 #16
0
파일: Win32Util.hpp 프로젝트: osch/luced
    static String toWindowsFileName(const String& cygwinFileName)
    {
        MemArray<char> buffer(2000);

        while (true)
        {
            ssize_t rc = cygwin_conv_path(CCP_POSIX_TO_WIN_A|CCP_ABSOLUTE,
                                          cygwinFileName.toCString(),
                                          buffer.getPtr(), 
                                          buffer.getLength());

            if (rc != 0 && errno == ENOSPC) {
                buffer.increaseTo(buffer.getLength() + 1000);
                continue;
            } else if (rc != 0) {
                throw SystemException(String() << "error in call to cygwin_conv_path for '" << cygwinFileName << "': " << strerror(errno));
            } else {
                return String(buffer.getPtr());
            }
        }
    }
예제 #17
0
파일: tclUnixFile.c 프로젝트: smh377/tcl
void
TclpFindExecutable(
    const char *argv0)		/* The value of the application's argv[0]
				 * (native). */
{
    Tcl_Encoding encoding;
#ifdef __CYGWIN__
    int length;
    char buf[PATH_MAX * 2];
    char name[PATH_MAX * TCL_UTF_MAX + 1];
    GetModuleFileNameW(NULL, buf, PATH_MAX);
    cygwin_conv_path(3, buf, name, PATH_MAX);
    length = strlen(name);
    if ((length > 4) && !strcasecmp(name + length - 4, ".exe")) {
	/* Strip '.exe' part. */
	length -= 4;
    }
    encoding = Tcl_GetEncoding(NULL, NULL);
    TclSetObjNameOfExecutable(
	    Tcl_NewStringObj(name, length), encoding);
#else
    const char *name, *p;
    Tcl_StatBuf statBuf;
    Tcl_DString buffer, nameString, cwd, utfName;

    if (argv0 == NULL) {
	return;
    }
    Tcl_DStringInit(&buffer);

    name = argv0;
    for (p = name; *p != '\0'; p++) {
	if (*p == '/') {
	    /*
	     * The name contains a slash, so use the name directly without
	     * doing a path search.
	     */

	    goto gotName;
	}
    }

    p = getenv("PATH");					/* INTL: Native. */
    if (p == NULL) {
	/*
	 * There's no PATH environment variable; use the default that is used
	 * by sh.
	 */

	p = ":/bin:/usr/bin";
    } else if (*p == '\0') {
	/*
	 * An empty path is equivalent to ".".
	 */

	p = "./";
    }

    /*
     * Search through all the directories named in the PATH variable to see if
     * argv[0] is in one of them. If so, use that file name.
     */

    while (1) {
	while (TclIsSpaceProc(*p)) {
	    p++;
	}
	name = p;
	while ((*p != ':') && (*p != 0)) {
	    p++;
	}
	TclDStringClear(&buffer);
	if (p != name) {
	    Tcl_DStringAppend(&buffer, name, p - name);
	    if (p[-1] != '/') {
		TclDStringAppendLiteral(&buffer, "/");
	    }
	}
	name = Tcl_DStringAppend(&buffer, argv0, -1);

	/*
	 * INTL: The following calls to access() and stat() should not be
	 * converted to Tclp routines because they need to operate on native
	 * strings directly.
	 */

	if ((access(name, X_OK) == 0)			/* INTL: Native. */
		&& (TclOSstat(name, &statBuf) == 0)	/* INTL: Native. */
		&& S_ISREG(statBuf.st_mode)) {
	    goto gotName;
	}
	if (*p == '\0') {
	    break;
	} else if (*(p+1) == 0) {
	    p = "./";
	} else {
	    p++;
	}
    }
    TclSetObjNameOfExecutable(Tcl_NewObj(), NULL);
    goto done;

    /*
     * If the name starts with "/" then just store it
     */

  gotName:
#ifdef DJGPP
    if (name[1] == ':')
#else
    if (name[0] == '/')
#endif
    {
	encoding = Tcl_GetEncoding(NULL, NULL);
	Tcl_ExternalToUtfDString(encoding, name, -1, &utfName);
	TclSetObjNameOfExecutable(
		Tcl_NewStringObj(Tcl_DStringValue(&utfName), -1), encoding);
	Tcl_DStringFree(&utfName);
	goto done;
    }

    if (TclpGetCwd(NULL, &cwd) == NULL) {
	TclSetObjNameOfExecutable(Tcl_NewObj(), NULL);
	goto done;
    }

    /*
     * The name is relative to the current working directory. First strip off
     * a leading "./", if any, then add the full path name of the current
     * working directory.
     */

    if ((name[0] == '.') && (name[1] == '/')) {
	name += 2;
    }

    Tcl_DStringInit(&nameString);
    Tcl_DStringAppend(&nameString, name, -1);

    Tcl_DStringFree(&buffer);
    Tcl_UtfToExternalDString(NULL, Tcl_DStringValue(&cwd),
	    Tcl_DStringLength(&cwd), &buffer);
    if (Tcl_DStringValue(&cwd)[Tcl_DStringLength(&cwd) -1] != '/') {
	TclDStringAppendLiteral(&buffer, "/");
    }
    Tcl_DStringFree(&cwd);
    TclDStringAppendDString(&buffer, &nameString);
    Tcl_DStringFree(&nameString);

    encoding = Tcl_GetEncoding(NULL, NULL);
    Tcl_ExternalToUtfDString(encoding, Tcl_DStringValue(&buffer), -1,
	    &utfName);
    TclSetObjNameOfExecutable(
	    Tcl_NewStringObj(Tcl_DStringValue(&utfName), -1), encoding);
    Tcl_DStringFree(&utfName);

  done:
    Tcl_DStringFree(&buffer);
#endif
}
예제 #18
0
static void
remote_fileio_func_rename (char *buf)
{
  CORE_ADDR old_ptr, new_ptr;
  int old_len, new_len;
  char *oldpath, *newpath;
  int ret, of, nf;
  struct stat ost, nst;

  /* 1. Parameter: Ptr to oldpath / length incl. trailing zero */
  if (remote_fileio_extract_ptr_w_len (&buf, &old_ptr, &old_len))
    {
      remote_fileio_ioerror ();
      return;
    }
  
  /* 2. Parameter: Ptr to newpath / length incl. trailing zero */
  if (remote_fileio_extract_ptr_w_len (&buf, &new_ptr, &new_len))
    {
      remote_fileio_ioerror ();
      return;
    }
  
  /* Request oldpath using 'm' packet */
  oldpath = alloca (old_len);
  if (target_read_memory (old_ptr, (gdb_byte *) oldpath, old_len) != 0)
    {
      remote_fileio_ioerror ();
      return;
    }
  
  /* Request newpath using 'm' packet */
  newpath = alloca (new_len);
  if (target_read_memory (new_ptr, (gdb_byte *) newpath, new_len) != 0)
    {
      remote_fileio_ioerror ();
      return;
    }
  
  /* Only operate on regular files and directories.  */
  of = stat (oldpath, &ost);
  nf = stat (newpath, &nst);
  if ((!of && !S_ISREG (ost.st_mode) && !S_ISDIR (ost.st_mode))
      || (!nf && !S_ISREG (nst.st_mode) && !S_ISDIR (nst.st_mode)))
    {
      remote_fileio_reply (-1, FILEIO_EACCES);
      return;
    }

  remote_fio_no_longjmp = 1;
  ret = rename (oldpath, newpath);

  if (ret == -1)
    {
      /* Special case: newpath is a non-empty directory.  Some systems
         return ENOTEMPTY, some return EEXIST.  We coerce that to be
	 always EEXIST.  */
      if (errno == ENOTEMPTY)
        errno = EEXIST;
#ifdef __CYGWIN__
      /* Workaround some Cygwin problems with correct errnos.  */
      if (errno == EACCES)
        {
	  if (!of && !nf && S_ISDIR (nst.st_mode))
	    {
	      if (S_ISREG (ost.st_mode))
		errno = EISDIR;
	      else
		{
		  char oldfullpath[PATH_MAX];
		  char newfullpath[PATH_MAX];
		  int len;

		  cygwin_conv_path (CCP_WIN_A_TO_POSIX, oldpath, oldfullpath,
				    PATH_MAX);
		  cygwin_conv_path (CCP_WIN_A_TO_POSIX, newpath, newfullpath,
				    PATH_MAX);
		  len = strlen (oldfullpath);
		  if (IS_DIR_SEPARATOR (newfullpath[len])
		      && !filename_ncmp (oldfullpath, newfullpath, len))
		    errno = EINVAL;
		  else
		    errno = EEXIST;
		}
	    }
	}
#endif

      remote_fileio_return_errno (-1);
    }
  else
    remote_fileio_return_success (ret);
}
static char *
pgwin32_CommandLine(bool registration)
{
	static char cmdLine[MAXPGPATH];
	int			ret;

#ifdef __CYGWIN__
	char		buf[MAXPGPATH];
#endif

	if (registration)
	{
		ret = find_my_exec(argv0, cmdLine);
		if (ret != 0)
		{
			write_stderr(_("%s: could not find own program executable\n"), progname);
			exit(1);
		}
	}
	else
	{
		ret = find_other_exec(argv0, "postgres", PG_BACKEND_VERSIONSTR,
							  cmdLine);
		if (ret != 0)
		{
			write_stderr(_("%s: could not find postgres program executable\n"), progname);
			exit(1);
		}
	}

#ifdef __CYGWIN__
	/* need to convert to windows path */
#if CYGWIN_VERSION_DLL_MAJOR >= 1007
	cygwin_conv_path(CCP_POSIX_TO_WIN_A, cmdLine, buf, sizeof(buf));
#else
	cygwin_conv_to_full_win32_path(cmdLine, buf);
#endif
	strcpy(cmdLine, buf);
#endif

	if (registration)
	{
		if (pg_strcasecmp(cmdLine + strlen(cmdLine) - 4, ".exe"))
		{
			/* If commandline does not end in .exe, append it */
			strcat(cmdLine, ".exe");
		}
		strcat(cmdLine, " runservice -N \"");
		strcat(cmdLine, register_servicename);
		strcat(cmdLine, "\"");
	}

	if (pg_data)
	{
		strcat(cmdLine, " -D \"");
		strcat(cmdLine, pg_data);
		strcat(cmdLine, "\"");
	}

	if (registration && do_wait)
		strcat(cmdLine, " -w");

	if (registration && wait_seconds != DEFAULT_WAIT)
		/* concatenate */
		sprintf(cmdLine + strlen(cmdLine), " -t %d", wait_seconds);

	if (post_opts)
	{
		strcat(cmdLine, " ");
		if (registration)
			strcat(cmdLine, " -o \"");
		strcat(cmdLine, post_opts);
		if (registration)
			strcat(cmdLine, "\"");
	}

	return cmdLine;
}
예제 #20
0
void
ruby_init_loadpath_safe(int safe_level, const char* szRoot)
{
    VALUE load_path;
    ID id_initial_load_path_mark;
    extern const char ruby_initial_load_paths[];
    const char *paths = ruby_initial_load_paths;
#if defined LOAD_RELATIVE
# if defined HAVE_DLADDR || (defined __CYGWIN__ && defined CCP_WIN_A_TO_POSIX)
#   define VARIABLE_LIBPATH 1
# else
#   define VARIABLE_LIBPATH 0
# endif
# if VARIABLE_LIBPATH
    char *libpath;
    VALUE sopath;
# else
    char libpath[MAXPATHLEN + 1];
# endif
    size_t baselen;
    char *p;
	if ( szRoot )
		strncpy(libpath, szRoot, sizeof(libpath) - 1);
	else
	{
#if defined _WIN32 || defined __CYGWIN__
# if VARIABLE_LIBPATH
    sopath = rb_str_new(0, MAXPATHLEN);
    libpath = RSTRING_PTR(sopath);
    GetModuleFileName(libruby, libpath, MAXPATHLEN);
# else
    GetModuleFileName(libruby, libpath, sizeof libpath);
# endif
#elif defined(__EMX__)
    _execname(libpath, sizeof(libpath) - 1);
#elif defined(HAVE_DLADDR)
    Dl_info dli;
    if (dladdr((void *)(VALUE)expand_include_path, &dli)) {
	VALUE fname = rb_str_new_cstr(dli.dli_fname);
	sopath = rb_file_absolute_path(fname, Qnil);
	rb_str_resize(fname, 0);
    }
    else {
	sopath = rb_str_new(0, 0);
    }
    libpath = RSTRING_PTR(sopath);
#endif
    }
//RHO

#if !VARIABLE_LIBPATH
    libpath[sizeof(libpath) - 1] = '\0';
#endif
#if defined DOSISH
    translit_char(libpath, '\\', '/');
#elif defined __CYGWIN__
    {
# if VARIABLE_LIBPATH
	const int win_to_posix = CCP_WIN_A_TO_POSIX | CCP_RELATIVE;
	size_t newsize = cygwin_conv_path(win_to_posix, libpath, 0, 0);
	if (newsize > 0) {
	    VALUE rubylib = rb_str_new(0, newsize);
	    p = RSTRING_PTR(rubylib);
	    if (cygwin_conv_path(win_to_posix, libpath, p, newsize) == 0) {
		rb_str_resize(sopath, 0);
		sopath = rubylib;
		libpath = p;
	    }
	}
# else
	char rubylib[FILENAME_MAX];
	cygwin_conv_to_posix_path(libpath, rubylib);
	strncpy(libpath, rubylib, sizeof(libpath));
# endif
    }
#endif
    p = strrchr(libpath, '/');
    if (p) {
	*p = 0;
	if (p - libpath > 3 && !(STRCASECMP(p - 4, "/bin") && strcmp(p - 4, "/lib"))) {
	    p -= 4;
	    *p = 0;
	}
    }
#if !VARIABLE_LIBPATH
    else {
	strlcpy(libpath, ".", sizeof(libpath));
	p = libpath + 1;
    }
    baselen = p - libpath;
#define PREFIX_PATH() rb_str_new(libpath, baselen)
#else
    baselen = p - libpath;
    rb_str_set_len(sopath, baselen);
    libpath = RSTRING_PTR(sopath);
#define PREFIX_PATH() sopath
#endif

#define BASEPATH() rb_str_buf_cat(rb_str_buf_new(baselen+len), libpath, baselen)

#define RUBY_RELATIVE(path, len) rb_str_buf_cat(BASEPATH(), path, len)
#else
    static const char exec_prefix[] = RUBY_EXEC_PREFIX;
#define RUBY_RELATIVE(path, len) rubylib_mangled_path(path, len)
#define PREFIX_PATH() RUBY_RELATIVE(exec_prefix, sizeof(exec_prefix)-1)
#endif
    load_path = GET_VM()->load_path;

    if (safe_level == 0) {
	ruby_push_include(getenv("RUBYLIB"), identical_path);
    }

    id_initial_load_path_mark = rb_intern_const("@gem_prelude_index");
    while (*paths) {
	size_t len = strlen(paths);
	VALUE path = RUBY_RELATIVE(paths, len);
	rb_ivar_set(path, id_initial_load_path_mark, path);
	rb_ary_push(load_path, path);
	paths += len + 1;
    }

    rb_const_set(rb_cObject, rb_intern_const("TMP_RUBY_PREFIX"), rb_obj_freeze(PREFIX_PATH()));
}
예제 #21
0
/* A function called through the vtable to open a module with this
   loader.  Returns an opaque representation of the newly opened
   module for processing with this loader's other vtable functions.  */
static lt_module
vm_open (lt_user_data LT__UNUSED loader_data, const char *filename,
         lt_dladvise LT__UNUSED advise)
{
  lt_module	module	   = 0;
  char		*ext;
  char		wpath[MAX_PATH];
  size_t	len;

  if (!filename)
    {
      /* Get the name of main module */
      *wpath = 0;
      GetModuleFileName (NULL, wpath, sizeof (wpath));
      filename = wpath;
    }
  else
    {
      len = LT_STRLEN (filename);

      if (len >= MAX_PATH)
        {
	  LT__SETERROR (CANNOT_OPEN);
	  return 0;
	}

#if HAVE_DECL_CYGWIN_CONV_PATH
      if (cygwin_conv_path (CCP_POSIX_TO_WIN_A, filename, wpath, MAX_PATH))
	{
	  LT__SETERROR (CANNOT_OPEN);
	  return 0;
	}
      len = 0;
#elif defined __CYGWIN__
      cygwin_conv_to_full_win32_path (filename, wpath);
      len = 0;
#else
      strcpy(wpath, filename);
#endif

      ext = strrchr (wpath, '.');
      if (!ext)
	{
	  /* Append a '.' to stop Windows from adding an
	     implicit '.dll' extension. */
	  if (!len)
	    len = strlen (wpath);

	  if (len + 1 >= MAX_PATH)
	    {
	      LT__SETERROR (CANNOT_OPEN);
	      return 0;
	    }

	  wpath[len] = '.';
	  wpath[len+1] = '\0';
	}
    }

  {
    /* Silence dialog from LoadLibrary on some failures. */
    DWORD errormode = getthreaderrormode ();
    DWORD last_error;

    setthreaderrormode (errormode | SEM_FAILCRITICALERRORS, NULL);

    module = LoadLibrary (wpath);

    /* Restore the error mode. */
    last_error = GetLastError ();
    setthreaderrormode (errormode, NULL);
    SetLastError (last_error);
  }

  /* libltdl expects this function to fail if it is unable
     to physically load the library.  Sadly, LoadLibrary
     will search the loaded libraries for a match and return
     one of them if the path search load fails.

     We check whether LoadLibrary is returning a handle to
     an already loaded module, and simulate failure if we
     find one. */
  {
    lt_dlhandle cur = 0;

    while ((cur = lt_dlhandle_iterate (iface_id, cur)))
      {
        if (!cur->module)
          {
            cur = 0;
            break;
          }

        if (cur->module == module)
          {
            break;
          }
      }

    if (!module)
      LOADLIB_SETERROR (CANNOT_OPEN);
    else if (cur)
      {
        LT__SETERROR (CANNOT_OPEN);
        module = 0;
      }
  }

  return module;
}
예제 #22
0
void
ruby_init_loadpath_safe(int safe_level)
{
    VALUE load_path;
    ID id_initial_load_path_mark;
    extern const char ruby_initial_load_paths[];
    const char *paths = ruby_initial_load_paths;
#if defined LOAD_RELATIVE
# if defined HAVE_DLADDR || defined HAVE_CYGWIN_CONV_PATH
#   define VARIABLE_LIBPATH 1
# else
#   define VARIABLE_LIBPATH 0
# endif
# if VARIABLE_LIBPATH
    char *libpath;
    VALUE sopath;
# else
    char libpath[MAXPATHLEN + 1];
# endif
    size_t baselen;
    char *p;

#if defined _WIN32 || defined __CYGWIN__
# if VARIABLE_LIBPATH
    sopath = rb_str_new(0, MAXPATHLEN);
    libpath = RSTRING_PTR(sopath);
    GetModuleFileName(libruby, libpath, MAXPATHLEN);
# else
    GetModuleFileName(libruby, libpath, sizeof libpath);
# endif
#elif defined(__EMX__)
    _execname(libpath, sizeof(libpath) - 1);
#elif defined(HAVE_DLADDR)
    Dl_info dli;
    if (dladdr((void *)(VALUE)expand_include_path, &dli)) {
	char fbuf[MAXPATHLEN];
	char *f = dln_find_file_r(dli.dli_fname, getenv(PATH_ENV), fbuf, sizeof(fbuf));
	VALUE fname = rb_str_new_cstr(f ? f : dli.dli_fname);
	rb_str_freeze(fname);
	sopath = rb_realpath_internal(Qnil, fname, 1);
    }
    else {
	sopath = rb_str_new(0, 0);
    }
    libpath = RSTRING_PTR(sopath);
#endif

#if !VARIABLE_LIBPATH
    libpath[sizeof(libpath) - 1] = '\0';
#endif
#if defined DOSISH
    translit_char(libpath, '\\', '/');
#elif defined __CYGWIN__
    {
# if VARIABLE_LIBPATH
	const int win_to_posix = CCP_WIN_A_TO_POSIX | CCP_RELATIVE;
	size_t newsize = cygwin_conv_path(win_to_posix, libpath, 0, 0);
	if (newsize > 0) {
	    VALUE rubylib = rb_str_new(0, newsize);
	    p = RSTRING_PTR(rubylib);
	    if (cygwin_conv_path(win_to_posix, libpath, p, newsize) == 0) {
		rb_str_resize(sopath, 0);
		sopath = rubylib;
		libpath = p;
	    }
	}
# else
	char rubylib[FILENAME_MAX];
	cygwin_conv_to_posix_path(libpath, rubylib);
	strncpy(libpath, rubylib, sizeof(libpath));
# endif
    }
#endif
    p = strrchr(libpath, '/');
    if (p) {
	static const char bindir[] = "/bin";
#ifdef LIBDIR_BASENAME
	static const char libdir[] = "/"LIBDIR_BASENAME;
#else
	static const char libdir[] = "/lib";
#endif
	const ptrdiff_t bindir_len = (ptrdiff_t)sizeof(bindir) - 1;
	const ptrdiff_t libdir_len = (ptrdiff_t)sizeof(libdir) - 1;
	*p = 0;
	if (p - libpath >= bindir_len && !STRCASECMP(p - bindir_len, bindir)) {
	    p -= bindir_len;
	    *p = 0;
	}
	else if (p - libpath >= libdir_len && !STRCASECMP(p - libdir_len, libdir)) {
	    p -= libdir_len;
	    *p = 0;
	}
    }
#if !VARIABLE_LIBPATH
    else {
	strlcpy(libpath, ".", sizeof(libpath));
	p = libpath + 1;
    }
    baselen = p - libpath;
#define PREFIX_PATH() rb_str_new(libpath, baselen)
#else
    baselen = p - libpath;
    rb_str_resize(sopath, baselen);
    libpath = RSTRING_PTR(sopath);
#define PREFIX_PATH() sopath
#endif

#define BASEPATH() rb_str_buf_cat(rb_str_buf_new(baselen+len), libpath, baselen)

#define RUBY_RELATIVE(path, len) rb_str_buf_cat(BASEPATH(), (path), (len))
#else
    static const char exec_prefix[] = RUBY_EXEC_PREFIX;
#define RUBY_RELATIVE(path, len) rubylib_mangled_path((path), (len))
#define PREFIX_PATH() RUBY_RELATIVE(exec_prefix, sizeof(exec_prefix)-1)
#endif
    load_path = GET_VM()->load_path;

    if (safe_level == 0) {
#ifdef MANGLED_PATH
	rubylib_mangled_path("", 0);
#endif
	ruby_push_include(getenv("RUBYLIB"), identical_path);
    }

    id_initial_load_path_mark = rb_intern_const("@gem_prelude_index");
    while (*paths) {
	size_t len = strlen(paths);
	VALUE path = RUBY_RELATIVE(paths, len);
	rb_ivar_set(path, id_initial_load_path_mark, path);
	rb_ary_push(load_path, path);
	paths += len + 1;
    }

    rb_const_set(rb_cObject, rb_intern_const("TMP_RUBY_PREFIX"), rb_obj_freeze(PREFIX_PATH()));
}
예제 #23
0
파일: main.c 프로젝트: smx-smx/epk2extract
int main(int argc, char *argv[]) {
	printf("\nLG Electronics digital TV firmware package (EPK) extractor 3.5 by sirius (http://openlgtv.org.ru)\n\n");

	if (argc < 2) {
		printf("Thanks to xeros, tbage, jenya, Arno1, rtokarev, cronix, lprot and all other guys from openlgtv project for their kind assistance.\n\n");
		printf("Usage: epk2extract [-options] FILENAME\n\n");
		printf("Options:\n");
		printf("  -c : extract to current directory instead of source file directory\n");
		#ifdef __CYGWIN__
			puts("Press any key to continue...");
			getch();
		#endif
		exit(1);
	}

	current_dir = getcwd(NULL, 0);
	printf("Current directory: %s\n", current_dir);
	readlink("/proc/self/exe", exe_dir, 1024);
	config_opts.config_dir = dirname(exe_dir);
	config_opts.dest_dir = NULL;

	int opt;
	while ((opt = getopt(argc, argv, "c")) != -1) {
		switch (opt) {
		case 'c': {
			config_opts.dest_dir = current_dir;
			break;
		}
		case ':': {
			printf("Option `%c' needs a value\n\n", optopt);
			exit(1);
			break;
		}
		case '?': {
			printf("Unknown option: `%c'\n\n", optopt);
			exit(1);
		}
		}
	}

	#ifdef __CYGWIN__
		char posix[PATH_MAX];
		cygwin_conv_path(CCP_WIN_A_TO_POSIX, argv[optind], posix, PATH_MAX);
		char *input_file = posix;
	#else
		char *input_file = argv[optind];
	#endif
	printf("Input file: %s\n", input_file);
	if (config_opts.dest_dir == NULL) config_opts.dest_dir = dirname(strdup(input_file));
	printf("Destination directory: %s\n", config_opts.dest_dir);
	int exit_code = handle_file(input_file, &config_opts);
	if(exit_code == EXIT_FAILURE) {
		printf("Unsupported input file format: %s\n\n", input_file);
		#ifdef __CYGWIN__
			puts("Press any key to continue...");
			getch();
		#endif
		return exit_code;
	}
	printf("\nExtraction is finished.\n\n");
	#ifdef __CYGWIN__
		puts("Press any key to continue...");
		getch();
	#endif
	return exit_code;
}
예제 #24
0
const wxChar* wxGetHomeDir(wxString *pstr)
{
    wxString& strDir = *pstr;

    // first branch is for Cygwin
#if defined(__UNIX__) && !defined(__WINE__)
    const wxChar *szHome = wxGetenv(wxT("HOME"));
    if ( szHome == NULL ) {
      // we're homeless...
      wxLogWarning(_("can't find user's HOME, using current directory."));
      strDir = wxT(".");
    }
    else
       strDir = szHome;

    // add a trailing slash if needed
    if ( strDir.Last() != wxT('/') )
      strDir << wxT('/');

    #ifdef __CYGWIN__
        // Cygwin returns unix type path but that does not work well
        static wxChar windowsPath[MAX_PATH];
        #if CYGWIN_VERSION_DLL_MAJOR >= 1007
            cygwin_conv_path(CCP_POSIX_TO_WIN_W, strDir, windowsPath, MAX_PATH);
        #else
            cygwin_conv_to_full_win32_path(strDir, windowsPath);
        #endif
        strDir = windowsPath;
    #endif
#elif defined(__WXWINCE__)
    strDir = wxT("\\");
#else
    strDir.clear();

    // If we have a valid HOME directory, as is used on many machines that
    // have unix utilities on them, we should use that.
    const wxChar *szHome = wxGetenv(wxT("HOME"));

    if ( szHome != NULL )
    {
        strDir = szHome;
    }
    else // no HOME, try HOMEDRIVE/PATH
    {
        szHome = wxGetenv(wxT("HOMEDRIVE"));
        if ( szHome != NULL )
            strDir << szHome;
        szHome = wxGetenv(wxT("HOMEPATH"));

        if ( szHome != NULL )
        {
            strDir << szHome;

            // the idea is that under NT these variables have default values
            // of "%systemdrive%:" and "\\". As we don't want to create our
            // config files in the root directory of the system drive, we will
            // create it in our program's dir. However, if the user took care
            // to set HOMEPATH to something other than "\\", we suppose that he
            // knows what he is doing and use the supplied value.
            if ( wxStrcmp(szHome, wxT("\\")) == 0 )
                strDir.clear();
        }
    }

    if ( strDir.empty() )
    {
        // If we have a valid USERPROFILE directory, as is the case in
        // Windows NT, 2000 and XP, we should use that as our home directory.
        szHome = wxGetenv(wxT("USERPROFILE"));

        if ( szHome != NULL )
            strDir = szHome;
    }

    if ( !strDir.empty() )
    {
        // sometimes the value of HOME may be "%USERPROFILE%", so reexpand the
        // value once again, it shouldn't hurt anyhow
        strDir = wxExpandEnvVars(strDir);
    }
    else // fall back to the program directory
    {
        // extract the directory component of the program file name
        wxFileName::SplitPath(wxGetFullModuleName(), &strDir, NULL, NULL);
    }
#endif  // UNIX/Win

    return strDir.c_str();
}
예제 #25
0
//
// The returned pointer should be freed with free unless,
// as it turns out, it is equal to the input pointer.
//
char *
arg_heuristic_with_exclusions (char const * const arg, char const * exclusions, size_t exclusions_count)
{
  int arglen = (arg ? strlen (arg): 0);
  
  if (arglen == 0) {
      char *retpath = (char *)malloc (sizeof (char));
      memset (retpath, 0, sizeof (char));
      return retpath;
  }
  
  debug_printf("Input value: (%s)", arg);
  for (size_t excl = 0; excl < exclusions_count; ++excl) {
      if ( strstr (arg, exclusions) == arg )
          return (char*)arg;
      exclusions += strlen (exclusions) + 1;
  }

  //
  // copy of the path string that we can overwrite
  //
  char *spath = (char *)alloca (arglen + 1);
  memcpy (spath, arg, arglen + 1);

  char * sspath;

  //
  // retpath contains the converted path string to be returned
  //
  char *retpath = (char *)malloc(((MAX_PATH - arglen) > 0) ? MAX_PATH : arglen + MAX_PATH);
  memset (retpath, 0, MAX_PATH);
  int retpath_len = 0;
  int retpath_buflen = MAX_PATH;

#define retpathcat(retstr) \
  retpath_len += strlen(retstr); \
  if (retpath_buflen <= retpath_len) \
    { \
      retpath_buflen = ((retpath_buflen * 2 <= retpath_len) ? \
    retpath_len + 1 : retpath_buflen * 2); \
      retpath = (char *)realloc (retpath, retpath_buflen); \
    } \
  strcat (retpath, retstr);

#define retpathcpy(retstr) \
  retpath_len = strlen (retstr); \
  *retpath = '\0'; \
  if (retpath_buflen <= retpath_len ) \
    { \
      retpath_buflen = ((retpath_buflen * 2 <= retpath_len) ? \
    retpath_len + 1 : retpath_buflen * 2); \
      retpath = (char *)realloc (retpath, retpath_buflen); \
    } \
  strcpy (retpath, retstr);

  //
  // Just return win32 paths and path lists.
  //
  if (isabswinpath (arg) || (strchr (arg, ';') > 0)) {
      debug_printf("returning Win32 absolute path: %s", arg);
      return ((char *)arg);
  }
  //
  // Multiple forward slashes are treated special,
  // Remove one and return for the form of //foo or ///bar
  // but just return for the form of //server/share.
  //
  else if (arg[0] == '/' && arg[1] == '/') {
      int tidx = 2;
      while (spath[tidx] && spath[tidx] == '/')
          tidx++;
      if (strchr (&spath[tidx], '/')) {
          retpathcpy (spath);
      } else {
          retpathcpy (&spath[1]);
      }
      return ScrubRetpath (retpath);
  }
  //
  // special case confusion elimination
  // Translate a path that looks similar to /c: to c:/.
  //
  else if (arg[0] == '/' && isabswinpath (arg + 1)) {
      retpathcpy (&arg[1]);
      return ScrubRetpath (retpath);
  }
  //
  // Check for variable set.
  //
  else if ((sspath = strchr(spath, '=')) && isalpha (spath[0])) {
      if (isabswinpath (sspath + 1)) {
          debug_printf("returning: %s", arg);
          return (char *)arg;
      }
      char *swin32_path = arg_heuristic(sspath + 1);
      if (swin32_path == (sspath + 1)) {
          debug_printf("returning: %s", arg);
          return (char *)arg;
      }
      *sspath = '\0';
      retpathcpy (spath);
      retpathcat ("=");
      retpathcat (swin32_path);
      free (swin32_path);
      return ScrubRetpath (retpath);
  }
  //
  // Check for paths after commas, if string begins with a '-' character.
  //
  else if ((sspath = strchr(spath, ',')) && spath[0] == '-') {
      if (isabswinpath (sspath + 1)) {
          debug_printf("returning: %s", arg);
          return (char *)arg;
      }
      char *swin32_path = arg_heuristic(sspath + 1);
      if (swin32_path == (sspath + 1)) {
          debug_printf("returning: %s", arg);
          return (char *)arg;
      }
      *sspath = '\0';
      retpathcpy (spath);
      retpathcat (",");
      retpathcat (swin32_path);
      free (swin32_path);
      return ScrubRetpath (retpath);
  }
  //
  // Check for POSIX path lists.
  // But we have to allow processing of quoted strings and switches first
  // which uses recursion so this code will be seen again.
  //
  else {
      sspath = strchr (spath, ':');
      //
      // Prevent http://some.string/ from being modified.
      // 
      if (   (sspath > 0 && strlen (sspath) > 2)
          && (sspath[1] == '/')
          && (sspath[2] == '/'))
      {
          debug_printf("returning: %s", arg);
          return ((char *)arg);
      }
      else
          if ((sspath > 0) && (strchr (spath, '/') > 0)
              // 
              // Prevent strings beginning with -, ", ', or @ from being processed,
              // remember that this is a recursive routine.
              // 
              && (strchr ("-\"\'@", spath[0]) == 0)
              // 
              // Prevent ``foo:echo /bar/baz'' from being considered a path list.
              // 
              && (strlen (sspath) > 1 && strchr (":./", sspath[1]) > 0)
              )
          {
              //
              // Yes, convert to Win32 path list.
              //
              while (sspath)
              {
                  *sspath = '\0';
                  char *swin32_path = arg_heuristic (spath);
                  //
                  // Just ignore sret; swin32_path has the value we need.
                  //
                  retpathcat (swin32_path);
                  if (swin32_path != spath)
                      free (swin32_path);
                  spath = sspath + 1;
                  sspath = strchr (spath, ':');
                  retpathcat (";");
                  //
                  // Handle the last path in the list.
                  //
                  if (!sspath) {
                      char *swin32_path = arg_heuristic (spath);
                      retpathcat (swin32_path);
                      if (swin32_path != spath)
                      free (swin32_path);
                  }
              }
              return ScrubRetpath (retpath);
          } else {
              switch (spath[0]) {
              case '/':
                  //
                  // Just a normal POSIX path.
                  //
                  {
                      //
                      // Convert only up to a ".." path component, and
                      // keep all what follows as is.
                      //
                      sspath = strstr (spath, "/..");
                      if (sspath) {
                          *sspath = '\0';
                          char *swin32_path = arg_heuristic (spath);
                          if (swin32_path == spath) {
                              debug_printf("returning: %s", arg);
                              return ((char *)arg);
                          }
                          retpathcpy (swin32_path);
                          retpathcat ("/");
                          retpathcat (sspath+1);
                          free (swin32_path);
                          return ScrubRetpath (retpath);
                      }
                      if (strcmp(spath, "/dev/null") == 0) {
                          retpathcpy("nul");
                          return ScrubRetpath (retpath);
                      }
                      path_conv p (spath, 0);
                      /*if (p.error) {
                          set_errno(p.error);
                          debug_printf("returning: %s", arg);
                          return ((char *)arg);
                      }*/
                      char win32_path1[PATH_MAX + 1];
                      ssize_t result = cygwin_conv_path(CCP_POSIX_TO_WIN_A|CCP_ABSOLUTE, spath, win32_path1, PATH_MAX+1);
                      retpathcpy (win32_path1);
                      return ScrubRetpath (retpath);
                  }
              case '-':
                  //
                  // here we check for POSIX paths as attributes to a POSIX switch.
                  //
                  sspath = strchr (spath, '=');
                  if (sspath) {
                      //
                      // just use recursion if we find a set variable token.
                      //
                      *sspath = '\0';
                      if (isabswinpath (sspath + 1)) {
                          debug_printf("returning: %s", arg);
                          return (char *)arg;
                      }
                      char *swin32_path = arg_heuristic(sspath + 1);
                      if (swin32_path == sspath + 1) {
                          debug_printf("returning: %s", arg);
                          return ((char *)arg);
                      }
                      retpathcpy (spath);
                      retpathcat ("=");
                      retpathcat (swin32_path);
                      free (swin32_path);
                      return ScrubRetpath (retpath);
                  } else {
                      //
                      // Check for single letter option with a
                      // path argument attached, eg -I/include */
                      //
                      if (spath[1] && spath[2] == '/') {
                          debug_printf("spath = %s", spath);
                          sspath = spath + 2;
                          char *swin32_path = arg_heuristic (sspath);
                          if (swin32_path == sspath) {
                              debug_printf("returning: %s", arg);
                              return ((char *)arg);
                          }
                          sspath = (char *)spath;
                          sspath++;
                          sspath++;
                          *sspath = '\0';
                          retpathcpy (spath);
                          *sspath = '/';
                          retpathcat (swin32_path);
                          free (swin32_path);
                          return ScrubRetpath (retpath);
                      } else {
                          debug_printf("returning: %s", arg);
                          return ((char *)arg);
                      }
                  }
                  break;
              case '@':
                  //
                  // here we check for POSIX paths as attributes to a response
                  // file argument (@file). This is specifically to support
                  // MinGW binutils and gcc.
                  //
                  sspath = spath + 1;
                  if (isabswinpath (sspath)) {
                      debug_printf("returning: %s", arg);
                      return (char *)arg;
                  }
                  if (spath[1] == '/') {
                      debug_printf("spath = %s", spath);
                      char *swin32_path = arg_heuristic (sspath);
                      if (swin32_path == sspath) {
                          debug_printf("returning: %s", arg);
                          return ((char *)arg);
                      }
                      sspath = (char *)spath;
                      sspath++;
                      *sspath = '\0';
                      retpathcpy (spath);
                      *sspath = '/';
                      retpathcat (swin32_path);
                      free (swin32_path);
                      return ScrubRetpath (retpath);
                  } else {
                      debug_printf("returning: %s", arg);
                      return ((char *)arg);
                  }
                  break;
              case '"':
                  //
                  // Handle a double quote case.
                  //
                  debug_printf ("spath: %s", spath);
                  if (spath[1] == '/') {
                      retpathcpy ("\"");
                      char *tpath = strchr(&spath[1], '"');
                      if (tpath)
                          *tpath = (char)NULL;
                      char *swin32_path = arg_heuristic (&spath[1]);
                      if (swin32_path == &spath[1]) {
                          debug_printf("returning: %s", arg);
                          return ((char *)arg);
                      }
                      retpathcat (swin32_path);
                      free (swin32_path);
                      if (tpath)
                          retpathcat ("\"");
                      return ScrubRetpath (retpath);
                  }
                  debug_printf("returning: %s", arg);
                  return ((char *)arg);
              case '\'':
                  //
                  // Handle a single quote case.
                  //
                  debug_printf ("spath: %s", spath);
                  if (spath[1] == '/') {
                      retpathcpy ("'");
                      char *tpath = strchr(&spath[1], '\'');
                      if (tpath)
                          *tpath = (char)NULL;
                      char *swin32_path = arg_heuristic (&spath[1]);
                      if (swin32_path == &spath[1]) {
                          debug_printf("returning: %s", arg);
                          return ((char *)arg);
                      }
                      retpathcat (swin32_path);
                      free (swin32_path);
                      if (tpath)
                          retpathcat ("'");
                      return ScrubRetpath (retpath);
                  }
                  debug_printf("returning: %s", arg);
                  return ((char *)arg);
              default:
                  //
                  // This takes care of variable_foo=/bar/baz
                  //
                  if ((sspath = strchr(spath, '=')) && (sspath[1] == '/')) {
                      sspath[1] = '\0';
                      retpathcpy (spath);
                      sspath[1] = '/';
                      char *swin32_path = arg_heuristic (&sspath[1]);
                      if (swin32_path == &sspath[1]) {
                          debug_printf("returning: %s", arg);
                          return ((char *)arg);
                      }
                      retpathcat (swin32_path);
                      free (swin32_path);
                      return ScrubRetpath (retpath);
                  }
                  //
                  // Oh well, nothing special found, set win32_path same as path.
                  //
                  debug_printf("returning: %s", arg);
                  return ((char *)arg);
              }
          }
  }
  // I should not get to this point.
  assert (false);
  debug_printf("returning: %s", arg);
  return ScrubRetpath (retpath);
}
예제 #26
0
    static dynamic_link_handle pin_symbols( dynamic_link_handle library_handle, dynamic_link_descriptor desc, const dynamic_link_descriptor* descriptors, size_t required ) {
        ::tbb::internal::suppress_unused_warning( desc, descriptors, required );
#if __TBB_DYNAMIC_LOAD_ENABLED
        // It is supposed that all symbols are from the only one library
        // The library has been loaded by another module and contains at least one requested symbol.
        // But after we obtained the symbol the library can be unloaded by another thread
        // invalidating our symbol. Therefore we need to pin the library in memory.
        const char * dli_fname;
    #ifdef __CYGWIN__
        MEMORY_BASIC_INFORMATION mbi;
        char path[MAX_PATH];
        VirtualQuery((void*)&dynamic_link, &mbi, sizeof(mbi));
        if(GetModuleFileNameA((HINSTANCE)mbi.AllocationBase, path, MAX_PATH)) {
        char posix_path[MAX_PATH];
        cygwin_conv_path(CCP_WIN_A_TO_POSIX | CCP_RELATIVE, path, posix_path, MAX_PATH);
        dli_fname = posix_path;

    #else
        Dl_info info;
        // Get library's name from earlier found symbol
        if ( dladdr( (void*)*desc.handler, &info ) ) {
            dli_fname = info.dli_fname;
    #endif
            // Pin the library
            library_handle = dlopen( dli_fname, RTLD_LAZY );
            if ( library_handle ) {
                // If original library was unloaded before we pinned it
                // and then another module loaded in its place, the earlier
                // found symbol would become invalid. So revalidate them.
                if ( !resolve_symbols( library_handle, descriptors, required ) ) {
                    // Wrong library.
                    dynamic_unlink(library_handle);
                    library_handle = 0;
                }
            } else {
                char const * err = dlerror();
                DYNAMIC_LINK_WARNING( dl_lib_not_found, dli_fname, err );
            }
        }
        else {
            // The library have been unloaded by another thread
            library_handle = 0;
        }
#endif /* __TBB_DYNAMIC_LOAD_ENABLED */
        return library_handle;
    }
#endif /* !_WIN32 */

    static dynamic_link_handle global_symbols_link( const char* library, const dynamic_link_descriptor descriptors[], size_t required ) {
        ::tbb::internal::suppress_unused_warning( library );
        dynamic_link_handle library_handle;
#if _WIN32
        if ( GetModuleHandleEx( 0, library, &library_handle ) ) {
            if ( resolve_symbols( library_handle, descriptors, required ) )
                return library_handle;
            else
                FreeLibrary( library_handle );
        }
#else /* _WIN32 */
    #if !__TBB_DYNAMIC_LOAD_ENABLED /* only __TBB_WEAK_SYMBOLS_PRESENT is defined */
        if ( !dlopen ) return 0;
    #endif /* !__TBB_DYNAMIC_LOAD_ENABLED */
        library_handle = dlopen( NULL, RTLD_LAZY );
    #if !__ANDROID__
        // On Android dlopen( NULL ) returns NULL if it is called during dynamic module initialization.
        LIBRARY_ASSERT( library_handle, "The handle for the main program is NULL" );
    #endif
        // Check existence of the first symbol only, then use it to find the library and load all necessary symbols.
        pointer_to_handler handler;
        dynamic_link_descriptor desc;
        desc.name = descriptors[0].name;
        desc.handler = &handler;
        if ( resolve_symbols( library_handle, &desc, 1 ) )
            return pin_symbols( library_handle, desc, descriptors, required );
#endif /* _WIN32 */
        return 0;
    }
예제 #27
0
    static void init_ap_data() {
    #if _WIN32
        // Get handle of our DLL first.
        HMODULE handle;
        BOOL brc = GetModuleHandleEx(
            GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
            (LPCSTR)( & dynamic_link ), // any function inside the library can be used for the address
            & handle
            );
        if ( !brc ) { // Error occurred.
            int err = GetLastError();
            DYNAMIC_LINK_WARNING( dl_sys_fail, "GetModuleHandleEx", err );
            return;
        }
        // Now get path to our DLL.
        DWORD drc = GetModuleFileName( handle, ap_data._path, static_cast< DWORD >( PATH_MAX ) );
        if ( drc == 0 ) { // Error occurred.
            int err = GetLastError();
            DYNAMIC_LINK_WARNING( dl_sys_fail, "GetModuleFileName", err );
            return;
        }
        if ( drc >= PATH_MAX ) { // Buffer too short.
            DYNAMIC_LINK_WARNING( dl_buff_too_small );
            return;
        }
        // Find the position of the last backslash.
        char *backslash = strrchr( ap_data._path, '\\' );

        if ( !backslash ) {    // Backslash not found.
            LIBRARY_ASSERT( backslash!=NULL, "Unbelievable.");
            return;
        }
        LIBRARY_ASSERT( backslash >= ap_data._path, "Unbelievable.");
        ap_data._len = (size_t)(backslash - ap_data._path) + 1;
        *(backslash+1) = 0;
    #else
        // Get the library path
        /*Dl_info dlinfo;
        int res = dladdr( (void*)&dynamic_link, &dlinfo ); // any function inside the library can be used for the address
        if ( !res ) {
            char const * err = dlerror();
            DYNAMIC_LINK_WARNING( dl_sys_fail, "dladdr", err );
            return;
        } else {
            LIBRARY_ASSERT( dlinfo.dli_fname!=NULL, "Unbelievable." );
        }*/
		const char *dli_fname;

		#ifdef __CYGWIN__
			MEMORY_BASIC_INFORMATION mbi;
			char path[MAX_PATH];
			VirtualQuery((void*)&dynamic_link, &mbi,
                sizeof(mbi));
			GetModuleFileNameA((HINSTANCE)mbi.AllocationBase, path, MAX_PATH);

			char posix_path[MAX_PATH];
			cygwin_conv_path(CCP_WIN_A_TO_POSIX | CCP_RELATIVE, path, posix_path, MAX_PATH);
			dli_fname = posix_path;

		#else
			Dl_info dlinfo;
			int res = dladdr( (void*)&dynamic_link, &dlinfo ); // any function inside the library can be used for the address
			if ( !res ) {
				char const * err = dlerror();
				DYNAMIC_LINK_WARNING( dl_sys_fail, "dladdr", err );
				return;
			} else {
				LIBRARY_ASSERT( dlinfo.dli_fname!=NULL, "Unbelievable." );
			}
			dli_fname = dlinfo.dli_fname;
		#endif

        char const *slash = strrchr( dli_fname, '/' );
        size_t fname_len=0;
        if ( slash ) {
            LIBRARY_ASSERT( slash >= dli_fname, "Unbelievable.");
            fname_len = (size_t)(slash - dli_fname) + 1;
        }

        size_t rc;
        if ( dli_fname[0]=='/' ) {
            // The library path is absolute
            rc = 0;
            ap_data._len = 0;
        } else {
            // The library path is relative so get the current working directory
            if ( !getcwd( ap_data._path, sizeof(ap_data._path)/sizeof(ap_data._path[0]) ) ) {
                DYNAMIC_LINK_WARNING( dl_buff_too_small );
                return;
            }
            ap_data._len = strlen( ap_data._path );
            ap_data._path[ap_data._len++]='/';
            rc = ap_data._len;
        }

        if ( fname_len>0 ) {
            if ( ap_data._len>PATH_MAX ) {
                DYNAMIC_LINK_WARNING( dl_buff_too_small );
                ap_data._len=0;
                return;
            }
            strncpy( ap_data._path+rc, dli_fname, fname_len );
            ap_data._len += fname_len;
            ap_data._path[ap_data._len]=0;
        }
    #endif /* _WIN32 */
    }
예제 #28
0
wxChar *wxDoGetCwd(wxChar *buf, int sz)
{
    if ( !buf )
    {
        buf = new wxChar[sz + 1];
    }

    bool ok = false;

    // for the compilers which have Unicode version of _getcwd(), call it
    // directly, for the others call the ANSI version and do the translation
#if !wxUSE_UNICODE
    #define cbuf buf
#else // wxUSE_UNICODE
    bool needsANSI = true;

    #if !defined(HAVE_WGETCWD)
        char cbuf[_MAXPATHLEN];
    #endif

    #ifdef HAVE_WGETCWD
            char *cbuf = NULL; // never really used because needsANSI will always be false
            {
                ok = _wgetcwd(buf, sz) != NULL;
                needsANSI = false;
            }
    #endif

    if ( needsANSI )
#endif // wxUSE_UNICODE
    {
    #if defined(_MSC_VER) || defined(__MINGW32__)
        ok = _getcwd(cbuf, sz) != NULL;
    #else // !Win32/VC++ !Mac
        ok = getcwd(cbuf, sz) != NULL;
    #endif // platform

    #if wxUSE_UNICODE
        // finally convert the result to Unicode if needed
        wxConvFile.MB2WC(buf, cbuf, sz);
    #endif // wxUSE_UNICODE
    }

    if ( !ok )
    {
        wxLogSysError(_("Failed to get the working directory"));

        // VZ: the old code used to return "." on error which didn't make any
        //     sense at all to me - empty string is a better error indicator
        //     (NULL might be even better but I'm afraid this could lead to
        //     problems with the old code assuming the return is never NULL)
        buf[0] = wxT('\0');
    }
    else // ok, but we might need to massage the path into the right format
    {
// MBN: we hope that in the case the user is compiling a GTK+/Motif app,
//      he needs Unix as opposed to Win32 pathnames
#if defined( __CYGWIN__ ) && defined( __WINDOWS__ )
        // another example of DOS/Unix mix (Cygwin)
        wxString pathUnix = buf;
#if wxUSE_UNICODE
    #if CYGWIN_VERSION_DLL_MAJOR >= 1007
        cygwin_conv_path(CCP_POSIX_TO_WIN_W, pathUnix.mb_str(wxConvFile), buf, sz);
    #else
        char bufA[_MAXPATHLEN];
        cygwin_conv_to_full_win32_path(pathUnix.mb_str(wxConvFile), bufA);
        wxConvFile.MB2WC(buf, bufA, sz);
    #endif
#else
    #if CYGWIN_VERSION_DLL_MAJOR >= 1007
        cygwin_conv_path(CCP_POSIX_TO_WIN_A, pathUnix, buf, sz);
    #else
        cygwin_conv_to_full_win32_path(pathUnix, buf);
    #endif
#endif // wxUSE_UNICODE
#endif // __CYGWIN__
    }

    return buf;

#if !wxUSE_UNICODE
    #undef cbuf
#endif

}
예제 #29
0
/* Start a new process.
   PROGRAM is a path to the program to execute.
   ARGS is a standard NULL-terminated array of arguments,
   to be passed to the inferior as ``argv''.
   Returns the new PID on success, -1 on failure.  Registers the new
   process with the process list.  */
static int
win32_create_inferior (char *program, char **program_args)
{
#ifndef USE_WIN32API
  char real_path[PATH_MAX];
  char *orig_path, *new_path, *path_ptr;
#endif
  BOOL ret;
  DWORD flags;
  char *args;
  int argslen;
  int argc;
  PROCESS_INFORMATION pi;
  DWORD err;

  /* win32_wait needs to know we're not attaching.  */
  attaching = 0;

  if (!program)
    error ("No executable specified, specify executable to debug.\n");

  flags = DEBUG_PROCESS | DEBUG_ONLY_THIS_PROCESS;

#ifndef USE_WIN32API
  orig_path = NULL;
  path_ptr = getenv ("PATH");
  if (path_ptr)
    {
      int size = cygwin_conv_path_list (CCP_POSIX_TO_WIN_A, path_ptr, NULL, 0);
      orig_path = alloca (strlen (path_ptr) + 1);
      new_path = alloca (size);
      strcpy (orig_path, path_ptr);
      cygwin_conv_path_list (CCP_POSIX_TO_WIN_A, path_ptr, new_path, size);
      setenv ("PATH", new_path, 1);
     }
  cygwin_conv_path (CCP_POSIX_TO_WIN_A, program, real_path, PATH_MAX);
  program = real_path;
#endif

  argslen = 1;
  for (argc = 1; program_args[argc]; argc++)
    argslen += strlen (program_args[argc]) + 1;
  args = alloca (argslen);
  args[0] = '\0';
  for (argc = 1; program_args[argc]; argc++)
    {
      /* FIXME: Can we do better about quoting?  How does Cygwin
	 handle this?  */
      strcat (args, " ");
      strcat (args, program_args[argc]);
    }
  OUTMSG2 (("Command line is \"%s\"\n", args));

#ifdef CREATE_NEW_PROCESS_GROUP
  flags |= CREATE_NEW_PROCESS_GROUP;
#endif

  ret = create_process (program, args, flags, &pi);
  err = GetLastError ();
  if (!ret && err == ERROR_FILE_NOT_FOUND)
    {
      char *exename = alloca (strlen (program) + 5);
      strcat (strcpy (exename, program), ".exe");
      ret = create_process (exename, args, flags, &pi);
      err = GetLastError ();
    }

#ifndef USE_WIN32API
  if (orig_path)
    setenv ("PATH", orig_path, 1);
#endif

  if (!ret)
    {
      error ("Error creating process \"%s%s\", (error %d): %s\n",
	     program, args, (int) err, strwinerror (err));
    }
  else
    {
      OUTMSG2 (("Process created: %s\n", (char *) args));
    }

#ifndef _WIN32_WCE
  /* On Windows CE this handle can't be closed.  The OS reuses
     it in the debug events, while the 9x/NT versions of Windows
     probably use a DuplicateHandle'd one.  */
  CloseHandle (pi.hThread);
#endif

  do_initial_child_stuff (pi.hProcess, pi.dwProcessId, 0);

  return current_process_id;
}
예제 #30
0
void
ruby_init_loadpath_safe(int safe_level)
{
    VALUE load_path;
    extern const char ruby_initial_load_paths[];
    const char *paths = ruby_initial_load_paths;
#if defined LOAD_RELATIVE
# if defined HAVE_DLADDR || (defined __CYGWIN__ && defined CCP_WIN_A_TO_POSIX)
#   define VARIABLE_LIBPATH 1
# else
#   define VARIABLE_LIBPATH 0
# endif
# if VARIABLE_LIBPATH
    char *libpath;
    VALUE sopath;
# else
    char libpath[MAXPATHLEN + 1];
    size_t baselen;
# endif
    char *p;

#if defined _WIN32 || defined __CYGWIN__
# if VARIABLE_LIBPATH
    sopath = rb_str_tmp_new(MAXPATHLEN);
    libpath = RSTRING_PTR(sopath);
    GetModuleFileName(libruby, libpath, MAXPATHLEN);
# else
    GetModuleFileName(libruby, libpath, sizeof libpath);
# endif
#elif defined(__EMX__)
    _execname(libpath, sizeof(libpath) - 1);
#elif defined(HAVE_DLADDR)
    Dl_info dli;
    if (dladdr(expand_include_path, &dli)) {
	VALUE fname = rb_str_new_cstr(dli.dli_fname);
	sopath = rb_file_absolute_path(fname, Qnil);
	rb_str_resize(fname, 0);
    }
    else {
	sopath = rb_str_new(0, 0);
    }
    libpath = RSTRING_PTR(sopath);
#endif

#if !VARIABLE_LIBPATH
    libpath[sizeof(libpath) - 1] = '\0';
#endif
#if defined DOSISH
    translit_char(libpath, '\\', '/');
#elif defined __CYGWIN__
    {
# if VARIABLE_LIBPATH
	const int win_to_posix = CCP_WIN_A_TO_POSIX | CCP_RELATIVE;
	size_t newsize = cygwin_conv_path(win_to_posix, libpath, 0, 0);
	if (newsize > 0) {
	    VALUE rubylib = rb_str_tmp_new(newsize);
	    p = RSTRING_PTR(rubylib);
	    if (cygwin_conv_path(win_to_posix, libpath, p, newsize) == 0) {
		rb_str_resize(sopath, 0);
		sopath = rubylib;
		libpath = p;
	    }
	}
# else
	char rubylib[FILENAME_MAX];
	cygwin_conv_to_posix_path(libpath, rubylib);
	strncpy(libpath, rubylib, sizeof(libpath));
# endif
    }
#endif
    p = strrchr(libpath, '/');
    if (p) {
	*p = 0;
	if (p - libpath > 3 && !(STRCASECMP(p - 4, "/bin") && strcmp(p - 4, "/lib"))) {
	    p -= 4;
	    *p = 0;
	}
    }
#if !VARIABLE_LIBPATH
    else {
	strlcpy(libpath, ".", sizeof(libpath));
	p = libpath + 1;
    }

    baselen = p - libpath;

#define BASEPATH() rb_str_buf_cat(rb_str_buf_new(baselen+len), libpath, baselen)
#else
    rb_str_set_len(sopath, p - libpath);

#define BASEPATH() rb_str_dup(sopath)
#endif

#define RUBY_RELATIVE(path, len) rb_str_buf_cat(BASEPATH(), path, len)
#else
#define RUBY_RELATIVE(path, len) rubylib_mangled_path(path, len)
#endif
#define incpush(path) rb_ary_push(load_path, (path))
    load_path = GET_VM()->load_path;

    if (safe_level == 0) {
	ruby_push_include(getenv("RUBYLIB"), identical_path);
    }

    while (*paths) {
	size_t len = strlen(paths);
	incpush(RUBY_RELATIVE(paths, len));
	paths += len + 1;
    }
}