Exemplo n.º 1
0
/* --- functions --- */
static gpointer
_g_module_open (const gchar *file_name,
		gboolean     bind_lazy,
		gboolean     bind_local)
{
  HINSTANCE handle;
  wchar_t *wfilename;
  DWORD old_mode;
  BOOL success;
#ifdef G_WITH_CYGWIN
  gchar tmp[MAX_PATH];

  cygwin_conv_to_win32_path(file_name, tmp);
  file_name = tmp;
#endif
  wfilename = g_utf8_to_utf16 (file_name, -1, NULL, NULL, NULL);

  /* suppress error dialog */
  success = SetThreadErrorMode (SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS, &old_mode);
  if (!success)
    set_error ("");
  handle = LoadLibraryW (wfilename);
  if (success)
    SetThreadErrorMode (old_mode, NULL);
  g_free (wfilename);
      
  if (!handle)
    set_error ("'%s': ", file_name);

  return handle;
}
Exemplo n.º 2
0
static void
ctime_now(const char* path)
{
	HANDLE		hp;
	SYSTEMTIME	st;
	FILETIME	ct;
	WIN32_FIND_DATA	ff;
	struct stat	fs;
	int		oerrno;
	char		tmp[MAX_PATH];

	if (sysstat(path, &fs) || (fs.st_mode & S_IWUSR) || syschmod(path, (fs.st_mode | S_IWUSR) & S_IPERM))
		fs.st_mode = 0;
	cygwin_conv_to_win32_path(path, tmp);
	hp = CreateFile(tmp, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
	if (hp && hp != INVALID_HANDLE_VALUE)
	{
		GetSystemTime(&st);
		SystemTimeToFileTime(&st, &ct);
		SetFileTime(hp, &ct, 0, 0);
		CloseHandle(hp);
	}
	if (fs.st_mode)
		syschmod(path, fs.st_mode & S_IPERM);
	errno = oerrno;
}
Exemplo n.º 3
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;
  }
Exemplo n.º 4
0
std::string FixWindowsPath(const std::string &in)
{
#if defined(__CYGWIN__)
  char tmp[1024];
  cygwin_conv_to_win32_path(in.c_str(), tmp);
  return std::string(tmp);
#else
  return in;
#endif
}
Exemplo n.º 5
0
const wxString ecUtils::PosixToNativePath(const wxString & posix)
{
#ifdef __CYGWIN__
    if (posix.IsEmpty())
        return posix;
    else
    {
        wxString native;
        cygwin_conv_to_win32_path(posix.c_str(), native.GetWriteBuf(MAXPATHLEN + 1));
        native.UngetWriteBuf();
        return native;
    }
#else
    return posix;
#endif
}
/* --- functions --- */
static gpointer
_g_module_open (const gchar *file_name,
		gboolean     bind_lazy)
{
  HINSTANCE handle;
#ifdef G_WITH_CYGWIN
  gchar tmp[MAX_PATH];

  cygwin_conv_to_win32_path(file_name, tmp);
  file_name = tmp;
#endif
  
  handle = LoadLibrary (file_name);
  if (!handle)
    set_error ();

  return handle;
}
Exemplo n.º 7
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);

        char result[MAX_PATH + 1];

#if defined(BOOST_WINDOWS_PATH)
        cygwin_conv_to_win32_path(path.c_str(), result);
#elif defined(BOOST_POSIX_PATH)
        cygwin_conv_to_posix_path(path.c_str(), result);
#else
#    error "Boost filesystem path type doesn't seem to be set."
#endif

        v = input_path(result);
    }
Exemplo n.º 8
0
void *ILDynLibraryOpen(const char *name)
{
	void *libHandle;
	char *newName = 0;

#if defined(IL_WIN32_CYGWIN) && defined(HAVE_SYS_CYGWIN_H) && \
    defined(HAVE_CYGWIN_CONV_TO_WIN32_PATH)

	/* Use Cygwin to expand the path */
	{
		char buf[4096];
		if(cygwin_conv_to_win32_path(name, buf) == 0)
		{
			newName = ILDupString(buf);
			if(!newName)
			{
				return 0;
			}
		}
	}

#endif

	/* Attempt to load the library */
	libHandle = (void *)LoadLibrary((newName ? newName : name));
	if(libHandle == 0)
	{
	#ifdef IL_DYNLIB_DEBUG
		fprintf(stderr, "%s: could not load dynamic library\n",
				(newName ? newName : name));
	#endif
		if(newName)
		{
			ILFree(newName);
		}
		return 0;
	}
	if(newName)
	{
		ILFree(newName);
	}
	return libHandle;
}
/* Copy cygwin environment variables to the Windows environment if they're not
 * already there. */
static void setup_win_environ(void)
{
    char **envp = environ;
    char *var, *val;
    char curval[2];
    char *winpathlist;
    char winpath[MAX_PATH+1];

    while (envp && *envp) {
        var = strdup(*envp++);
        val = strchr(var, '=');
        *val++ = '\0';
        
        if (GetEnvironmentVariable(var, curval, 2) == 0
                    && GetLastError() == ERROR_ENVVAR_NOT_FOUND) {
            /* Convert POSIX to Win32 where necessary */
            if (!strcmp(var, "PATH") ||
                        !strcmp(var, "LD_LIBRARY_PATH")) {
                winpathlist = (char *)
                      malloc(cygwin_posix_to_win32_path_list_buf_size(val)+1);
                if (winpathlist) {
                    cygwin_posix_to_win32_path_list(val, winpathlist);
                    //std::cout << "A: setting " << var << " to " << winpathlist << "\n";
                    SetEnvironmentVariable(var, winpathlist);
                    free(winpathlist);
                }
            } else if (!strcmp(var, "HOME") ||
                        !strcmp(var, "TMPDIR") ||
                        !strcmp(var, "TMP") ||
                        !strcmp(var, "TEMP")) {
                //std::cout << "B: setting " << var << " to " << winpath << "\n";
                cygwin_conv_to_win32_path(val, winpath);
                SetEnvironmentVariable(var, winpath);
            } else {
                //std::cout << "C: setting " << var << " to " << val << "\n";
                //std::cout.flush();
                SetEnvironmentVariable(var, val);
            }
        }

        free(var);
    }
}
Exemplo n.º 10
0
/* --- functions --- */
static gpointer
_g_module_open (const gchar *file_name,
		gboolean     bind_lazy,
		gboolean     bind_local)
{
  HINSTANCE handle;
  wchar_t *wfilename;
#ifdef G_WITH_CYGWIN
  gchar tmp[MAX_PATH];

  cygwin_conv_to_win32_path(file_name, tmp);
  file_name = tmp;
#endif
  wfilename = g_utf8_to_utf16 (file_name, -1, NULL, NULL, NULL);

  handle = LoadLibraryW (wfilename);
  g_free (wfilename);
      
  if (!handle)
    set_error ("'%s': ", file_name);

  return handle;
}
Exemplo n.º 11
0
static void
var_edit_shift( 
	string	*out,
	VAR_EDITS *edits )
{
	/* Handle upshifting, downshifting and slash translation now */

    char *p;
    for ( p = out->value; *p; ++p)
    {
        if (edits->upshift)
        {
            *p = toupper( *p );
        }
        else if ( edits->downshift )
        {
            *p = tolower( *p );
        } 
        if ( edits->to_slashes )
        {
            if ( *p == '\\')
                *p = '/';
        }
# ifdef OS_CYGWIN
        if ( edits->to_windows )
        {
            char result[MAX_PATH + 1];
            cygwin_conv_to_win32_path(out->value, result);
            assert(strlen(result) <= MAX_PATH);
            string_free( out );
            string_copy( out, result );
        }
# endif
    }
    out->size = p - out->value;
}
Exemplo n.º 12
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[MAXPATHLEN];
  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)
    {
      orig_path = alloca (strlen (path_ptr) + 1);
      new_path = alloca (cygwin_posix_to_win32_path_list_buf_size (path_ptr));
      strcpy (orig_path, path_ptr);
      cygwin_posix_to_win32_path_list (path_ptr, new_path);
      setenv ("PATH", new_path, 1);
    }
  cygwin_conv_to_win32_path (program, real_path);
  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;
}
Exemplo n.º 13
0
static wBOOL CALLBACK
winAboutDlgProc (HWND hwndDialog, UINT message,
		 WPARAM wParam, LPARAM lParam)
{
  static winPrivScreenPtr	s_pScreenPriv = NULL;
  static winScreenInfo		*s_pScreenInfo = NULL;
  static ScreenPtr		s_pScreen = NULL;

#if CYGDEBUG
  winDebug ("winAboutDlgProc\n");
#endif

  /* Branch on message type */
  switch (message)
    {
    case WM_INITDIALOG:
#if CYGDEBUG
      winDebug ("winAboutDlgProc - WM_INITDIALOG\n");
#endif

      /* Store pointers to private structures for future use */
      s_pScreenPriv = (winPrivScreenPtr) lParam;
      s_pScreenInfo = s_pScreenPriv->pScreenInfo;
      s_pScreen = s_pScreenInfo->pScreen;

      winInitDialog (hwndDialog);

      /* Override the URL buttons */
      winOverrideURLButton (hwndDialog, ID_ABOUT_CHANGELOG);
      winOverrideURLButton (hwndDialog, ID_ABOUT_WEBSITE);
      winOverrideURLButton (hwndDialog, ID_ABOUT_UG);
      winOverrideURLButton (hwndDialog, ID_ABOUT_FAQ);

      return TRUE;

    case WM_DRAWITEM:
      /* Draw the URL buttons as needed */
      winDrawURLWindow (lParam);
      return TRUE;

    case WM_MOUSEMOVE:
    case WM_NCMOUSEMOVE:
      /* Show the cursor if it is hidden */
      if (g_fSoftwareCursor && !g_fCursor)
	{
	  g_fCursor = TRUE;
	  ShowCursor (TRUE);
	}
      return TRUE;

    case WM_COMMAND:
      switch (LOWORD (wParam))
	{
	case IDOK:
	case IDCANCEL:
	  ErrorF ("winAboutDlgProc - WM_COMMAND - IDOK or IDCANCEL\n");

	  DestroyWindow (g_hDlgAbout);
	  g_hDlgAbout = NULL;

	  /* Fix to make sure keyboard focus isn't trapped */
	  PostMessage (s_pScreenPriv->hwndScreen, WM_NULL, 0, 0);

	  /* Restore window procedures for URL buttons */
	  winUnoverrideURLButton (hwndDialog, ID_ABOUT_CHANGELOG);
	  winUnoverrideURLButton (hwndDialog, ID_ABOUT_WEBSITE);
	  winUnoverrideURLButton (hwndDialog, ID_ABOUT_UG);
	  winUnoverrideURLButton (hwndDialog, ID_ABOUT_FAQ);

	  return TRUE;

	case ID_ABOUT_CHANGELOG:
	  {
	    int iReturn;
#ifdef __CYGWIN__
	    const char *	pszCygPath = "/usr/X11R6/share/doc/"
	      "xorg-x11-xwin/changelog.html";
	    char		pszWinPath[MAX_PATH + 1];

	    /* Convert the POSIX path to a Win32 path */
	    cygwin_conv_to_win32_path (pszCygPath, pszWinPath);
#else
	    const char *	pszWinPath = "http://x.cygwin.com/"
		    "devel/server/changelog.html";
#endif
	    
	    iReturn = (int)ShellExecute (NULL,
                                    "open",
                                    pszWinPath,
                                    NULL,
                                    NULL,
                                    SW_MAXIMIZE);
	    if (iReturn < 32)
	      {
		ErrorF ("winAboutDlgProc - WM_COMMAND - ID_ABOUT_CHANGELOG - "
			"ShellExecute failed: %d\n",
			iReturn);
	      }	    
	  }
	  return TRUE;

	case ID_ABOUT_WEBSITE:
	  {
	    const char *	pszPath = __VENDORDWEBSUPPORT__;
	    int			iReturn;
	    
	    iReturn = (int)ShellExecute (NULL,
                                    "open",
                                    pszPath,
                                    NULL,
                                    NULL,
                                    SW_MAXIMIZE);
	    if (iReturn < 32)
	      {
		ErrorF ("winAboutDlgProc - WM_COMMAND - ID_ABOUT_WEBSITE - "
			"ShellExecute failed: %d\n",
			iReturn);
	      }	    
	  }
	  return TRUE;

	case ID_ABOUT_UG:
	  {
	    const char *	pszPath = "http://x.cygwin.com/docs/ug/";
	    int			iReturn;
	    
	    iReturn = (int)ShellExecute (NULL,
                                    "open",
                                    pszPath,
                                    NULL,
                                    NULL,
                                    SW_MAXIMIZE);
	    if (iReturn < 32)
	      {
		ErrorF ("winAboutDlgProc - WM_COMMAND - ID_ABOUT_UG - "
			"ShellExecute failed: %d\n",
			iReturn);
	      }	    
	  }
	  return TRUE;

	case ID_ABOUT_FAQ:
	  {
	    const char *	pszPath = "http://x.cygwin.com/docs/faq/";
	    int			iReturn;
	    
	    iReturn = (int)ShellExecute (NULL,
                                    "open",
                                    pszPath,
                                    NULL,
                                    NULL,
                                    SW_MAXIMIZE);
	    if (iReturn < 32)
	      {
		ErrorF ("winAboutDlgProc - WM_COMMAND - ID_ABOUT_FAQ - "
			"ShellExecute failed: %d\n",
			iReturn);
	      }	    
	  }
	  return TRUE;
	}
      break;

    case WM_CLOSE:
      ErrorF ("winAboutDlgProc - WM_CLOSE\n");

      DestroyWindow (g_hDlgAbout);
      g_hDlgAbout = NULL;

      /* Fix to make sure keyboard focus isn't trapped */
      PostMessage (s_pScreenPriv->hwndScreen, WM_NULL, 0, 0);

      /* Restore window procedures for URL buttons */
      winUnoverrideURLButton (hwndDialog, ID_ABOUT_CHANGELOG);
      winUnoverrideURLButton (hwndDialog, ID_ABOUT_WEBSITE);
      winUnoverrideURLButton (hwndDialog, ID_ABOUT_UG);
      winUnoverrideURLButton (hwndDialog, ID_ABOUT_FAQ);

      return TRUE;
    }

  return FALSE;
}
Exemplo n.º 14
0
/*
 * private static bool StartProcess(String filename, String arguments,
 *									String workingDir,
 *									String[] argv, int flags,
 *									int windowStyle, String[] envVars,
 *									String verb, IntPtr errorDialogParent,
 *									out IntPtr processHandle,
 *									out int processID,
 *									out IntPtr stdinHandle,
 *									out IntPtr stdoutHandle,
 *									out IntPtr stderrHandle);
 */
ILBool _IL_Process_StartProcess(ILExecThread *_thread,
								ILString *filename,
								ILString *arguments,
								ILString *workingDir,
								System_Array *argv,
								ILInt32 flags,
								ILInt32 windowStyle,
								System_Array *envVars,
								ILString *verb,
								ILNativeInt errorDialogParent,
								ILNativeInt *processHandle,
								ILInt32 *processID,
								ILNativeInt *stdinHandle,
								ILNativeInt *stdoutHandle,
								ILNativeInt *stderrHandle)
{
#ifdef IL_WIN32_PLATFORM

#ifdef IL_WIN32_CYGWIN
	#define	GET_OSF(fd)		((HANDLE)(get_osfhandle((fd))))
	#define	MAKE_PIPE(fds)	(pipe((fds)))
#else
	#define	GET_OSF(fd)		((HANDLE)(_get_osfhandle((fd))))
	#define	MAKE_PIPE(fds)	(_pipe((fds), 0, _O_BINARY))
#endif

	const char *fname;
	const char *workdir = 0;
	char *args;
	STARTUPINFO startupInfo;
	PROCESS_INFORMATION processInfo;
	char *env = 0;
	ILBool result;
	int pipefds[2];
	int cleanups[8];
	int numCleanups = 0;
	int closeAfterFork[8];
	int numCloseAfterFork = 0;
	int index;
#if defined(HAVE_SYS_CYGWIN_H) && defined(HAVE_CYGWIN_CONV_TO_WIN32_PATH)
	char cygFname[4096];
	char cygWorkdir[4096];
#endif

	/* Clear errno, because we will check for it when something fails */
	ILSysIOSetErrno(0);

	/* Convert the parameters into something that the OS can understand */
	fname = ILStringToAnsi(_thread, filename);
	if(!fname)
	{
		return 0;
	}

#if defined(HAVE_SYS_CYGWIN_H) && defined(HAVE_CYGWIN_CONV_TO_WIN32_PATH)
	/* Use the Cygwin-supplied function to convert the path
	   that CreateProcess() will understand */
	if(cygwin_conv_to_win32_path(fname, cygFname) == 0)
	{
		fname = cygFname;
	}
#endif

	if(((System_String *) workingDir)->length)
	{
		workdir = ILStringToAnsi(_thread, workingDir);
		if(!workdir)
		{
			return 0;
		}
#if defined(HAVE_SYS_CYGWIN_H) && defined(HAVE_CYGWIN_CONV_TO_WIN32_PATH)
		/* Use convert workdir for CreateProcess() under cygwin */
		if(cygwin_conv_to_win32_path(workdir, cygWorkdir) == 0)
		{
			workdir = cygWorkdir;
		}
#endif
	}
	args = ILStringToAnsi(_thread, arguments);
	if(!args)
	{
		return 0;
	}
	ILMemZero(&startupInfo, sizeof(startupInfo));
	startupInfo.cb = sizeof(STARTUPINFO);
	startupInfo.dwFlags = STARTF_USESHOWWINDOW;
	startupInfo.wShowWindow = (WORD)windowStyle;

	/* Redirect stdin, stdout, and stderr if necessary */
	*stdinHandle = (ILNativeInt)(ILSysIOHandle_Invalid);
	*stdoutHandle = (ILNativeInt)(ILSysIOHandle_Invalid);
	*stderrHandle = (ILNativeInt)(ILSysIOHandle_Invalid);
	if((flags & (ProcessStart_RedirectStdin |
				 ProcessStart_RedirectStdout |
				 ProcessStart_RedirectStderr)) != 0)
	{
		startupInfo.dwFlags |= STARTF_USESTDHANDLES;
		if((flags & ProcessStart_RedirectStdin) != 0)
		{
			MAKE_PIPE(pipefds);
			*stdinHandle = (ILNativeInt)(pipefds[1]);
			SetHandleInformation(GET_OSF(pipefds[1]),
								 HANDLE_FLAG_INHERIT, 0);
			startupInfo.hStdInput = GET_OSF(pipefds[0]);
			cleanups[numCleanups++] = pipefds[0];
			cleanups[numCleanups++] = pipefds[1];
			closeAfterFork[numCloseAfterFork++] = pipefds[0];
		}
		else
		{
			startupInfo.hStdInput = GET_OSF(0);
		}
		if((flags & ProcessStart_RedirectStdout) != 0)
		{
			MAKE_PIPE(pipefds);
			*stdoutHandle = (ILNativeInt)(pipefds[0]);
			SetHandleInformation(GET_OSF(pipefds[0]),
								 HANDLE_FLAG_INHERIT, 0);
			startupInfo.hStdOutput = GET_OSF(pipefds[1]);
			cleanups[numCleanups++] = pipefds[0];
			cleanups[numCleanups++] = pipefds[1];
			closeAfterFork[numCloseAfterFork++] = pipefds[1];
		}
		else
		{
			startupInfo.hStdOutput = GET_OSF(1);
		}
		if((flags & ProcessStart_RedirectStderr) != 0)
		{
			MAKE_PIPE(pipefds);
			*stderrHandle = (ILNativeInt)(pipefds[0]);
			SetHandleInformation(GET_OSF(pipefds[0]),
								 HANDLE_FLAG_INHERIT, 0);
			startupInfo.hStdError = GET_OSF(pipefds[1]);
			cleanups[numCleanups++] = pipefds[0];
			cleanups[numCleanups++] = pipefds[1];
			closeAfterFork[numCloseAfterFork++] = pipefds[1];
		}
		else
		{
			startupInfo.hStdError = GET_OSF(2);
		}
	}

	/* TODO: shell execution, environment variables, and ExecOverTop */

	/* Launch the process */
	*processID = -1;
	*processHandle = 0;
	result = 0;
	if(CreateProcess(fname, args, NULL, NULL, TRUE, 0, env, workdir,
					 &startupInfo, &processInfo))
	{
		*processHandle = (ILNativeInt)(processInfo.hProcess);
		*processID = (ILInt32)(processInfo.dwProcessId);
		result = 1;
	}
	else
	{
		/* TODO: it could be useful to report error details using GetLastError().
		   We can't do ILSysIOSetErrno(GetLastError()), because errno is related
		   to IO function, while GetLastError() is windows-specific error code */
		ILSysIOSetErrno(ENOENT);
	}

	/* Clean up and exit */
	if(env)
	{
		ILFree(env);
	}
	if(result)
	{
		for(index = 0; index < numCloseAfterFork; ++index)
		{
			close(closeAfterFork[index]);
		}
	}
	else
	{
		for(index = 0; index < numCleanups; ++index)
		{
			close(cleanups[index]);
		}
	}
	return result;

#elif defined(HAVE_FORK) && defined(HAVE_EXECV) && (defined(HAVE_WAITPID) || defined(HAVE_WAIT))
#define	IL_USING_FORK	1

	const char *fname;
	const char *workdir = 0;
	char **args;
	char **newEnviron = 0;
	int varNum = 0;
	int stdinFds[2] = {-1, -1};
	int stdoutFds[2] = {-1, -1};
	int stderrFds[2] = {-1, -1};
	ILBool result = 0;
	int pid;
	ILInt32 argc;
	const char *ansi;
	int pipefds[2];
#define	FreeStringList(list,size)	\
		do { \
			if((list)) \
			{ \
				int __posn = (int)(size); \
				while(__posn > 0) \
				{ \
					--__posn; \
					ILFree((list)[__posn]); \
				} \
				ILFree((list)); \
			} \
		} while (0)

	/* Convert the parameters into something that the OS can understand */
	fname = ILStringToAnsi(_thread, filename);
	if(!fname)
	{
		return 0;
	}
	if(((System_String *) workingDir)->length)
	{
		workdir = ILStringToAnsi(_thread, workingDir);
		if(!workdir)
		{
			return 0;
		}
	}
	args = (char **)ILCalloc(ArrayLength(argv) + 1, sizeof(char *));
	if(!args)
	{
		ILExecThreadThrowOutOfMemory(_thread);
		return 0;
	}
	argc = 0;
	while(argc < ArrayLength(argv))
	{
		ansi = ILStringToAnsi
			(_thread, ((ILString **)ArrayToBuffer(argv))[argc]);
		if(!ansi)
		{
			FreeStringList(args, argc);
			return 0;
		}
		args[argc] = (char *)ILMalloc(strlen(ansi) + 1);
		if(!(args[argc]))
		{
			FreeStringList(args, argc);
			return 0;
		}
		strcpy(args[argc], ansi);
		++argc;
	}
	args[argc] = 0;

	/* Convert the environment */
	if(envVars)
	{
		newEnviron = (char **)ILCalloc(ArrayLength(envVars) + 1, sizeof(char *));
		if(!newEnviron)
		{
			ILExecThreadThrowOutOfMemory(_thread);
			FreeStringList(args, argc);
			return 0;
		}
		while(varNum < (int)(ArrayLength(envVars)))
		{
			ansi = ILStringToAnsi
				(_thread, ((ILString **)ArrayToBuffer(envVars))[varNum]);
			if(!ansi)
			{
				FreeStringList(args, argc);
				FreeStringList(newEnviron, varNum);
				return 0;
			}
			newEnviron[varNum] = (char *)ILMalloc(strlen(ansi) + 1);
			if(!(newEnviron[varNum]))
			{
				FreeStringList(args, argc);
				FreeStringList(newEnviron, varNum);
				return 0;
			}
			strcpy(newEnviron[varNum], ansi);
			++varNum;
		}
		newEnviron[varNum] = 0;
	}

	/* Redirect stdin, stdout, and stderr as necessary */
	*stdinHandle = (ILNativeInt)(ILSysIOHandle_Invalid);
	*stdoutHandle = (ILNativeInt)(ILSysIOHandle_Invalid);
	*stderrHandle = (ILNativeInt)(ILSysIOHandle_Invalid);
	if((flags & ProcessStart_RedirectStdin) != 0)
	{
		if(pipe(stdinFds) < 0)
		{
			return 0;
		}
	#if HAVE_FCNTL
		fcntl(stdinFds[1], F_SETFD, 1);
	#endif
		*stdinHandle = (ILNativeInt)(stdinFds[1]);
	}
	if((flags & ProcessStart_RedirectStdout) != 0)
	{
		if(pipe(stdoutFds) < 0)
		{
			if((flags & ProcessStart_RedirectStdin) != 0)
			{
				close(stdinFds[0]);
				close(stdinFds[1]);
			}
			return 0;
		}
	#if HAVE_FCNTL
		fcntl(stdoutFds[0], F_SETFD, 1);
	#endif
		*stdoutHandle = (ILNativeInt)(stdoutFds[0]);
	}
	if((flags & ProcessStart_RedirectStderr) != 0)
	{
		if(pipe(stderrFds) < 0)
		{
			if((flags & ProcessStart_RedirectStdin) != 0)
			{
				close(stdinFds[0]);
				close(stdinFds[1]);
			}
			if((flags & ProcessStart_RedirectStdout) != 0)
			{
				close(stdoutFds[0]);
				close(stdoutFds[1]);
			}
			return 0;
		}
	#if HAVE_FCNTL
		fcntl(stderrFds[0], F_SETFD, 1);
	#endif
		*stderrHandle = (ILNativeInt)(stderrFds[0]);
	}

	/* Open the pipe for returning errno */
	if(pipe(pipefds) < 0)
	{
		return 0;
	}
	
	/* Fork and execute the process */
	*processID = -1;
	*processHandle = 0;
	pid = fork();
	if(pid == 0)
	{
		/* We are in the child process */
		if((flags & ProcessStart_RedirectStdin) != 0)
		{
			dup2(stdinFds[0], 0);
			close(stdinFds[0]);
		}
		if((flags & ProcessStart_RedirectStdout) != 0)
		{
			dup2(stdoutFds[1], 1);
			close(stdoutFds[1]);
		}
		if((flags & ProcessStart_RedirectStderr) != 0)
		{
			dup2(stderrFds[1], 2);
			close(stderrFds[1]);
		}
		if(newEnviron)
		{
			extern char **environ;
			environ = newEnviron;
		}
		close(pipefds[0]);
		
	#ifdef HAVE_FCNTL
		fcntl(pipefds[1],F_SETFD,1);
	#endif
		if(workdir)
		{
			if(ILChangeDir(workdir) != IL_ERRNO_Success)
			{
				/* Send errno to parent process */
				write(pipefds[1],&errno, sizeof(errno));
				exit(1);
			}
		}

		execvp(fname, args);
		write(pipefds[1],&errno, sizeof(errno));
		exit(1);
	}
	else if(pid > 0)
	{
		/* We are in the parent process */
		if((flags & ProcessStart_RedirectStdin) != 0)
		{
			close(stdinFds[0]);
		}
		if((flags & ProcessStart_RedirectStdout) != 0)
		{
			close(stdoutFds[1]);
		}
		if((flags & ProcessStart_RedirectStderr) != 0)
		{
			close(stderrFds[1]);
		}
		*processID = (ILInt32)pid;
		close(pipefds[1]);
		errno = 0;
		read(pipefds[0],&errno,sizeof(errno));
		close(pipefds[0]);
		result = (errno == 0);
	}
	else
	{
		/* An error occurred during the fork */
		if((flags & ProcessStart_RedirectStdin) != 0)
		{
			close(stdinFds[0]);
			close(stdinFds[1]);
		}
		if((flags & ProcessStart_RedirectStdout) != 0)
		{
			close(stdoutFds[0]);
			close(stdoutFds[1]);
		}
		if((flags & ProcessStart_RedirectStderr) != 0)
		{
			close(stderrFds[0]);
			close(stderrFds[1]);
		}
		close(pipefds[0]);
		close(pipefds[1]);
	}

	/* Clean up and exit */
	FreeStringList(args, argc);
	FreeStringList(newEnviron, varNum);
	return result;

#else
	/* Don't know how to spawn processes on this platform */
	return 0;
#endif
}
Exemplo n.º 15
0
int csync_rs_patch(const char *filename)
{
	FILE *basis_file = 0, *delta_file = 0, *new_file = 0;
	int backup_errno;
	rs_stats_t stats;
	rs_result result;
	char *errstr = "?";
	char tmpfname[MAXPATHLEN], newfname[MAXPATHLEN];

	csync_debug(3, "Csync2 / Librsync: csync_rs_patch('%s')\n", filename);

	csync_debug(3, "Receiving delta_file from peer..\n");
	delta_file = open_temp_file(tmpfname, prefixsubst(filename));
	if ( !delta_file ) { errstr="creating delta temp file"; goto io_error; }
	if (unlink(tmpfname) < 0) { errstr="removing delta temp file"; goto io_error; }
	if ( csync_recv_file(delta_file) ) goto error;

	csync_debug(3, "Opening to be patched file on local host..\n");
	basis_file = fopen(prefixsubst(filename), "rb");
	if ( !basis_file ) {
		basis_file = open_temp_file(tmpfname, prefixsubst(filename));
		if ( !basis_file ) { errstr="opening data file for reading"; goto io_error; }
		if (unlink(tmpfname) < 0) { errstr="removing data temp file"; goto io_error; }
	}

	csync_debug(3, "Opening temp file for new data on local host..\n");
	new_file = open_temp_file(newfname, prefixsubst(filename));
	if ( !new_file ) { errstr="creating new data temp file"; goto io_error; }

	csync_debug(3, "Running rs_patch_file() from librsync..\n");
	result = rs_patch_file(basis_file, delta_file, new_file, &stats);
	if (result != RS_DONE) {
		csync_debug(0, "Internal error from rsync library!\n");
		goto error;
	}

	csync_debug(3, "Renaming tmp file to data file..\n");
	fclose(basis_file);

#ifdef __CYGWIN__

/* TODO: needed? */
	// This creates the file using the native windows API, bypassing
	// the cygwin wrappers and so making sure that we do not mess up the
	// permissions..
	{
		char winfilename[MAX_PATH];
		HANDLE winfh;

		cygwin_conv_to_win32_path(prefixsubst(filename), winfilename);

		winfh = CreateFile(TEXT(winfilename),
				GENERIC_WRITE,          // open for writing
				0,                      // do not share
				NULL,                   // default security
				CREATE_ALWAYS,          // overwrite existing
				FILE_ATTRIBUTE_NORMAL | // normal file
				FILE_FLAG_OVERLAPPED,   // asynchronous I/O
				NULL);                  // no attr. template

		if (winfh == INVALID_HANDLE_VALUE) {
			csync_debug(0, "Win32 I/O Error %d in rsync-patch: %s\n",
					(int)GetLastError(), winfilename);
			errno = EACCES;
			goto error;
		}
		CloseHandle(winfh);
	}
#endif

	if (rename(newfname, prefixsubst(filename)) < 0) { errstr="renaming tmp file to to be patched file"; goto io_error; }

	csync_debug(3, "File has been patched successfully.\n");
	fclose(delta_file);
	fclose(new_file);

	return 0;

io_error:
	csync_debug(0, "I/O Error '%s' while %s in rsync-patch: %s\n",
			strerror(errno), errstr, prefixsubst(filename));

error:;
	backup_errno = errno;
	if ( delta_file ) fclose(delta_file);
	if ( basis_file ) fclose(basis_file);
	if ( new_file )   fclose(new_file);
	errno = backup_errno;
	return -1;
}
Exemplo n.º 16
0
csLibraryHandle csLoadLibrary (const char* iName)
{
  csLibraryHandle handle;
  DWORD errorCode;

  CS_ALLOC_STACK_ARRAY (char, dllPath, strlen (iName) + 5);
  strcpy (dllPath, iName);
  char* dot = strrchr (dllPath, '.');
  if ((!dot) || (strcasecmp (dot, ".dll") != 0))
  {
    if (dot && (strcasecmp (dot, ".csplugin") == 0))
    {
      strcpy (dot, ".dll");
    }
    else
    {
      strcat (dllPath, ".dll");
    }
  }

  handle = LoadLibraryEx (dllPath, 0, LOADLIBEX_FLAGS);
  errorCode = GetLastError();

#ifdef __CYGWIN__
 // A load attempt might fail if the DLL depends implicitly upon some other
 // DLLs which reside in the Cygwin /bin directory.  To deal with this case, we
 // add the Cygwin /bin directory to the PATH environment variable and retry.
 if (handle == 0)
 {
   char *OLD_PATH = new char[4096];
   char *DLLDIR = new char[1024];
   GetEnvironmentVariable("PATH", OLD_PATH, 4096);
   if (cygwin_conv_to_win32_path ("/bin/",DLLDIR))
   {
     ErrorMessages.Push(
       "LoadLibraryEx() '/bin/' Cygwin/Win32 path conversion failed.");
     delete[] DLLDIR;
     delete[] OLD_PATH;
     return 0;
   }
   SetEnvironmentVariable("PATH", DLLDIR);
   handle = LoadLibraryEx (dllPath, 0, LOADLIBEX_FLAGS);
   errorCode = GetLastError();
   SetEnvironmentVariable("PATH", OLD_PATH);
   delete[] DLLDIR;
   delete[] OLD_PATH;
 }
#endif

  if (handle == 0)
  {
    char *buf = cswinGetErrorMessage (errorCode);
    csString s;
    s << "LoadLibraryEx(" << dllPath << ") error " << (int)errorCode << ": "
      << buf;
    ErrorMessages.Push (s);
    delete[] buf;
    return 0;
  }

  typedef const char* (*pfnGetPluginCompiler)();
  pfnGetPluginCompiler get_plugin_compiler = 
    (pfnGetPluginCompiler) csGetLibrarySymbol (handle, "plugin_compiler");
  if (!get_plugin_compiler)
  {
    csString s;
    s << dllPath << ": DLL does not export \"plugin_compiler\".";
    ErrorMessages.Push (s);
    FreeLibrary ((HMODULE)handle);
    return 0;
  }
  const char* plugin_compiler = get_plugin_compiler();
  if (strcmp(plugin_compiler, CS_COMPILER_NAME) != 0)
  {
    csString s;
    s << dllPath << ": plugin compiler does not match application compiler: "
      << plugin_compiler << " != " CS_COMPILER_NAME;
    ErrorMessages.Push (s);
    FreeLibrary ((HMODULE)handle);
    return 0;
  }

  return handle;
}