int main ( int argc, char **argv )
{
    g_type_init();
    Display *display;

    // catch help request
    if ( find_arg( argc, argv, "-help" ) >= 0
         || find_arg( argc, argv, "--help" ) >= 0
         || find_arg( argc, argv, "-h" ) >= 0 ) {
        help();
        return EXIT_SUCCESS;
    }

    // Get DISPLAY
    const char *display_str= getenv( "DISPLAY" );

    if ( !( display = XOpenDisplay( display_str ) ) ) {
        fprintf( stderr, "cannot open display!\n" );
        return EXIT_FAILURE;
    }

    // Setup error handler.
    XSync( display, False );
    xerror = XSetErrorHandler( X11_oops );
    XSync( display, False );

    // Initialize renderer
    renderer_init( display );

    // Get monitor layout. (xinerama aware)
    MMB_Screen *mmb_screen = mmb_screen_create( display );


    // Check input file.
    char *image_file = NULL;
    find_arg_str( argc, argv, "-input", &image_file );

    if ( image_file ) {
        int clip = ( find_arg( argc, argv, "-clip" ) >= 0 );
        GdkPixbuf *pb = renderer_create_empty_background( mmb_screen );


        if ( renderer_overlay_wallpaper( pb, image_file, mmb_screen,clip ) ) {
            char *output_file = NULL;
            find_arg_str( argc, argv, "-output", &output_file );

            if ( output_file ) {
                renderer_store_image( pb, output_file );
            } else {
                renderer_update_X11_background( display, pb );
            }
        }

        g_object_unref( pb );
    }

    // Print layout
    if ( find_arg( argc, argv, "-print" ) >= 0 ) {
        mmb_screen_print( mmb_screen );
    }

    // Cleanup
    mmb_screen_free( &mmb_screen );
    XCloseDisplay( display );
}
Example #2
0
int
main (int argc, char **argv)
{
    int opt;

#define LIB_GL_OPT	(CHAR_MAX + 1)
#define LIB_EGL_OPT	(CHAR_MAX + 2)
#define DEBUG_CTX_OPT	(CHAR_MAX + 3)
#define REMOTE_OPT	(CHAR_MAX + 4)

    /* The initial '+' means that getopt will stop looking for
     * options after the first non-option argument. */
    const char *short_options="+h";
    const struct option long_options[] = {
	{"help",	    no_argument,	0, 'h'},
#ifdef SUPPORT_GL
	{"libgl",	    optional_argument,	0, LIB_GL_OPT},
	{"libegl",	    optional_argument,	0, LIB_EGL_OPT},
	{"debug-context",   no_argument,	0, DEBUG_CTX_OPT},
#endif
#ifdef SUPPORT_WEBUI
	{"remote",	    no_argument,	0, REMOTE_OPT},
#endif
	{0, 0, 0, 0}
    };
    const char *prev_ld_library_path;
    char *ld_library_path;
    char *gputop_system_args[] = {
	"gputop-system",
	NULL
    };
    char **args = argv;
    int err;
    int i;


    while ((opt = getopt_long(argc, argv, short_options, long_options, NULL))
	   != -1)
    {
	switch (opt) {
	    case 'h':
		usage();
		return 0;
	    case LIB_GL_OPT:
		setenv("GPUTOP_GL_LIBRARY", optarg, true);
		break;
	    case LIB_EGL_OPT:
		setenv("GPUTOP_EGL_LIBRARY", optarg, true);
		break;
	    case DEBUG_CTX_OPT:
		setenv("GPUTOP_FORCE_DEBUG_CONTEXT", "1", true);
		break;
	    case REMOTE_OPT:
		setenv("GPUTOP_MODE", "remote", true);
		break;
	    default:
		fprintf (stderr, "Internal error: "
			 "unexpected getopt value: %d\n", opt);
		exit (1);
	}
    }

    if (optind >= argc) {
	/* If no program is given then launch a dummy "test
	 * application" so gputop can also be used for analysing
	 * system wide metrics. */
	args = gputop_system_args;
	optind = 0;
    }

    if (!getenv("GPUTOP_GL_LIBRARY"))
        resolve_lib_path_for_env("libGL.so.1", "glClear", "GPUTOP_GL_LIBRARY");

    if (!getenv("GPUTOP_EGL_LIBRARY"))
        resolve_lib_path_for_env("libEGL.so.1", "eglGetDisplay", "GPUTOP_EGL_LIBRARY");

    prev_ld_library_path = getenv("LD_LIBRARY_PATH");
    if (!prev_ld_library_path)
	prev_ld_library_path = "";

    asprintf(&ld_library_path, "%s:%s", GPUTOP_WRAPPER_DIR, prev_ld_library_path);
    setenv("LD_LIBRARY_PATH", ld_library_path, true);
    free(ld_library_path);

    execvp(args[optind], &args[optind]);
    err = errno;

    fprintf(stderr, "gputop: Failed to run GL application: \n\n"
	    "  ");
    for (i = optind; i < argc; i++)
	fprintf(stderr, "%s ", args[i]);
    fprintf(stderr, "\n\n%s\n", strerror(err));

    return 0;
}
Example #3
0
/**
 * Tries to locate and load VBoxCAPI.so/dylib/dll, resolving all the related
 * function pointers.
 *
 * @returns 0 on success, -1 on failure.
 *
 * @remark  This should be considered moved into a separate glue library since
 *          its its going to be pretty much the same for any user of VBoxCAPI
 *          and it will just cause trouble to have duplicate versions of this
 *          source code all around the place.
 */
int VBoxCGlueInit(void)
{
    const char *pszHome;

    memset(g_szVBoxErrMsg, 0, sizeof(g_szVBoxErrMsg));

    /*
     * If the user specifies the location, try only that.
     */
    pszHome = getenv("VBOX_APP_HOME");
    if (pszHome)
        return tryLoadLibrary(pszHome, 0);

    /*
     * Try the known standard locations.
     */
#if defined(__gnu__linux__) || defined(__linux__)
    if (tryLoadLibrary("/opt/VirtualBox", 1) == 0)
        return 0;
    if (tryLoadLibrary("/usr/lib/virtualbox", 1) == 0)
        return 0;
#elif defined(__sun__)
    if (tryLoadLibrary("/opt/VirtualBox/amd64", 1) == 0)
        return 0;
    if (tryLoadLibrary("/opt/VirtualBox/i386", 1) == 0)
        return 0;
#elif defined(__APPLE__)
    if (tryLoadLibrary("/Application/VirtualBox.app/Contents/MacOS", 1) == 0)
        return 0;
#elif defined(__FreeBSD__)
    if (tryLoadLibrary("/usr/local/lib/virtualbox", 1) == 0)
        return 0;
#elif defined(__OS2__)
    if (tryLoadLibrary("C:/Apps/VirtualBox", 1) == 0)
        return 0;
#elif defined(WIN32)
    pszHome = getenv("ProgramFiles");
    if (pszHome)
    {
        char szPath[4096];
        size_t cb = sizeof(szPath);
        char *tmp = szPath;
        strncpy(tmp, pszHome, cb);
        tmp[cb - 1] = '\0';
        cb -= strlen(tmp);
        tmp += strlen(tmp);
        strncpy(tmp, "/Oracle/VirtualBox", cb);
        tmp[cb - 1] = '\0';
        if (tryLoadLibrary(szPath, 1) == 0)
            return 0;
    }
    if (tryLoadLibrary("C:/Program Files/Oracle/VirtualBox", 1) == 0)
        return 0;
#else
# error "port me"
#endif

    /*
     * Finally try the dynamic linker search path.
     */
    if (tryLoadLibrary(NULL, 1) == 0)
        return 0;

    /* No luck, return failure. */
    return -1;
}
Example #4
0
File: linker.cpp Project: smolt/ldc
int executeMsvcToolAndWait(const std::string &tool,
                           const std::vector<std::string> &args, bool verbose) {
  llvm::SmallString<1024> commandLine; // full command line incl. executable

  // if the VSINSTALLDIR environment variable is NOT set,
  // the MSVC environment needs to be set up
  const bool needMsvcSetup = !getenv("VSINSTALLDIR");
  if (needMsvcSetup) {
    /* <command line> => %ComSpec% /s /c "<batch file> <command line>"
     *
     * cmd.exe /c treats the following string argument (the command)
     * in a very peculiar way if it starts with a double-quote.
     * By adding /s and enclosing the command in extra double-quotes
     * (WITHOUT additionally escaping the command), the command will
     * be parsed properly.
     */

    auto comspecEnv = getenv("ComSpec");
    if (!comspecEnv) {
      warning(Loc(), "'ComSpec' environment variable is not set, assuming 'cmd.exe'.");
      comspecEnv = "cmd.exe";
    }
    std::string cmdExecutable = comspecEnv;
    std::string batchFile = exe_path::prependBinDir(
        global.params.targetTriple.isArch64Bit() ? "amd64.bat" : "x86.bat");

    commandLine.append(windows::quoteArg(cmdExecutable));
    commandLine.append(" /s /c \"");
    commandLine.append(windows::quoteArg(batchFile));
    commandLine.push_back(' ');
    commandLine.append(windows::quoteArg(tool));
  } else {
    std::string toolPath = getProgram(tool.c_str());
    commandLine.append(windows::quoteArg(toolPath));
  }

  const size_t commandLineLengthAfterTool = commandLine.size();

  // append (quoted) args
  for (size_t i = 0; i < args.size(); ++i) {
    commandLine.push_back(' ');
    commandLine.append(windows::quoteArg(args[i]));
  }

  const bool useResponseFile = (!args.empty() && commandLine.size() > 2000);
  llvm::SmallString<128> responseFilePath;
  if (useResponseFile) {
    const size_t firstArgIndex = commandLineLengthAfterTool + 1;
    llvm::StringRef content(commandLine.data() + firstArgIndex,
                            commandLine.size() - firstArgIndex);

    if (llvm::sys::fs::createTemporaryFile("ldc_link", "rsp",
                                           responseFilePath) ||
        llvm::sys::writeFileWithEncoding(
            responseFilePath,
            content)) // keep encoding (LLVM assumes UTF-8 input)
    {
      error(Loc(), "cannot write temporary response file for %s", tool.c_str());
      return -1;
    }

    // replace all args by @<responseFilePath>
    std::string responseFileArg = ("@" + responseFilePath).str();
    commandLine.resize(firstArgIndex);
    commandLine.append(windows::quoteArg(responseFileArg));
  }

  if (needMsvcSetup)
    commandLine.push_back('"');

  const char *finalCommandLine = commandLine.c_str();

  if (verbose) {
    fprintf(global.stdmsg, finalCommandLine);
    fprintf(global.stdmsg, "\n");
    fflush(global.stdmsg);
  }

  const int exitCode = windows::executeAndWait(finalCommandLine);

  if (exitCode != 0) {
    commandLine.resize(commandLineLengthAfterTool);
    if (needMsvcSetup)
      commandLine.push_back('"');
    error(Loc(), "`%s` failed with status: %d", commandLine.c_str(), exitCode);
  }

  if (useResponseFile)
    llvm::sys::fs::remove(responseFilePath);

  return exitCode;
}
Example #5
0
/* initialize controller */
struct nvstusb_context *
nvstusb_init(char const * fw) 
{
  /* initialize usb */
  if (!nvstusb_usb_init()) return 0;

  /* open device */
  struct nvstusb_usb_device *dev = nvstusb_usb_open_device(fw? fw : "nvstusb.fw");
  if (0 == dev) return 0;

  /* allocate context */
  struct nvstusb_context *ctx = malloc(sizeof(*ctx));
  if (0 == ctx) {
    fprintf(stderr, "nvstusb: Could not allocate %d bytes for nvstusb_context...\n", (int)sizeof(*ctx));
    nvstusb_usb_close_device(dev);
    nvstusb_usb_deinit();
    return 0;
  }
  ctx->rate = 0.0;
  ctx->eye = 0;
  ctx->device = dev;
  ctx->vblank_method = 0;
  ctx->toggled3D = 0;
  ctx->invert_eyes = 0;
  ctx->b_thread_running = 0;


  /* Vblank init */
  /* NVIDIA VBlank syncing environment variable defined, signal it and disable
   * any attempt to application side method */
  if (getenv ("__GL_SYNC_TO_VBLANK"))
  {
    fprintf (stderr, "__GL_SYNC_TO_VBLANK defined in environment\n");
    ctx->vblank_method = 2;
    goto out_err;
  }

  /* Swap interval */
  glXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC)glXGetProcAddress("glXSwapIntervalSGI");

  if (NULL != glXSwapIntervalSGI) {
    fprintf(stderr, "nvstusb: forcing vsync\n");
    ctx->vblank_method = 3;
  }

  /* Sync Video */
  glXGetVideoSyncSGI = (PFNGLXGETVIDEOSYNCSGIPROC)glXGetProcAddress("glXGetVideoSyncSGI");
  glXWaitVideoSyncSGI = (PFNGLXWAITVIDEOSYNCSGIPROC)glXGetProcAddress("glXWaitVideoSyncSGI");
  if (NULL == glXWaitVideoSyncSGI) {
    glXGetVideoSyncSGI = 0;
  } else {
    ctx->vblank_method = 1;
  }

  if (NULL != glXGetVideoSyncSGI ) {
    fprintf(stderr, "nvstusb: GLX_SGI_video_sync supported!\n");
  }

  fprintf(stderr, "nvstusb:selected vblank method: %d\n", ctx->vblank_method);
out_err:
  return ctx;
}
Example #6
0
/* Find and parse the SystemVersion.plist file. */
static void parseSystemVersionPList(void *Unused) {
  (void)Unused;
  /* Load CoreFoundation dynamically */
  const void *NullAllocator = dlsym(RTLD_DEFAULT, "kCFAllocatorNull");
  if (!NullAllocator)
    return;
  const CFAllocatorRef AllocatorNull = *(const CFAllocatorRef *)NullAllocator;
  CFDataCreateWithBytesNoCopyFuncTy CFDataCreateWithBytesNoCopyFunc =
      (CFDataCreateWithBytesNoCopyFuncTy)dlsym(RTLD_DEFAULT,
                                               "CFDataCreateWithBytesNoCopy");
  if (!CFDataCreateWithBytesNoCopyFunc)
    return;
  CFPropertyListCreateWithDataFuncTy CFPropertyListCreateWithDataFunc =
      (CFPropertyListCreateWithDataFuncTy)dlsym(
          RTLD_DEFAULT, "CFPropertyListCreateWithData");
/* CFPropertyListCreateWithData was introduced only in macOS 10.6+, so it
 * will be NULL on earlier OS versions. */
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
  CFPropertyListCreateFromXMLDataFuncTy CFPropertyListCreateFromXMLDataFunc =
      (CFPropertyListCreateFromXMLDataFuncTy)dlsym(
          RTLD_DEFAULT, "CFPropertyListCreateFromXMLData");
#pragma clang diagnostic pop
  /* CFPropertyListCreateFromXMLDataFunc is deprecated in macOS 10.10, so it
   * might be NULL in future OS versions. */
  if (!CFPropertyListCreateWithDataFunc && !CFPropertyListCreateFromXMLDataFunc)
    return;
  CFStringCreateWithCStringNoCopyFuncTy CFStringCreateWithCStringNoCopyFunc =
      (CFStringCreateWithCStringNoCopyFuncTy)dlsym(
          RTLD_DEFAULT, "CFStringCreateWithCStringNoCopy");
  if (!CFStringCreateWithCStringNoCopyFunc)
    return;
  CFDictionaryGetValueFuncTy CFDictionaryGetValueFunc =
      (CFDictionaryGetValueFuncTy)dlsym(RTLD_DEFAULT, "CFDictionaryGetValue");
  if (!CFDictionaryGetValueFunc)
    return;
  CFGetTypeIDFuncTy CFGetTypeIDFunc =
      (CFGetTypeIDFuncTy)dlsym(RTLD_DEFAULT, "CFGetTypeID");
  if (!CFGetTypeIDFunc)
    return;
  CFStringGetTypeIDFuncTy CFStringGetTypeIDFunc =
      (CFStringGetTypeIDFuncTy)dlsym(RTLD_DEFAULT, "CFStringGetTypeID");
  if (!CFStringGetTypeIDFunc)
    return;
  CFStringGetCStringFuncTy CFStringGetCStringFunc =
      (CFStringGetCStringFuncTy)dlsym(RTLD_DEFAULT, "CFStringGetCString");
  if (!CFStringGetCStringFunc)
    return;
  CFReleaseFuncTy CFReleaseFunc =
      (CFReleaseFuncTy)dlsym(RTLD_DEFAULT, "CFRelease");
  if (!CFReleaseFunc)
    return;

  char *PListPath = "/System/Library/CoreServices/SystemVersion.plist";

#if TARGET_OS_SIMULATOR
  char *PListPathPrefix = getenv("IPHONE_SIMULATOR_ROOT");
  if (!PListPathPrefix)
    return;
  char FullPath[strlen(PListPathPrefix) + strlen(PListPath) + 1];
  strcpy(FullPath, PListPathPrefix);
  strcat(FullPath, PListPath);
  PListPath = FullPath;
#endif
  FILE *PropertyList = fopen(PListPath, "r");
  if (!PropertyList)
    return;

  /* Dynamically allocated stuff. */
  CFDictionaryRef PListRef = NULL;
  CFDataRef FileContentsRef = NULL;
  UInt8 *PListBuf = NULL;

  fseek(PropertyList, 0, SEEK_END);
  long PListFileSize = ftell(PropertyList);
  if (PListFileSize < 0)
    goto Fail;
  rewind(PropertyList);

  PListBuf = malloc((size_t)PListFileSize);
  if (!PListBuf)
    goto Fail;

  size_t NumRead = fread(PListBuf, 1, (size_t)PListFileSize, PropertyList);
  if (NumRead != (size_t)PListFileSize)
    goto Fail;

  /* Get the file buffer into CF's format. We pass in a null allocator here *
   * because we free PListBuf ourselves */
  FileContentsRef = (*CFDataCreateWithBytesNoCopyFunc)(
      NULL, PListBuf, (CFIndex)NumRead, AllocatorNull);
  if (!FileContentsRef)
    goto Fail;

  if (CFPropertyListCreateWithDataFunc)
    PListRef = (*CFPropertyListCreateWithDataFunc)(
        NULL, FileContentsRef, CF_PROPERTY_LIST_IMMUTABLE, NULL, NULL);
  else
    PListRef = (*CFPropertyListCreateFromXMLDataFunc)(
        NULL, FileContentsRef, CF_PROPERTY_LIST_IMMUTABLE, NULL);
  if (!PListRef)
    goto Fail;

  CFStringRef ProductVersion = (*CFStringCreateWithCStringNoCopyFunc)(
      NULL, "ProductVersion", CF_STRING_ENCODING_ASCII, AllocatorNull);
  if (!ProductVersion)
    goto Fail;
  CFTypeRef OpaqueValue = (*CFDictionaryGetValueFunc)(PListRef, ProductVersion);
  (*CFReleaseFunc)(ProductVersion);
  if (!OpaqueValue ||
      (*CFGetTypeIDFunc)(OpaqueValue) != (*CFStringGetTypeIDFunc)())
    goto Fail;

  char VersionStr[32];
  if (!(*CFStringGetCStringFunc)((CFStringRef)OpaqueValue, VersionStr,
                                 sizeof(VersionStr), CF_STRING_ENCODING_UTF8))
    goto Fail;
  sscanf(VersionStr, "%d.%d.%d", &GlobalMajor, &GlobalMinor, &GlobalSubminor);

Fail:
  if (PListRef)
    (*CFReleaseFunc)(PListRef);
  if (FileContentsRef)
    (*CFReleaseFunc)(FileContentsRef);
  free(PListBuf);
  fclose(PropertyList);
}
Example #7
0
void
gcov_exit (void)
{
  struct gcov_info *gi_ptr;
  const struct gcov_fn_info *gfi_ptr;
  struct gcov_summary this_prg; /* summary for program.  */
  struct gcov_summary all_prg;  /* summary for all instances of program.  */
  struct gcov_ctr_summary *cs_ptr;
  const struct gcov_ctr_info *ci_ptr;
  unsigned t_ix;
  int f_ix;
  gcov_unsigned_t c_num;
  const char *gcov_prefix;
  int gcov_prefix_strip = 0;
  size_t prefix_length;
  char *gi_filename, *gi_filename_up;
  gcov_unsigned_t crc32 = 0;

  /* Prevent the counters from being dumped a second time on exit when the
     application already wrote out the profile using __gcov_dump().  */
  if (gcov_dump_complete)
    return;

  memset (&all_prg, 0, sizeof (all_prg));
  /* Find the totals for this execution.  */
  memset (&this_prg, 0, sizeof (this_prg));
  for (gi_ptr = gcov_list; gi_ptr; gi_ptr = gi_ptr->next)
    {
      crc32 = crc32_unsigned (crc32, gi_ptr->stamp);
      crc32 = crc32_unsigned (crc32, gi_ptr->n_functions);
      
      for (f_ix = 0; (unsigned)f_ix != gi_ptr->n_functions; f_ix++)
	{
	  gfi_ptr = gi_ptr->functions[f_ix];

	  if (gfi_ptr && gfi_ptr->key != gi_ptr)
	    gfi_ptr = 0;
	  
	  crc32 = crc32_unsigned (crc32, gfi_ptr ? gfi_ptr->cfg_checksum : 0);
	  crc32 = crc32_unsigned (crc32,
				  gfi_ptr ? gfi_ptr->lineno_checksum : 0);
	  if (!gfi_ptr)
	    continue;

	  ci_ptr = gfi_ptr->ctrs;
	  for (t_ix = 0; t_ix != GCOV_COUNTERS_SUMMABLE; t_ix++)
	    {
	      if (!gi_ptr->merge[t_ix])
		continue;

	      cs_ptr = &this_prg.ctrs[t_ix];
	      cs_ptr->num += ci_ptr->num;
	      crc32 = crc32_unsigned (crc32, ci_ptr->num);
	      
	      for (c_num = 0; c_num < ci_ptr->num; c_num++)
		{
		  cs_ptr->sum_all += ci_ptr->values[c_num];
		  if (cs_ptr->run_max < ci_ptr->values[c_num])
		    cs_ptr->run_max = ci_ptr->values[c_num];
		}
	      ci_ptr++;
	    }
	}
    }

  {
    /* Check if the level of dirs to strip off specified. */
    char *tmp = getenv("GCOV_PREFIX_STRIP");
    if (tmp)
      {
	gcov_prefix_strip = atoi (tmp);
	/* Do not consider negative values. */
	if (gcov_prefix_strip < 0)
	  gcov_prefix_strip = 0;
      }
  }

  /* Get file name relocation prefix.  Non-absolute values are ignored. */
  gcov_prefix = getenv("GCOV_PREFIX");
  if (gcov_prefix)
    {
      prefix_length = strlen(gcov_prefix);

      /* Remove an unnecessary trailing '/' */
      if (IS_DIR_SEPARATOR (gcov_prefix[prefix_length - 1]))
	prefix_length--;
    }
  else
    prefix_length = 0;

  /* If no prefix was specified and a prefix stip, then we assume
     relative.  */
  if (gcov_prefix_strip != 0 && prefix_length == 0)
    {
      gcov_prefix = ".";
      prefix_length = 1;
    }
  /* Allocate and initialize the filename scratch space plus one.  */
  gi_filename = (char *) alloca (prefix_length + gcov_max_filename + 2);
  if (prefix_length)
    memcpy (gi_filename, gcov_prefix, prefix_length);
  gi_filename_up = gi_filename + prefix_length;

  /* Now merge each file.  */
  for (gi_ptr = gcov_list; gi_ptr; gi_ptr = gi_ptr->next)
    {
      unsigned n_counts;
      struct gcov_summary prg; /* summary for this object over all
				  program.  */
      struct gcov_ctr_summary *cs_prg, *cs_tprg, *cs_all;
      int error = 0;
      gcov_unsigned_t tag, length;
      gcov_position_t summary_pos = 0;
      gcov_position_t eof_pos = 0;
      const char *fname, *s;
      struct gcov_fn_buffer *fn_buffer = 0;
      struct gcov_fn_buffer **fn_tail = &fn_buffer;

      fname = gi_ptr->filename;

      /* Avoid to add multiple drive letters into combined path.  */
      if (prefix_length != 0 && HAS_DRIVE_SPEC(fname))
        fname += 2;

      /* Build relocated filename, stripping off leading
         directories from the initial filename if requested. */
      if (gcov_prefix_strip > 0)
        {
          int level = 0;
          s = fname;
          if (IS_DIR_SEPARATOR(*s))
            ++s;

          /* Skip selected directory levels. */
	  for (; (*s != '\0') && (level < gcov_prefix_strip); s++)
	    if (IS_DIR_SEPARATOR(*s))
	      {
		fname = s;
		level++;
	      }
        }

      /* Update complete filename with stripped original. */
      if (prefix_length != 0 && !IS_DIR_SEPARATOR (*fname))
        {
          /* If prefix is given, add directory separator.  */
	  strcpy (gi_filename_up, "/");
	  strcpy (gi_filename_up + 1, fname);
	}
      else
        strcpy (gi_filename_up, fname);

      if (!gcov_open (gi_filename))
	{
	  /* Open failed likely due to missed directory.
	     Create directory and retry to open file. */
          if (create_file_directory (gi_filename))
	    {
	      fprintf (stderr, "profiling:%s:Skip\n", gi_filename);
	      continue;
	    }
	  if (!gcov_open (gi_filename))
	    {
              fprintf (stderr, "profiling:%s:Cannot open\n", gi_filename);
	      continue;
	    }
	}

      tag = gcov_read_unsigned ();
      if (tag)
	{
	  /* Merge data from file.  */
	  if (tag != GCOV_DATA_MAGIC)
	    {
	      fprintf (stderr, "profiling:%s:Not a gcov data file\n",
		       gi_filename);
	      goto read_fatal;
	    }
	  length = gcov_read_unsigned ();
	  if (!gcov_version (gi_ptr, length, gi_filename))
	    goto read_fatal;

	  length = gcov_read_unsigned ();
	  if (length != gi_ptr->stamp)
	    /* Read from a different compilation. Overwrite the file.  */
	    goto rewrite;

	  /* Look for program summary.  */
	  for (f_ix = 0;;)
	    {
	      struct gcov_summary tmp;
	      
	      eof_pos = gcov_position ();
	      tag = gcov_read_unsigned ();
	      if (tag != GCOV_TAG_PROGRAM_SUMMARY)
		break;

	      f_ix--;
	      length = gcov_read_unsigned ();
	      if (length != GCOV_TAG_SUMMARY_LENGTH)
		goto read_mismatch;
	      gcov_read_summary (&tmp);
	      if ((error = gcov_is_error ()))
		goto read_error;
	      if (summary_pos || tmp.checksum != crc32)
		goto next_summary;
	      
	      for (t_ix = 0; t_ix != GCOV_COUNTERS_SUMMABLE; t_ix++)
		if (tmp.ctrs[t_ix].num != this_prg.ctrs[t_ix].num)
		  goto next_summary;
	      prg = tmp;
	      summary_pos = eof_pos;

	    next_summary:;
	    }
	  
	  /* Merge execution counts for each function.  */
	  for (f_ix = 0; (unsigned)f_ix != gi_ptr->n_functions;
	       f_ix++, tag = gcov_read_unsigned ())
	    {
	      gfi_ptr = gi_ptr->functions[f_ix];

	      if (tag != GCOV_TAG_FUNCTION)
		goto read_mismatch;

	      length = gcov_read_unsigned ();
	      if (!length)
		/* This function did not appear in the other program.
		   We have nothing to merge.  */
		continue;

	      if (length != GCOV_TAG_FUNCTION_LENGTH)
		goto read_mismatch;
	      
	      if (!gfi_ptr || gfi_ptr->key != gi_ptr)
		{
		  /* This function appears in the other program.  We
		     need to buffer the information in order to write
		     it back out -- we'll be inserting data before
		     this point, so cannot simply keep the data in the
		     file.  */
		  fn_tail = buffer_fn_data (gi_filename,
					    gi_ptr, fn_tail, f_ix);
		  if (!fn_tail)
		    goto read_mismatch;
		  continue;
		}

	      length = gcov_read_unsigned ();
	      if (length != gfi_ptr->ident)
		goto read_mismatch;
	      
	      length = gcov_read_unsigned ();
	      if (length != gfi_ptr->lineno_checksum)
		goto read_mismatch;
	      
	      length = gcov_read_unsigned ();
	      if (length != gfi_ptr->cfg_checksum)
		goto read_mismatch;
	      
	      ci_ptr = gfi_ptr->ctrs;
	      for (t_ix = 0; t_ix < GCOV_COUNTERS; t_ix++)
		{
		  gcov_merge_fn merge = gi_ptr->merge[t_ix];

		  if (!merge)
		    continue;

		  tag = gcov_read_unsigned ();
		  length = gcov_read_unsigned ();
		  if (tag != GCOV_TAG_FOR_COUNTER (t_ix)
		      || length != GCOV_TAG_COUNTER_LENGTH (ci_ptr->num))
		    goto read_mismatch;
		  (*merge) (ci_ptr->values, ci_ptr->num);
		  ci_ptr++;
		}
	      if ((error = gcov_is_error ()))
		goto read_error;
	    }

	  if (tag)
	    {
	    read_mismatch:;
	      fprintf (stderr, "profiling:%s:Merge mismatch for %s %u\n",
		       gi_filename, f_ix >= 0 ? "function" : "summary",
		       f_ix < 0 ? -1 - f_ix : f_ix);
	      goto read_fatal;
	    }
	}
      goto rewrite;

    read_error:;
      fprintf (stderr, "profiling:%s:%s merging\n", gi_filename,
	       error < 0 ? "Overflow": "Error");

      goto read_fatal;

    rewrite:;
      gcov_rewrite ();
      if (!summary_pos)
	{
	  memset (&prg, 0, sizeof (prg));
	  summary_pos = eof_pos;
	}

      /* Merge the summaries.  */
      for (t_ix = 0; t_ix < GCOV_COUNTERS_SUMMABLE; t_ix++)
	{
	  cs_prg = &prg.ctrs[t_ix];
	  cs_tprg = &this_prg.ctrs[t_ix];
	  cs_all = &all_prg.ctrs[t_ix];

	  if (gi_ptr->merge[t_ix])
	    {
	      if (!cs_prg->runs++)
		cs_prg->num = cs_tprg->num;
	      cs_prg->sum_all += cs_tprg->sum_all;
	      if (cs_prg->run_max < cs_tprg->run_max)
		cs_prg->run_max = cs_tprg->run_max;
	      cs_prg->sum_max += cs_tprg->run_max;
	    }
	  else if (cs_prg->runs)
	    goto read_mismatch;

	  if (!cs_all->runs && cs_prg->runs)
	    memcpy (cs_all, cs_prg, sizeof (*cs_all));
	  else if (!all_prg.checksum
		   && (!GCOV_LOCKED || cs_all->runs == cs_prg->runs)
		   && memcmp (cs_all, cs_prg, sizeof (*cs_all)))
	    {
	      fprintf (stderr, "profiling:%s:Invocation mismatch - some data files may have been removed%s\n",
		       gi_filename, GCOV_LOCKED
		       ? "" : " or concurrently updated without locking support");
	      all_prg.checksum = ~0u;
	    }
	}

      prg.checksum = crc32;

      /* Write out the data.  */
      if (!eof_pos)
	{
	  gcov_write_tag_length (GCOV_DATA_MAGIC, GCOV_VERSION);
	  gcov_write_unsigned (gi_ptr->stamp);
	}

      if (summary_pos)
	gcov_seek (summary_pos);

      /* Generate whole program statistics.  */
      gcov_write_summary (GCOV_TAG_PROGRAM_SUMMARY, &prg);

      if (summary_pos < eof_pos)
	gcov_seek (eof_pos);

      /* Write execution counts for each function.  */
      for (f_ix = 0; (unsigned)f_ix != gi_ptr->n_functions; f_ix++)
	{
	  unsigned buffered = 0;

	  if (fn_buffer && fn_buffer->fn_ix == (unsigned)f_ix)
	    {
	      /* Buffered data from another program.  */
	      buffered = 1;
	      gfi_ptr = &fn_buffer->info;
	      length = GCOV_TAG_FUNCTION_LENGTH;
	    }
	  else
	    {
	      gfi_ptr = gi_ptr->functions[f_ix];
	      if (gfi_ptr && gfi_ptr->key == gi_ptr)
		length = GCOV_TAG_FUNCTION_LENGTH;
	      else
		length = 0;
	    }
	  
	  gcov_write_tag_length (GCOV_TAG_FUNCTION, length);
	  if (!length)
	    continue;
	  
	  gcov_write_unsigned (gfi_ptr->ident);
	  gcov_write_unsigned (gfi_ptr->lineno_checksum);
	  gcov_write_unsigned (gfi_ptr->cfg_checksum);

	  ci_ptr = gfi_ptr->ctrs;
	  for (t_ix = 0; t_ix < GCOV_COUNTERS; t_ix++)
	    {
	      if (!gi_ptr->merge[t_ix])
		continue;

	      n_counts = ci_ptr->num;
	      gcov_write_tag_length (GCOV_TAG_FOR_COUNTER (t_ix),
				     GCOV_TAG_COUNTER_LENGTH (n_counts));
	      gcov_type *c_ptr = ci_ptr->values;
	      while (n_counts--)
		gcov_write_counter (*c_ptr++);
	      ci_ptr++;
	    }
	  if (buffered)
	    fn_buffer = free_fn_data (gi_ptr, fn_buffer, GCOV_COUNTERS);
	}

      gcov_write_unsigned (0);

    read_fatal:;
      while (fn_buffer)
	fn_buffer = free_fn_data (gi_ptr, fn_buffer, GCOV_COUNTERS);

      if ((error = gcov_close ()))
	  fprintf (stderr, error  < 0 ?
		   "profiling:%s:Overflow writing\n" :
		   "profiling:%s:Error writing\n",
		   gi_filename);
    }
}
Example #8
0
File: main.c Project: WndSks/msys
int
main(int argc, char **argv)
{
	int c;
	char *scan;
	/* the + on the front tells GNU getopt not to rearrange argv */
	const char *optlist = "+F:f:v:W;m:D";
	int stopped_early = FALSE;
	int old_optind;
	extern int optind;
	extern int opterr;
	extern char *optarg;
	int i;
	int stdio_problem = FALSE;

	/* do these checks early */
	if (getenv("TIDYMEM") != NULL)
		do_tidy_mem = TRUE;

	if (getenv("WHINY_USERS") != NULL)
		whiny_users = TRUE;

#ifdef HAVE_MCHECK_H
	if (do_tidy_mem)
		mtrace();
#endif /* HAVE_MCHECK_H */
	
#if defined(LC_CTYPE)
	setlocale(LC_CTYPE, "");
#endif
#if defined(LC_COLLATE)
	setlocale(LC_COLLATE, "");
#endif
#if defined(LC_MESSAGES)
	setlocale(LC_MESSAGES, "");
#endif
#if defined(LC_NUMERIC)
	/*
	 * Force the issue here.  According to POSIX 2001, decimal
	 * point is used for parsing source code and for command-line
	 * assignments and the locale value for processing input,
	 * number to string conversion, and printing output.
	 */
	setlocale(LC_NUMERIC, "C");
#endif
#if defined(LC_TIME)
	setlocale(LC_TIME, "");
#endif

#ifdef MBS_SUPPORT
	/*
	 * In glibc, MB_CUR_MAX is actually a function.  This value is
	 * tested *a lot* in many speed-critical places in gawk. Caching
	 * this value once makes a speed difference.
	 */
	gawk_mb_cur_max = MB_CUR_MAX;
	/* Without MBS_SUPPORT, gawk_mb_cur_max is 1. */
#endif

	(void) bindtextdomain(PACKAGE, LOCALEDIR);
	(void) textdomain(PACKAGE);

	(void) signal(SIGFPE, catchsig);
	(void) signal(SIGSEGV, catchsig);
#ifdef SIGBUS
	(void) signal(SIGBUS, catchsig);
#endif

	myname = gawk_name(argv[0]);
        argv[0] = (char *) myname;
	os_arg_fixup(&argc, &argv); /* emulate redirection, expand wildcards */

	/* remove sccs gunk */
	if (strncmp(version_string, "@(#)", 4) == 0)
		version_string += 4;

	if (argc < 2)
		usage(1, stderr);

	/* Robustness: check that file descriptors 0, 1, 2 are open */
	init_fds();

	/* init array handling. */
	array_init();

	/* we do error messages ourselves on invalid options */
	opterr = FALSE;

	/* option processing. ready, set, go! */
	for (optopt = 0, old_optind = 1;
	     (c = getopt_long(argc, argv, optlist, optab, NULL)) != EOF;
	     optopt = 0, old_optind = optind) {
		if (do_posix)
			opterr = TRUE;

		switch (c) {
		case 'F':
			preassigns_add(PRE_ASSIGN_FS, optarg);
			break;

		case 'S':
			disallow_var_assigns = TRUE;
			/* fall through */
		case 'f':
			/*
			 * a la MKS awk, allow multiple -f options.
			 * this makes function libraries real easy.
			 * most of the magic is in the scanner.
			 *
			 * The following is to allow for whitespace at the end
			 * of a #! /bin/gawk line in an executable file
			 */
			scan = optarg;
			if (argv[optind-1] != optarg)
				while (ISSPACE(*scan))
					scan++;
			srcfiles_add(SOURCEFILE,
				(*scan == '\0' ? argv[optind++] : optarg));
			break;

		case 'v':
			preassigns_add(PRE_ASSIGN, optarg);
			break;

		case 'm':
			/*
			 * Research awk extension.
			 *	-mf nnn		set # fields, gawk ignores
			 *	-mr nnn		set record length, ditto
			 */
			if (do_lint)
				lintwarn(_("`-m[fr]' option irrelevant in gawk"));
			if (optarg[0] != 'r' && optarg[0] != 'f')
				warning(_("-m option usage: `-m[fr] nnn'"));
			/*
			 * Set fixed length records for Tandem,
			 * ignored on other platforms (see io.c:get_a_record).
			 */
			if (optarg[0] == 'r') {
				if (ISDIGIT(optarg[1]))
					MRL = atoi(optarg+1);
				else {
					MRL = atoi(argv[optind]);
					optind++;
				}
			} else if (optarg[1] == '\0')
				optind++;
			break;

		case 'W':       /* gawk specific options - now in getopt_long */
			fprintf(stderr, _("%s: option `-W %s' unrecognized, ignored\n"),
				argv[0], optarg);
			break;

		/* These can only come from long form options */
		case 'C':
			copyleft();
			break;

		case 'd':
			do_dump_vars = TRUE;
			if (optarg != NULL && optarg[0] != '\0')
				varfile = optarg;
			break;

		case 'l':
#ifndef NO_LINT
			do_lint = LINT_ALL;
			if (optarg != NULL) {
				if (strcmp(optarg, "fatal") == 0)
					lintfunc = r_fatal;
				else if (strcmp(optarg, "invalid") == 0)
					do_lint = LINT_INVALID;
			}
#endif
			break;

		case 'p':
			do_profiling = TRUE;
			if (optarg != NULL)
				set_prof_file(optarg);
			else
				set_prof_file(DEFAULT_PROFILE);
			break;

		case 's':
			if (optarg[0] == '\0')
				warning(_("empty argument to `--source' ignored"));
			else
				srcfiles_add(CMDLINE, optarg);
			break;

		case 'u':
			usage(0, stdout);	/* per coding stds */
			break;

		case 'V':
			version();
			break;

		case 0:
			/*
			 * getopt_long found an option that sets a variable
			 * instead of returning a letter. Do nothing, just
			 * cycle around for the next one.
			 */
			break;

		case 'D':
#ifdef GAWKDEBUG
			yydebug = 2;
			break;
#endif
			/* if not debugging, fall through */

		case '?':
		default:
			/*
			 * New behavior.  If not posix, an unrecognized
			 * option stops argument processing so that it can
			 * go into ARGV for the awk program to see. This
			 * makes use of ``#! /bin/gawk -f'' easier.
			 *
			 * However, it's never simple. If optopt is set,
			 * an option that requires an argument didn't get the
			 * argument. We care because if opterr is 0, then
			 * getopt_long won't print the error message for us.
			 */
			if (! do_posix
			    && (optopt == '\0' || strchr(optlist, optopt) == NULL)) {
				/*
				 * can't just do optind--. In case of an
				 * option with >= 2 letters, getopt_long
				 * won't have incremented optind.
				 */
				optind = old_optind;
				stopped_early = TRUE;
				goto out;
			} else if (optopt != '\0')
				/* Use 1003.2 required message format */
				fprintf(stderr,
					_("%s: option requires an argument -- %c\n"),
					myname, optopt);
			/* else
				let getopt print error message for us */
			break;
		}
		if (c == 'S')	/* --exec ends option processing */
			break;
	}
out:

	if (do_nostalgia)
		nostalgia();

	/* check for POSIXLY_CORRECT environment variable */
	if (! do_posix && getenv("POSIXLY_CORRECT") != NULL) {
		do_posix = TRUE;
		if (do_lint)
			lintwarn(
	_("environment variable `POSIXLY_CORRECT' set: turning on `--posix'"));
	}

	if (do_posix) {
		if (do_traditional)	/* both on command line */
			warning(_("`--posix' overrides `--traditional'"));
		else
			do_traditional = TRUE;
			/*
			 * POSIX compliance also implies
			 * no GNU extensions either.
			 */
	}

	if (do_traditional && do_non_decimal_data) {
		do_non_decimal_data = FALSE;
		warning(_("`--posix'/`--traditional' overrides `--non-decimal-data'"));
	}

	if (do_lint && os_is_setuid())
		warning(_("running %s setuid root may be a security problem"), myname);

	/*
	 * Force profiling if this is pgawk.
	 * Don't bother if the command line already set profiling up.
	 */
	if (! do_profiling)
		init_profiling(& do_profiling, DEFAULT_PROFILE);

	/* load group set */
	init_groupset();

	/* initialize the null string */
	Nnull_string = make_string("", 0);
	Nnull_string->numbr = 0.0;
	Nnull_string->type = Node_val;
	Nnull_string->flags = (PERM|STRCUR|STRING|NUMCUR|NUMBER);

	/*
	 * Tell the regex routines how they should work.
	 * Do this before initializing variables, since
	 * they could want to do a regexp compile.
	 */
	resetup();

	/* Set up the special variables */
	init_vars();

	/* Set up the field variables */
	init_fields();

	/* Now process the pre-assignments */
	for (i = 0; i <= numassigns; i++)
		if (preassigns[i].stype == PRE_ASSIGN)
			(void) arg_assign(preassigns[i].val, TRUE);
		else	/* PRE_ASSIGN_FS */
			cmdline_fs(preassigns[i].val);
	free(preassigns);

	if ((BINMODE & 1) != 0)
		if (os_setbinmode(fileno(stdin), O_BINARY) == -1)
			fatal(_("can't set binary mode on stdin (%s)"), strerror(errno));
	if ((BINMODE & 2) != 0) {
		if (os_setbinmode(fileno(stdout), O_BINARY) == -1)
			fatal(_("can't set binary mode on stdout (%s)"), strerror(errno));
		if (os_setbinmode(fileno(stderr), O_BINARY) == -1)
			fatal(_("can't set binary mode on stderr (%s)"), strerror(errno));
	}

#ifdef GAWKDEBUG
	setbuf(stdout, (char *) NULL);	/* make debugging easier */
#endif
	if (isatty(fileno(stdout)))
		output_is_tty = TRUE;
	/* No -f or --source options, use next arg */
	if (numfiles == -1) {
		if (optind > argc - 1 || stopped_early) /* no args left or no program */
			usage(1, stderr);
		srcfiles_add(CMDLINE, argv[optind]);
		optind++;
	}

	init_args(optind, argc, (char *) myname, argv);
	(void) tokexpand();

#if defined(LC_NUMERIC)
	/*
	 * FRAGILE!  CAREFUL!
	 * Pre-initing the variables with arg_assign() can change the
	 * locale.  Force it to C before parsing the program.
	 */
	setlocale(LC_NUMERIC, "C");
#endif

	/* Read in the program */
	if (yyparse() != 0 || errcount != 0)
		exit(1);

	free(srcfiles);

	if (do_intl)
		exit(0);

	if (do_lint && begin_block == NULL && expression_value == NULL
	     && end_block == NULL)
		lintwarn(_("no program text at all!"));

	if (do_lint)
		shadow_funcs();

	init_profiling_signals();

#if defined(LC_NUMERIC)
	/* See comment above. */
	setlocale(LC_NUMERIC, "");
#endif

#if defined(HAVE_LOCALE_H)
	loc = *localeconv();	/* Make a local copy of locale numeric info */
#endif

	/* Whew. Finally, run the program. */
	if (begin_block != NULL) {
		in_begin_rule = TRUE;
		(void) interpret(begin_block);
	}
	in_begin_rule = FALSE;
	if (! exiting && (expression_value != NULL || end_block != NULL))
		do_input();
	if (end_block != NULL) {
		in_end_rule = TRUE;
		(void) interpret(end_block);
	}
	in_end_rule = FALSE;
	/*
	 * This used to be:
	 *
	 * if (close_io() != 0 && ! exiting && exit_val == 0)
	 * 	exit_val = 1;
	 *
	 * Other awks don't care about problems closing open files
	 * and pipes, in that it doesn't affect their exit status.
	 * So we no longer do either.
	 */
	(void) close_io(& stdio_problem);
	/*
	 * However, we do want to exit non-zero if there was a problem
	 * with stdout/stderr, so we reinstate a slightly different
	 * version of the above:
	 */
	if (stdio_problem && ! exiting && exit_val == 0)
		exit_val = 1;

	if (do_profiling) {
		dump_prog(begin_block, expression_value, end_block);
		dump_funcs();
	}

	if (do_dump_vars)
		dump_vars(varfile);

	if (do_tidy_mem)
		release_all_vars();

	exit(exit_val);		/* more portable */
	return exit_val;	/* to suppress warnings */
}
Example #9
0
/*
 * Create an CSDLAudioSync for a session.  Don't alloc any buffers until
 * config is called by codec
 */
CSDLAudioSync::CSDLAudioSync (CPlayerSession *psptr, int volume) :
  CBufferAudioSync(psptr, volume)
{
  Our_SDL_AudioInit(getenv("SDL_AUDIODRIVER"));
  m_volume = (volume * SDL_MIX_MAXVOLUME)/100;
}
int main()
{
  // Disable deprecation warning for getenv call.
#ifdef CHAISCRIPT_MSVC
#ifdef max // Why Microsoft? why?
#undef max
#endif
#pragma warning(push)
#pragma warning(disable : 4996)
#endif

  const char *usepath = getenv("CHAI_USE_PATH");
  const char *modulepath = getenv("CHAI_MODULE_PATH");

#ifdef CHAISCRIPT_MSVC
#pragma warning(pop)
#endif

  std::vector<std::string> usepaths;
  usepaths.push_back("");
  if (usepath)
  {
    usepaths.push_back(usepath);
  }

  std::vector<std::string> modulepaths;
  modulepaths.push_back("");
  if (modulepath)
  {
    modulepaths.push_back(modulepath);
  }

  chaiscript::ChaiScript chai(modulepaths,usepaths);

  std::vector<std::shared_ptr<std::thread> > threads;

  // Ensure at least two, but say only 7 on an 8 core processor
  int num_threads = std::max(std::thread::hardware_concurrency() - 1, 2u);

  for (int i = 0; i < num_threads; ++i)
  {
    threads.push_back(std::shared_ptr<std::thread>(new std::thread(do_work, std::ref(chai), i)));
  }

  for (int i = 0; i < num_threads; ++i)
  {
    threads[i]->join();
  }



  for (int i = 0; i < num_threads; ++i)
  {
    std::stringstream ss;
    ss << i;
    if (chai.eval<int>("getvalue(" + ss.str() + ")") != expected_value(4000))
    {
      return EXIT_FAILURE;
    }

    if (chai.eval<int>("getid(" + ss.str() + ")") != i)
    {
      return EXIT_FAILURE;
    }
  }

  return EXIT_SUCCESS;
}
Example #11
0
PsiLogger::PsiLogger(const QString& logFileName)
	: QObject(QCoreApplication::instance())
	, file_(0)
	, stream_(0)
{
	bool enableLogging = false;
#ifdef Q_WS_WIN
	{
		QSettings sUser(QSettings::UserScope, "Yandex", "Online");
		enableLogging = sUser.contains("extra_log");
	}
#endif

	{
		char* p = getenv("ENABLE_LOGGING");
		if (p) {
			enableLogging = true;
		}

#ifdef YAPSI
		QString extraLogFileName = ApplicationInfo::homeDir() + "/extra-log";
		if (QFile::exists(extraLogFileName))
			enableLogging = true;
#endif
	}

	if (!enableLogging)
		return;

#ifdef YAPSI
	QString fileName = ApplicationInfo::homeDir() + "/";
	if (logFileName.isEmpty())
		fileName += "yachat-log.txt";
	else
		fileName += logFileName;
#else
	QString fileName = QDir::homePath() + "/";
	if (logFileName.isEmpty())
		fileName += "psilogger.txt";
	else
		fileName += logFileName;
#endif
	QFile::remove(fileName);
	file_ = new QFile(fileName);
	if (!file_->open(QIODevice::WriteOnly)) {
		qWarning("unable to open log file");
	}
	
	stream_ = new QTextStream();
	stream_->setDevice(file_);
	stream_->setCodec("UTF-8");
	qWarning("Logging started: '%s'", qPrintable(fileName));
#ifdef YAPSI
	log(QString("*** LOG STARTED %1 (%2 / %3) %4")
	    .arg(YaDayUse::ver())
	    .arg(YaDayUse::osId())
	    .arg(YaDayUse::osVer())
	    .arg(QDateTime::currentDateTime().toString(Qt::ISODate)));
#else
	log(QString("*** LOG STARTED %1")
	    .arg(QDateTime::currentDateTime().toString(Qt::ISODate)));
#endif
}
Example #12
0
char *get_dfu_alt_system(char *interface, char *devstr)
{
	return getenv("dfu_alt_system");
}
int main(int argc, char** argv)
{
//   TestCertClient Parameters
//       Parameter 1: Client Certification File
//       Parameter 2: Client Private Key File
//       Parameter 3: Random Key File
//       Parameter 4: User Name
//       Parameter 5: Password
//       Parameter 6: Expected Result
//       Parameter 7: Expected Identity

    if ((argc < 3) || (argc > 8))
    {
        PEGASUS_STD(cout) << "Wrong number of arguments" << PEGASUS_STD(endl);
        exit(1);
    }

    String certpath;
    if (strcmp(argv[1],"NONE") != 0)
    {
        certpath = argv[1];
    }

    String keypath;
    if (strcmp(argv[2],"NONE") != 0)
    {
        keypath = argv[2];
    }

    String randFile;
    if (argc >=4)
    {
        if (strcmp(argv[3],"CONFIG") == 0)
        {
            const char* pegasusHome = getenv("PEGASUS_HOME");
            randFile = FileSystem::getAbsolutePath(
                pegasusHome, PEGASUS_SSLCLIENT_RANDOMFILE);
        }
        else if (strcmp(argv[3],"NONE") != 0)
        {
            randFile = argv[3];
        }
    }

    String userName;
    if (argc >=  5)
    {
        userName = argv[4];
    }

    String password;
    if (argc >=  6)
    {
        password = argv[5];
    }

    expectedResultType expectedResult = NONE;
    expectedErrorType expectedError = ERROR_TYPE_NONE;
    String expectedUserName;
    if (argc >=  7)
    {
        if (strcmp(argv[6],"PASS") == 0)
        {
            expectedResult = PASS;
            if (argc >= 8)
            {
               if (strcmp(argv[7],"NONE") != 0)
               {
                   expectedUserName = argv[7];
               }
            }
        }
        else if (strcmp(argv[6],"FAIL") == 0)
        {
            expectedResult = FAIL;
            if (argc >= 8)
            {
               if (strcmp(argv[7],"NONE") == 0)
               {
                   expectedError = ERROR_TYPE_NONE;
               }
               else if (strcmp(argv[7],"HTTP_401") == 0)
               {
                   expectedError = ERROR_TYPE_HTTP_401;
               }
               else if (strcmp(argv[7],"CANNOT_CONNECT") == 0)
               {
                   expectedError = ERROR_TYPE_CANNOT_CONNECT;
               }
               else
               {
                   PEGASUS_STD(cout) << "Invalid expectedError parameter: "
                        << argv[7] << PEGASUS_STD(endl);
                   exit(1);
               }
            }
        }
        else if (strcmp(argv[6],"NONE") == 0)
        {
            expectedResult = NONE;
        }
        else
        {
            PEGASUS_STD(cout) << "Invalid expectedResult parameter: "
                << argv[6] << PEGASUS_STD(endl);
            exit(1);
        }
    }

    try
    {
        AutoPtr<SSLContext> pCtx;
        if (certpath != String::EMPTY)
        {
            pCtx.reset(
                new SSLContext(String::EMPTY, certpath, keypath, 0, randFile));
        }
        else
        {
            pCtx.reset(new SSLContext(String::EMPTY, 0, randFile));
        }

        PEGASUS_STD(cout)<< "TestCertClient::Connecting to 127.0.0.1:5989"
          << PEGASUS_STD(endl);
    
        CIMClient client;
        client.connect("127.0.0.1", 5989, *pCtx, userName, password);

        Array<CIMParamValue> inParams;
        Array<CIMParamValue> outParams;
        CIMValue retValue = client.invokeMethod(
            CIMNamespaceName("test/TestProvider"),
            CIMObjectPath("Test_MethodProviderClass"),
            CIMName("getIdentity"),
            inParams,
            outParams);

        if (expectedResult == FAIL)
        {
           throw Exception("Failure: Connection unexpectedly succeeded");
        }

        String retUserName;
        retValue.get(retUserName);

        if (expectedUserName != String::EMPTY)
        {
           if (expectedUserName != retUserName)
           {
              throw Exception("Provider returned unexpected Identity: "
                  + retUserName);
           }
        }
        CIMClass c = client.getClass("root/cimv2",
            "CIM_ComputerSystem", false, false, true);
          
        PEGASUS_STD(cout) << "Result: " <<  c.getClassName().getString()
            << PEGASUS_STD(endl);
    }
    catch (CIMClientHTTPErrorException& httpException)
    {
        if ((expectedResult == FAIL) &&
                (httpException.getCode() == 401) &&
                (expectedError == ERROR_TYPE_HTTP_401))
        {
            PEGASUS_STD(cout) << "+++++ "<< argv[0] <<
                " +++++ passed all tests" << PEGASUS_STD(endl);
            exit(0);
         }
           
         PEGASUS_STD(cout) << "Exception: " << httpException.getMessage()
            << PEGASUS_STD(endl);
         exit(1);
    }
    catch (CannotConnectException& connectException)
    {
        if ((expectedResult == FAIL) &&
                (expectedError == ERROR_TYPE_CANNOT_CONNECT))
        {
            PEGASUS_STD(cout) << "+++++ "<< argv[0] <<
                " +++++ passed all tests" << PEGASUS_STD(endl);
            exit(0);
        }
        PEGASUS_STD(cout) << "Exception: " << connectException.getMessage()
            << PEGASUS_STD(endl);
        exit(1);
    }
    catch (Exception& ex)
    {
        PEGASUS_STD(cout) << "Exception: " << ex.getMessage()
             << PEGASUS_STD(endl);
        exit(1);

    }
    catch (...)
    {
        PEGASUS_STD(cout) << "Unknown exception" << PEGASUS_STD(endl);
        exit(1);
    }
    if (expectedResult == PASS)
    {
        PEGASUS_STD(cout) << "+++++ "<< argv[0] <<
             " +++++ passed all tests" << PEGASUS_STD(endl);
    }
    else
    {
        PEGASUS_STD(cout) << "+++++ "<< "TestCertClient" 
            << " Terminated Normally" << PEGASUS_STD(endl);
    }
    exit(0);
}
int get_process(char *command,char *argm[],int num_args)
{
	int check = 1;
	if(num_args>2)
	{
		if(!strcmp(command,"pid"))
		{
			if(!strcmp(argm[1],"current"))
				pid_current();
			else if(!strcmp(argm[1],"all"))
				pid_all();
			check = 0;
			proc[num_proc].proc_run = 0;
			proc[num_proc].proc_pid = pid_out;
			num_proc++;
		}
		if(!strcmp(command,"cd"))
		{
			if(!strcmp(argm[1],getenv("HOME")))
				chdir(getenv("HOME"));
			else
				change_dir(argm[1]);

			check = 0;
			proc[num_proc].proc_pid = pid_out;
			proc[num_proc].proc_run = 0;
			num_proc++;
		}
	}
	else
	{
		if(!strcmp(command,"pid"))
		{
			printf("command name: ./a.out process id: %d\n",pid_out);
			check = 0;
			proc[num_proc].proc_pid = pid_out;
			proc[num_proc].proc_run = 0;
			num_proc++;
		}
		else if(!strcmp(command,"hist"))
		{
			hist_all();
			check = 0;
			proc[num_proc].proc_run = 0;
			proc[num_proc].proc_pid = pid_out;
			num_proc++;
		}
		else if(!strcmp(strndup(command,4),"hist") && strlen(command)>4)
		{
			hist_n(string_to_int(&command[4]));
			check = 0;
			proc[num_proc].proc_pid = pid_out;
			proc[num_proc].proc_run = 0;
			num_proc++;
		}
		else if(!strcmp(strndup(command,5),"!hist"))
		{
			proc[num_proc].proc_pid = pid_out;
			proc[num_proc].proc_run = 0;
			num_proc++;
			not_hist_n(string_to_int(&command[5]));
			check = 0;
		}
		else if(!strcmp(command,"quit"))
			exit(0);
		else if(!strcmp(command,"ls"))
		{
			ls_out();
			check = 0;
			proc[num_proc].proc_pid = pid_out;
			proc[num_proc].proc_run = 0;
			num_proc++;
		}
		else if(!strcmp(command,"cd"))
		{
			char *home = getenv("HOME");
			chdir(home);
			check = 0;
			proc[num_proc].proc_pid = pid_out;
			proc[num_proc].proc_run = 0;
			num_proc++;
		}
	}
	return check;
}
Example #15
0
int start_stunnel(int stunnel_port, int x11vnc_port, int hport, int x11vnc_hport) {
#ifdef SSLCMDS
	char extra[] = ":/usr/sbin:/usr/local/sbin:/dist/sbin";
	char *path, *p, *exe;
	char *stunnel_path = NULL;
	struct stat verify_buf;
	struct stat crl_buf;
	int status, tmp_pem = 0;

	if (stunnel_pid) {
		stop_stunnel();
	}
	stunnel_pid = 0;

	path = getenv("PATH");
	if (! path) {
		path = strdup(extra+1);
	} else {
		char *pt = path;
		path = (char *) malloc(strlen(path)+strlen(extra)+1);
		if (! path) {
			return 0;
		}
		strcpy(path, pt);
		strcat(path, extra);
	}

	exe = (char *) malloc(strlen(path) + 1 + strlen("stunnel4") + 1);

	p = strtok(path, ":");

	exe[0] = '\0';

	while (p) {
		struct stat sbuf;

		sprintf(exe, "%s/%s", p, "stunnel4");
		if (! stunnel_path && stat(exe, &sbuf) == 0) {
			if (! S_ISDIR(sbuf.st_mode)) {
				stunnel_path = exe;
				break;
			}
		}

		sprintf(exe, "%s/%s", p, "stunnel");
		if (! stunnel_path && stat(exe, &sbuf) == 0) {
			if (! S_ISDIR(sbuf.st_mode)) {
				stunnel_path = exe;
				break;
			}
		}

		p = strtok(NULL, ":");
	}
	if (path) {
		free(path);
	}

	if (getenv("STUNNEL_PROG")) {
		free(exe);
		exe = strdup(getenv("STUNNEL_PROG"));
		stunnel_path = exe;
	}

	if (! stunnel_path) {
		free(exe);
		return 0;
	}
	if (stunnel_path[0] == '\0') {
		free(exe);
		return 0;
	}

	/* stunnel */
	if (no_external_cmds || !cmd_ok("stunnel")) {
		rfbLogEnable(1);
		rfbLog("start_stunnel: cannot run external commands in -nocmds mode:\n");
		rfbLog("   \"%s\"\n", stunnel_path);
		rfbLog("   exiting.\n");
		clean_up_exit(1);
	}

	if (! quiet) {
		rfbLog("\n");
		rfbLog("starting ssl tunnel: %s  %d -> %d\n", stunnel_path,
		    stunnel_port, x11vnc_port);
	}

	if (stunnel_pem && strstr(stunnel_pem, "SAVE") == stunnel_pem) {
		stunnel_pem = get_saved_pem(stunnel_pem, 1);
		if (! stunnel_pem) {
			rfbLog("start_stunnel: could not create or open"
			    " saved PEM.\n");	
			clean_up_exit(1);
		}
	} else if (!stunnel_pem) {
		stunnel_pem = create_tmp_pem(NULL, 0);
		if (! stunnel_pem) {
			rfbLog("start_stunnel: could not create temporary,"
			    " self-signed PEM.\n");	
			clean_up_exit(1);
		}
		tmp_pem = 1;
		if (getenv("X11VNC_SHOW_TMP_PEM")) {
			FILE *in = fopen(stunnel_pem, "r");
			if (in != NULL) {
				char line[128];
				fprintf(stderr, "\n");
				while (fgets(line, 128, in) != NULL) {
					fprintf(stderr, "%s", line);
				}
				fprintf(stderr, "\n");
				fclose(in);
			}
		}
	}

	if (ssl_verify) {
		char *file = get_ssl_verify_file(ssl_verify);
		if (file) {
			ssl_verify = file;
		}
		if (stat(ssl_verify, &verify_buf) != 0) {
			rfbLog("stunnel: %s does not exist.\n", ssl_verify);
			clean_up_exit(1);
		}
	}
	if (ssl_crl) {
		if (stat(ssl_crl, &crl_buf) != 0) {
			rfbLog("stunnel: %s does not exist.\n", ssl_crl);
			clean_up_exit(1);
		}
	}

	stunnel_pid = fork();

	if (stunnel_pid < 0) {
		stunnel_pid = 0;
		free(exe);
		return 0;
	}

	if (stunnel_pid == 0) {
		FILE *in;
		char fd[20];
		int i;
		char *st_if = getenv("STUNNEL_LISTEN");

		if (st_if == NULL) {
			st_if = "";
		} else {
			st_if = (char *) malloc(strlen(st_if) + 2);
			sprintf(st_if, "%s:", getenv("STUNNEL_LISTEN"));
		}


		for (i=3; i<256; i++) {
			close(i);
		}

		if (use_stunnel == 3) {
			char sp[30], xp[30], *a = NULL;
			char *st = stunnel_path;
			char *pm = stunnel_pem;
			char *sv = ssl_verify;

			sprintf(sp, "%d", stunnel_port);
			sprintf(xp, "%d", x11vnc_port);

			if (ssl_verify) {
				if(S_ISDIR(verify_buf.st_mode)) {
					a = "-a";
				} else {
					a = "-A";
				}
			}

			if (ssl_crl) {
				rfbLog("stunnel: stunnel3 does not support CRL. %s\n", ssl_crl);
				clean_up_exit(1);
			}
			
			if (stunnel_pem && ssl_verify) {
				/* XXX double check -v 2 */
				execlp(st, st, "-f", "-d", sp, "-r", xp, "-P",
				    "none", "-p", pm, a, sv, "-v", "2",
				    (char *) NULL);
			} else if (stunnel_pem && !ssl_verify) {
				execlp(st, st, "-f", "-d", sp, "-r", xp, "-P",
				    "none", "-p", pm,
				    (char *) NULL);
			} else if (!stunnel_pem && ssl_verify) {
				execlp(st, st, "-f", "-d", sp, "-r", xp, "-P",
				    "none", a, sv, "-v", "2",
				    (char *) NULL);
			} else {
				execlp(st, st, "-f", "-d", sp, "-r", xp, "-P",
				    "none", (char *) NULL);
			}
			exit(1);
		}

		in = tmpfile();
		if (! in) {
			exit(1);
		}

		fprintf(in, "foreground = yes\n");
		fprintf(in, "pid =\n");
		if (stunnel_pem) {
			fprintf(in, "cert = %s\n", stunnel_pem);
		}
		if (ssl_crl) {
			if(S_ISDIR(crl_buf.st_mode)) {
				fprintf(in, "CRLpath = %s\n", ssl_crl);
			} else {
				fprintf(in, "CRLfile = %s\n", ssl_crl);
			}
		}
		if (ssl_verify) {
			if(S_ISDIR(verify_buf.st_mode)) {
				fprintf(in, "CApath = %s\n", ssl_verify);
			} else {
				fprintf(in, "CAfile = %s\n", ssl_verify);
			}
			fprintf(in, "verify = 2\n");
		}
		fprintf(in, ";debug = 7\n\n");
		fprintf(in, "[x11vnc_stunnel]\n");
		fprintf(in, "accept = %s%d\n", st_if, stunnel_port);
		fprintf(in, "connect = %d\n", x11vnc_port);

		if (hport > 0 && x11vnc_hport > 0) {
			fprintf(in, "\n[x11vnc_http]\n");
			fprintf(in, "accept = %s%d\n", st_if, hport);
			fprintf(in, "connect = %d\n", x11vnc_hport);
		}

		fflush(in);
		rewind(in);

		if (getenv("STUNNEL_DEBUG")) {
			char line[1000];
			fprintf(stderr, "\nstunnel config contents:\n\n");
			while (fgets(line, sizeof(line), in) != NULL) {
				fprintf(stderr, "%s", line);
			}
			fprintf(stderr, "\n");
			rewind(in);
		}
		
		sprintf(fd, "%d", fileno(in));
		execlp(stunnel_path, stunnel_path, "-fd", fd, (char *) NULL);
		exit(1);
	}

	free(exe);
	usleep(750 * 1000);

	waitpid(stunnel_pid, &status, WNOHANG); 

	if (ssl_verify && strstr(ssl_verify, "/sslverify-tmp-load-")) {
		/* temporary file */
		usleep(1000 * 1000);
		unlink(ssl_verify);
	}
	if (tmp_pem) {
		/* temporary cert */
		usleep(1500 * 1000);
		unlink(stunnel_pem);
	}

	if (kill(stunnel_pid, 0) != 0) {
		waitpid(stunnel_pid, &status, WNOHANG); 
		stunnel_pid = 0;
		return 0;
	}

	if (! quiet) {
		rfbLog("stunnel pid is: %d\n", (int) stunnel_pid);
	}

	return 1;
#else
	return 0;
#endif
}
Example #16
0
int main(int argc, char *argv[])
{
  int      status, i, uptodate, nBRep, nParams, nBranch, nattr;
  double   xform[12];
  char     *server, *filename, *modeler;
  gemCntxt *context;
  gemModel *model, *newModel;
  gemBRep  **BReps; 

  if ((argc != 2) && (argc != 3)) {
    printf(" usage: [d/q]static filename [modeler]!\n");
    return 1;
  }
  for (i = 1; i < 12; i++) xform[i] = 0.0;
  xform[0] = xform[5] = xform[10] = 1.5;

  server = getenv("GEMserver");
  status = gem_initialize(&context);
  printf(" gem_initialize = %d\n", status);
  if (argc == 2) {
    status = gem_setAttribute(context, 0, 0, "Modeler", GEM_STRING, 7, NULL,
                              NULL, "Parasolid");
  } else {
    status = gem_setAttribute(context, 0, 0, "Modeler", GEM_STRING, 7, NULL, 
                              NULL, argv[2]);
  }
  printf(" gem_setAttribute = %d\n", status);
  status = gem_loadModel(context, server, argv[1], &model);
  printf(" gem_loadModel = %d\n", status);
  printf(" \n");
  if (status != GEM_SUCCESS) {
    status = gem_terminate(context);
    printf(" gem_terminate = %d\n", status);
    return 1;
  }
  status  = gem_getModel(model, &server, &filename, &modeler, &uptodate,
                         &nBRep, &BReps, &nParams, &nBranch, &nattr);
  printf(" gem_getModel = %d\n", status);

  status = gem_staticModel(context, &newModel);
  printf(" gem_staticModel = %d\n", status);
  if (status != GEM_SUCCESS) {
    status = gem_releaseModel(model);
    printf(" gem_releaseModel = %d\n", status);
    status = gem_terminate(context);
    printf(" gem_terminate = %d\n", status);
    return 1;
  }
  status = gem_add2Model(newModel, BReps[0], NULL);
  printf(" gem_add2Model = %d\n", status);
  status = gem_add2Model(newModel, BReps[0], xform);
  printf(" gem_add2Model = %d\n\n", status);
  status  = gem_getModel(newModel, &server, &filename, &modeler, &uptodate,
                         &nBRep, &BReps, &nParams, &nBranch, &nattr);
  printf(" gem_getModel = %d\n", status);
  printf("     FileName = %s\n", filename);
  printf("     Modeler  = %s\n", modeler);
  printf("     UpToDate = %d\n", uptodate);
  printf("     nBReps   = %d\n", nBRep);
  printf("\n");

#ifndef QUARTZ
  status = gem_saveModel(newModel, "newModel.egads");
  printf(" gem_saveModel egads = %d\n", status);
#endif
  status = gem_releaseModel(newModel);
  printf(" gem_releaseModel = %d\n", status);
  status = gem_releaseModel(model);
  printf(" gem_releaseModel = %d\n", status);
  status = gem_terminate(context);
  printf(" gem_terminate = %d\n", status);

  return 0;
}
Example #17
0
int I_PickIWad (WadStuff *wads, int numwads, bool showwin, int defaultiwad)
{
	int i;

	if (!showwin)
	{
		return defaultiwad;
	}

#if !defined(__APPLE__)
	const char *str;
	if((str=getenv("KDE_FULL_SESSION")) && strcmp(str, "true") == 0)
	{
		FString cmd("kdialog --title \""GAMESIG" "DOTVERSIONSTR": Select an IWAD to use\""
		            " --menu \"ZDoom found more than one IWAD\n"
		            "Select from the list below to determine which one to use:\"");

		for(i = 0; i < numwads; ++i)
		{
			const char *filepart = strrchr(wads[i].Path, '/');
			if(filepart == NULL)
				filepart = wads[i].Path;
			else
				filepart++;
			// Menu entries are specified in "tag" "item" pairs, where when a
			// particular item is selected (and the Okay button clicked), its
			// corresponding tag is printed to stdout for identification.
			cmd.AppendFormat(" \"%d\" \"%s (%s)\"", i, wads[i].Name.GetChars(), filepart);
		}

		if(defaultiwad >= 0 && defaultiwad < numwads)
		{
			const char *filepart = strrchr(wads[defaultiwad].Path, '/');
			if(filepart == NULL)
				filepart = wads[defaultiwad].Path;
			else
				filepart++;
			cmd.AppendFormat(" --default \"%s (%s)\"", wads[defaultiwad].Name.GetChars(), filepart);
		}

		FILE *f = popen(cmd, "r");
		if(f != NULL)
		{
			char gotstr[16];

			if(fgets(gotstr, sizeof(gotstr), f) == NULL ||
			   sscanf(gotstr, "%d", &i) != 1)
				i = -1;

			// Exit status = 1 means the selection was canceled (either by
			// Cancel/Esc or the X button), not that there was an error running
			// the program. In that case, nothing was printed so fgets will
			// have failed. Other values can indicate an error running the app,
			// so fall back to whatever else can be used.
			int status = pclose(f);
			if(WIFEXITED(status) && (WEXITSTATUS(status) == 0 || WEXITSTATUS(status) == 1))
				return i;
		}
	}
#endif
#ifndef NO_GTK
	if (GtkAvailable)
	{
		return I_PickIWad_Gtk (wads, numwads, showwin, defaultiwad);
	}
#elif defined(__APPLE__)
	return I_PickIWad_Cocoa (wads, numwads, showwin, defaultiwad);
#endif
	
	printf ("Please select a game wad (or 0 to exit):\n");
	for (i = 0; i < numwads; ++i)
	{
		const char *filepart = strrchr (wads[i].Path, '/');
		if (filepart == NULL)
			filepart = wads[i].Path;
		else
			filepart++;
		printf ("%d. %s (%s)\n", i+1, wads[i].Name.GetChars(), filepart);
	}
	printf ("Which one? ");
	scanf ("%d", &i);
	if (i > numwads)
		return -1;
	return i-1;
}
Example #18
0
bool response_expand(Strings *args)
{
    const char *cp;
    int recurse = 0;

    for (size_t i = 0; i < args->dim; )
    {
        cp = (*args)[i];
        if (*cp != '@')
        {
            ++i;
            continue;
        }

        args->remove(i);

        char *buffer;
        char *bufend;

        cp++;
        char *p = getenv(cp);
        if (p)
        {
            buffer = strdup(p);
            if (!buffer)
                goto noexpand;
            bufend = buffer + strlen(buffer);
        }
        else
        {
            File f(cp);
            if (f.read())
                goto noexpand;
            f.ref = 1;

            buffer = (char *)f.buffer;
            bufend = buffer + f.len;
        }

        // The logic of this should match that in setargv()

        int comment = 0;
        for (p = buffer; p < bufend; p++)
        {
            char *d;
            char c,lastc;
            unsigned char instring;
            int num_slashes,non_slashes;

            switch (*p)
            {
                case 26:      /* ^Z marks end of file      */
                    goto L2;

                case 0xD:
                case '\n':
                    if (comment)
                    {
                        comment = 0;
                    }
                case 0:
                case ' ':
                case '\t':
                    continue;   // scan to start of argument

                case '#':
                    comment = 1;
                    continue;

                case '@':
                    if (comment)
                    {
                        continue;
                    }
                    recurse = 1;
                default:      /* start of new argument   */
                    if (comment)
                    {
                        continue;
                    }
                    args->insert(i, p);
                    ++i;
                    instring = 0;
                    c = 0;
                    num_slashes = 0;
                    for (d = p; 1; p++)
                    {
                        lastc = c;
                        if (p >= bufend)
                        {
                            *d = 0;
                            goto L2;
                        }
                        c = *p;
                        switch (c)
                        {
                            case '"':
                                /*
                                    Yes this looks strange,but this is so that we are
                                    MS Compatible, tests have shown that:
                                    \\\\"foo bar"  gets passed as \\foo bar
                                    \\\\foo  gets passed as \\\\foo
                                    \\\"foo gets passed as \"foo
                                    and \"foo gets passed as "foo in VC!
                                 */
                                non_slashes = num_slashes % 2;
                                num_slashes = num_slashes / 2;
                                for (; num_slashes > 0; num_slashes--)
                                {
                                    d--;
                                    *d = '\0';
                                }

                                if (non_slashes)
                                {
                                    *(d-1) = c;
                                }
                                else
                                {
                                    instring ^= 1;
                                }
                                break;
                            case 26:
                                *d = 0;      // terminate argument
                                goto L2;

                            case 0xD:      // CR
                                c = lastc;
                                continue;      // ignore

                            case '@':
                                recurse = 1;
                                goto Ladd;

                            case ' ':
                            case '\t':
                                if (!instring)
                                {
                            case '\n':
                            case 0:
                                    *d = 0;      // terminate argument
                                    goto Lnextarg;
                                }
                            default:
                            Ladd:
                                if (c == '\\')
                                    num_slashes++;
                                else
                                    num_slashes = 0;
                                *d++ = c;
                                break;
                        }
                    }
                break;
            }
        Lnextarg:
            ;
        }
    L2:
        ;
    }
    if (recurse)
    {
        /* Recursively expand @filename   */
        if (response_expand(args))
            goto noexpand;
    }
    return false;            /* success         */

noexpand:            /* error         */
    /* BUG: any file buffers are not free'd   */
    return true;
}
Example #19
0
int
main(int argc, char ** argv)
{
    char *display = NULL;
    char *theme = NULL;
    int ret = 1;
    int i;

    if (!ecore_init())
    {
        fprintf(stderr, "Error initing Ecore.\n");
        goto SHUTDOWN;
    }
    ecore_app_args_set(argc, (const char **)argv);
    ecore_event_handler_add(ECORE_EVENT_SIGNAL_EXIT, entangle_cb_exit, NULL);

    for (i = 1; i < argc; i++)
    {
        if ((!strcmp(argv[i], "-display")) || (!strcmp(argv[i], "-d")))
        {
            if (++i < argc)
            {
                IF_FREE(display);
                display = strdup(argv[i]);
            }
            else
            {
                fprintf(stderr, "ERROR: Missing argument to -display\n");
                goto ECORE_SHUTDOWN;
            }
        }
        else if ((!strcmp(argv[i], "-theme")) || (!strcmp(argv[i], "-t")))
        {
            if (++i < argc)
            {
                IF_FREE(theme);
                theme = strdup(argv[i]);
            }
            else
            {
                fprintf(stderr, "ERROR: Missing argument to -theme\n");
                goto ECORE_SHUTDOWN;
            }
        }
        else if ((!strcmp(argv[i], "-help")) || (!strcmp(argv[i], "-h")))
        {
            entangle_usage(argv);
            return 0;
        }
    }

    /* make sure the theme is valid */
    if (theme)
    {
        char *p;
        p = strstr(theme, ".edj");

        if (p && (strlen(theme) - (p - theme) == strlen(".edj")))
        {
            if (!ecore_file_exists(theme))
            {
                char tmp[PATH_MAX];
                snprintf(tmp, PATH_MAX, PACKAGE_DATA_DIR"/data/entangle/%s", theme);
                FREE(theme);

                if (ecore_file_exists(tmp)) theme = strdup(tmp);
            }
        }
        else
        {
            char tmp[PATH_MAX];
            snprintf(tmp, PATH_MAX, PACKAGE_DATA_DIR"/data/entangle/%s.edj", theme);
            FREE(theme);

            if (ecore_file_exists(tmp)) theme = strdup(tmp);
        }
    }
    if (!theme) theme = strdup(PACKAGE_DATA_DIR"/data/entangle/default.edj");

    /* make sure the display is valid */
    if (!display) 
    {
        char *tmp = getenv("DISPLAY");
        if (tmp) display = strdup(tmp);
    }
    if (display)
    {
        char *p;
        char buf[1024];

        p = strrchr(display, ':');
        if (!p)
        {
            snprintf(buf, sizeof(buf), "%s:0.0", display);
            FREE(display);
            display = strdup(buf);
        }
        else
        {
            p = strrchr(p, '.');
            if (!p)
            {
                snprintf(buf, sizeof(buf), "%s.0", display);
                FREE(display);
                display = strdup(buf);
            }
        }
    }
    else
        display = strdup(":0.0");

    if (!ecore_file_init())
    {
        fprintf(stderr, "Error initing Ecore_File.\n");
        goto ECORE_SHUTDOWN;
    }

    if (!ecore_evas_init())
    {
        fprintf(stderr, "Error initing Ecore_Evas.\n");
        goto ECORE_FILE_SHUTDOWN;
    }

    if (!edje_init())
    {
        fprintf(stderr, "Error initing Edje.\n");
        goto ECORE_EVAS_SHUTDOWN;
    }

    if (!eet_init())
    {
        fprintf(stderr, "Error initing Eet.\n");
        goto EDJE_SHUTDOWN;
    }

    if (!entangle_eapps_init())
    {
        fprintf(stderr, "Error initing Entangle_Eapps.\n");
        goto EET_SHUTDOWN;
    }

    if (!entangle_apps_init())
    {
        fprintf(stderr, "Error initing Entangle_Apps.\n");
        goto ENTANGLE_EAPPS_SHUTDOWN;
    }

    if (!entangle_ui_init(display, theme))
    {
        fprintf(stderr, "Error initing Entangle_Ui.\n");
        goto ENTANGLE_APPS_SHUTDOWN;
    }

    ecore_main_loop_begin();
    ret = 0;

    entangle_ui_shutdown();
ENTANGLE_APPS_SHUTDOWN:
    entangle_apps_shutdown();
ENTANGLE_EAPPS_SHUTDOWN:
    entangle_eapps_shutdown();
EET_SHUTDOWN:
    eet_shutdown();
EDJE_SHUTDOWN:
    edje_shutdown();
ECORE_EVAS_SHUTDOWN:
    ecore_evas_shutdown();
ECORE_FILE_SHUTDOWN:
    ecore_file_shutdown();
ECORE_SHUTDOWN:
    ecore_shutdown();
SHUTDOWN:

    IF_FREE(display);
    IF_FREE(theme);
    return ret;
}
Example #20
0
static int
munge_line_in_editor(int count, int key)
{
  int line_number = 0, column_number = 0,  ret, tmpfile_fd, bytes_read;
  size_t tmpfilesize;
  char *p, *tmpfilename, *text_to_edit;
  char *editor_command1, *editor_command2, *editor_command3, *editor_command4,
    *line_number_as_string, *column_number_as_string;
  char *input, *rewritten_input, *rewritten_input2,  **possible_editor_commands;


  if (!multiline_separator)
    return 0;

  tmpfile_fd = open_unique_tempfile(multi_line_tmpfile_ext, &tmpfilename);

  text_to_edit =
    search_and_replace(multiline_separator, "\n", rl_line_buffer, rl_point,
                       &line_number, &column_number);
  write_patiently(tmpfile_fd, text_to_edit, strlen(text_to_edit), "to temporary file");

  if (close(tmpfile_fd) != 0) /* improbable */
    myerror("couldn't close temporary file %s", tmpfilename); 

  /* find out which editor command we have to use */
  possible_editor_commands = list4(getenv("RLWRAP_EDITOR"), getenv("EDITOR"), getenv("VISUAL"), "vi +%L");
  editor_command1 = first_of(possible_editor_commands);
  line_number_as_string = as_string(line_number);
  column_number_as_string = as_string(column_number);
  editor_command2 =
    search_and_replace("%L", line_number_as_string, editor_command1, 0, NULL,
                       NULL);
  editor_command3 =
    search_and_replace("%C", column_number_as_string, editor_command2, 0,
                       NULL, NULL);
  editor_command4 = add3strings(editor_command3, " ", tmpfilename);
  

  /* call editor, temporarily restoring terminal settings */    
  if (terminal_settings_saved && (tcsetattr(STDIN_FILENO, TCSAFLUSH, &saved_terminal_settings) < 0))    /* reset terminal */
    myerror("tcsetattr error on stdin");
  DPRINTF1(DEBUG_READLINE, "calling %s", editor_command4);
  if ((ret = system(editor_command4))) {
    if (WIFSIGNALED(ret)) {
      fprintf(stderr, "\n"); errno = 0;
      myerror("editor killed by signal");
    } else {    
      myerror("failed to invoke editor with '%s'", editor_command4);
    }
  }
  completely_mirror_slaves_terminal_settings();
  ignore_queued_input = TRUE;  

  /* read back edited input, replacing real newline with substitute */
  tmpfile_fd = open(tmpfilename, O_RDONLY);
  if (tmpfile_fd < 0)
    myerror("could not read temp file %s", tmpfilename);
  tmpfilesize = filesize(tmpfilename);
  input = mymalloc(tmpfilesize + 1);
  bytes_read = read(tmpfile_fd, input, tmpfilesize);
  if (bytes_read < 0)
    myerror("unreadable temp file %s", tmpfilename);
  input[bytes_read] = '\0';
  rewritten_input = search_and_replace("\t", "    ", input, 0, NULL, NULL);     /* rlwrap cannot handle tabs in input lines */
  rewritten_input2 =
    search_and_replace("\n", multiline_separator, rewritten_input, 0, NULL,
                       NULL);
  for(p = rewritten_input2; *p ;p++)
    if(*p >= 0 && *p < ' ') /* @@@FIXME: works for UTF8, but not UTF16 or UTF32 (Mention this in manpage?)*/ 
      *p = ' ';        /* replace all control characters (like \r) by spaces */


  rl_delete_text(0, strlen(rl_line_buffer));
  rl_point = 0;  
  clear_line();
  cr();
  my_putstr(saved_rl_state.cooked_prompt);
  rl_insert_text(rewritten_input2);
  rl_point = 0;                 /* leave cursor on predictable place */
  rl_done = 1;                  /* accept line immediately */

  


  /* wash those dishes */
  if (unlink(tmpfilename))
    myerror("could not delete temporary file %s", tmpfilename);
  free(editor_command2);
  free(editor_command3);
  free(editor_command4);
  free(line_number_as_string);
  free(column_number_as_string);
  free(tmpfilename);
  free(text_to_edit);
  free(input);
  free(rewritten_input);
  free(rewritten_input2);
  
  return_key = (char)'\n';
  return 0;
}
Example #21
0
int
bi_getboothowto(char *kargs)
{
    char	*cp;
    char	*curpos, *next, *string;
    int		howto;
    int		active;
    int		i;
    int		vidconsole;

    /* Parse kargs */
    howto = 0;
    if (kargs  != NULL) {
	cp = kargs;
	active = 0;
	while (*cp != 0) {
	    if (!active && (*cp == '-')) {
		active = 1;
	    } else if (active)
		switch (*cp) {
		case 'a':
		    howto |= RB_ASKNAME;
		    break;
		case 'C':
		    howto |= RB_CDROM;
		    break;
		case 'd':
		    howto |= RB_KDB;
		    break;
		case 'D':
		    howto |= RB_MULTIPLE;
		    break;
		case 'm':
		    howto |= RB_MUTE;
		    break;
		case 'g':
		    howto |= RB_GDB;
		    break;
		case 'h':
		    howto |= RB_SERIAL;
		    break;
		case 'p':
		    howto |= RB_PAUSE;
		    break;
		case 'r':
		    howto |= RB_DFLTROOT;
		    break;
		case 's':
		    howto |= RB_SINGLE;
		    break;
		case 'v':
		    howto |= RB_VERBOSE;
		    break;
		default:
		    active = 0;
		    break;
		}
	    cp++;
	}
    }
    /* get equivalents from the environment */
    for (i = 0; howto_names[i].ev != NULL; i++)
	if (getenv(howto_names[i].ev) != NULL)
	    howto |= howto_names[i].mask;

    /* Enable selected consoles */
    string = next = strdup(getenv("console"));
    vidconsole = 0;
    while (next != NULL) {
	curpos = strsep(&next, " ,");
	if (*curpos == '\0')
		continue;
	if (!strcmp(curpos, "vidconsole"))
	    vidconsole = 1;
	else if (!strcmp(curpos, "comconsole"))
	    howto |= RB_SERIAL;
	else if (!strcmp(curpos, "nullconsole"))
	    howto |= RB_MUTE;
    }

    if (vidconsole && (howto & RB_SERIAL))
	howto |= RB_MULTIPLE;

    /*
     * XXX: Note that until the kernel is ready to respect multiple consoles
     * for the boot messages, the first named console is the primary console
     */
    if (!strcmp(string, "vidconsole"))
	howto &= ~RB_SERIAL;

    free(string);

    return(howto);
}
Example #22
0
int plink_main(int argc, char **argv)
{
    int sending;
    int portnumber = -1;
    SOCKET *sklist;
    int skcount, sksize;
    int exitcode;
    int errors;
    int got_host = FALSE;
    int use_subsystem = 0;
    long now, next;
	
    IsPortableMode() ;
    //if( IsPortableMode() ) { printf( "Portable mode on\n" ) ; }

#else

int main(int argc, char **argv)
{
    int sending;
    int portnumber = -1;
    SOCKET *sklist;
    int skcount, sksize;
    int exitcode;
    int errors;
    int got_host = FALSE;
    int use_subsystem = 0;
    long now, next;
#endif

    sklist = NULL;
    skcount = sksize = 0;
    /*
     * Initialise port and protocol to sensible defaults. (These
     * will be overridden by more or less anything.)
     */
    default_protocol = PROT_SSH;
    default_port = 22;

    flags = FLAG_STDERR;
    /*
     * Process the command line.
     */
    do_defaults(NULL, &cfg);
    loaded_session = FALSE;
    default_protocol = cfg.protocol;
    default_port = cfg.port;
    errors = 0;
    {
	/*
	 * Override the default protocol if PLINK_PROTOCOL is set.
	 */
	char *p = getenv("PLINK_PROTOCOL");
	if (p) {
	    const Backend *b = backend_from_name(p);
	    if (b) {
		default_protocol = cfg.protocol = b->protocol;
		default_port = cfg.port = b->default_port;
	    }
	}
    }
    while (--argc) {
	char *p = *++argv;
	if (*p == '-') {
	    int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL),
					    1, &cfg);
	    if (ret == -2) {
		fprintf(stderr,
			"plink: option \"%s\" requires an argument\n", p);
		errors = 1;
	    } else if (ret == 2) {
		--argc, ++argv;
	    } else if (ret == 1) {
		continue;
	    } else if (!strcmp(p, "-batch")) {
		console_batch_mode = 1;
	    } else if (!strcmp(p, "-s")) {
		/* Save status to write to cfg later. */
		use_subsystem = 1;
	    } else if (!strcmp(p, "-V")) {
                version();
            } else if (!strcmp(p, "-pgpfp")) {
                pgp_fingerprints();
                exit(1);
	    } else {
		fprintf(stderr, "plink: unknown option \"%s\"\n", p);
		errors = 1;
	    }
	} else if (*p) {
	    if (!cfg_launchable(&cfg) || !(got_host || loaded_session)) {
		char *q = p;
		/*
		 * If the hostname starts with "telnet:", set the
		 * protocol to Telnet and process the string as a
		 * Telnet URL.
		 */
		if (!strncmp(q, "telnet:", 7)) {
		    char c;

		    q += 7;
		    if (q[0] == '/' && q[1] == '/')
			q += 2;
		    cfg.protocol = PROT_TELNET;
		    p = q;
		    while (*p && *p != ':' && *p != '/')
			p++;
		    c = *p;
		    if (*p)
			*p++ = '\0';
		    if (c == ':')
			cfg.port = atoi(p);
		    else
			cfg.port = -1;
		    strncpy(cfg.host, q, sizeof(cfg.host) - 1);
		    cfg.host[sizeof(cfg.host) - 1] = '\0';
		    got_host = TRUE;
		} else {
		    char *r, *user, *host;
		    /*
		     * Before we process the [[email protected]]host string, we
		     * first check for the presence of a protocol
		     * prefix (a protocol name followed by ",").
		     */
		    r = strchr(p, ',');
		    if (r) {
			const Backend *b;
			*r = '\0';
			b = backend_from_name(p);
			if (b) {
			    default_protocol = cfg.protocol = b->protocol;
			    portnumber = b->default_port;
			}
			p = r + 1;
		    }

		    /*
		     * A nonzero length string followed by an @ is treated
		     * as a username. (We discount an _initial_ @.) The
		     * rest of the string (or the whole string if no @)
		     * is treated as a session name and/or hostname.
		     */
		    r = strrchr(p, '@');
		    if (r == p)
			p++, r = NULL; /* discount initial @ */
		    if (r) {
			*r++ = '\0';
			user = p, host = r;
		    } else {
			user = NULL, host = p;
		    }

		    /*
		     * Now attempt to load a saved session with the
		     * same name as the hostname.
		     */
		    {
			Config cfg2;
			do_defaults(host, &cfg2);
			if (loaded_session || !cfg_launchable(&cfg2)) {
			    /* No settings for this host; use defaults */
			    /* (or session was already loaded with -load) */
			    strncpy(cfg.host, host, sizeof(cfg.host) - 1);
			    cfg.host[sizeof(cfg.host) - 1] = '\0';
			    cfg.port = default_port;
			    got_host = TRUE;
			} else {
			    cfg = cfg2;
			    loaded_session = TRUE;
			}
		    }

		    if (user) {
			/* Patch in specified username. */
			strncpy(cfg.username, user,
				sizeof(cfg.username) - 1);
			cfg.username[sizeof(cfg.username) - 1] = '\0';
		    }

		}
	    } else {
		char *command;
		int cmdlen, cmdsize;
		cmdlen = cmdsize = 0;
		command = NULL;

		while (argc) {
		    while (*p) {
			if (cmdlen >= cmdsize) {
			    cmdsize = cmdlen + 512;
			    command = sresize(command, cmdsize, char);
			}
			command[cmdlen++]=*p++;
		    }
		    if (cmdlen >= cmdsize) {
			cmdsize = cmdlen + 512;
			command = sresize(command, cmdsize, char);
		    }
		    command[cmdlen++]=' '; /* always add trailing space */
		    if (--argc) p = *++argv;
		}
		if (cmdlen) command[--cmdlen]='\0';
				       /* change trailing blank to NUL */
		cfg.remote_cmd_ptr = command;
		cfg.remote_cmd_ptr2 = NULL;
		cfg.nopty = TRUE;      /* command => no terminal */

		break;		       /* done with cmdline */
	    }
	}
Example #23
0
LanguageType Application::getCurrentLanguage()
{
    char *pLanguageName = getenv("LANG");
    LanguageType ret = LanguageType::ENGLISH;
    if (!pLanguageName)
    {
        return LanguageType::ENGLISH;
    }
    strtok(pLanguageName, "_");
    if (!pLanguageName)
    {
        return LanguageType::ENGLISH;
    }
    
    if (0 == strcmp("zh", pLanguageName))
    {
        ret = LanguageType::CHINESE;
    }
    else if (0 == strcmp("en", pLanguageName))
    {
        ret = LanguageType::ENGLISH;
    }
    else if (0 == strcmp("fr", pLanguageName))
    {
        ret = LanguageType::FRENCH;
    }
    else if (0 == strcmp("it", pLanguageName))
    {
        ret = LanguageType::ITALIAN;
    }
    else if (0 == strcmp("de", pLanguageName))
    {
        ret = LanguageType::GERMAN;
    }
    else if (0 == strcmp("es", pLanguageName))
    {
        ret = LanguageType::SPANISH;
    }
    else if (0 == strcmp("nl", pLanguageName))
    {
        ret = LanguageType::DUTCH;
    }
    else if (0 == strcmp("ru", pLanguageName))
    {
        ret = LanguageType::RUSSIAN;
    }
    else if (0 == strcmp("ko", pLanguageName))
    {
        ret = LanguageType::KOREAN;
    }
    else if (0 == strcmp("ja", pLanguageName))
    {
        ret = LanguageType::JAPANESE;
    }
    else if (0 == strcmp("hu", pLanguageName))
    {
        ret = LanguageType::HUNGARIAN;
    }
    else if (0 == strcmp("pt", pLanguageName))
    {
        ret = LanguageType::PORTUGUESE;
    }
    else if (0 == strcmp("ar", pLanguageName))
    {
        ret = LanguageType::ARABIC;
    }
    else if (0 == strcmp("nb", pLanguageName))
    {
        ret = LanguageType::NORWEGIAN;
    }
    else if (0 == strcmp("pl", pLanguageName))
    {
        ret = LanguageType::POLISH;
    }
    else if (0 == strcmp("tr", pLanguageName))
    {
        ret = LanguageType::TURKISH;
    }
    else if (0 == strcmp("uk", pLanguageName))
    {
        ret = LanguageType::UKRAINIAN;
    }
    else if (0 == strcmp("ro", pLanguageName))
    {
        ret = LanguageType::ROMANIAN;
    }
    else if (0 == strcmp("bg", pLanguageName))
    {
        ret = LanguageType::BULGARIAN;
    }
    
    return ret;
}
Example #24
0
static SQLRETURN
MNDBBrowseConnect(ODBCDbc *dbc,
		  SQLCHAR *InConnectionString,
		  SQLSMALLINT StringLength1,
		  SQLCHAR *OutConnectionString,
		  SQLSMALLINT BufferLength,
		  SQLSMALLINT *StringLength2Ptr)
{
	char *key, *attr;
	char *dsn, *uid, *pwd, *host, *dbname;
	int port;
	SQLSMALLINT len = 0;
	char buf[256];
	int n;
	SQLRETURN rc;
#ifdef ODBCDEBUG
	int allocated = 0;
#endif

	fixODBCstring(InConnectionString, StringLength1, SQLSMALLINT, addDbcError, dbc, return SQL_ERROR);

#ifdef ODBCDEBUG
	ODBCLOG(" \"%.*s\"\n", (int) StringLength1, (char*) InConnectionString);
#endif

	/* check connection state, should not be connected */
	if (dbc->Connected) {
		/* Connection name in use */
		addDbcError(dbc, "08002", NULL, 0);
		return SQL_ERROR;
	}

	dsn = dbc->dsn ? strdup(dbc->dsn) : NULL;
	uid = dbc->uid ? strdup(dbc->uid) : NULL;
	pwd = dbc->pwd ? strdup(dbc->pwd) : NULL;
	host = dbc->host ? strdup(dbc->host) : NULL;
	port = dbc->port;
	dbname = dbc->dbname ? strdup(dbc->dbname) : NULL;

	while ((n = ODBCGetKeyAttr(&InConnectionString, &StringLength1, &key, &attr)) > 0) {
		if (strcasecmp(key, "dsn") == 0 && dsn == NULL) {
			if (dsn)
				free(dsn);
			dsn = attr;
		} else if (strcasecmp(key, "uid") == 0 && uid == NULL) {
			if (uid)
				free(uid);
			uid = attr;
		} else if (strcasecmp(key, "pwd") == 0 && pwd == NULL) {
			if (pwd)
				free(pwd);
			pwd = attr;
		} else if (strcasecmp(key, "host") == 0 && host == NULL) {
			if (host)
				free(host);
			host = attr;
		} else if (strcasecmp(key, "port") == 0 && port == 0) {
			port = atoi(attr);
			free(attr);
		} else if (strcasecmp(key, "database") == 0 && dbname == NULL) {
			if (dbname)
				free(dbname);
			dbname = attr;
#ifdef ODBCDEBUG
		} else if (strcasecmp(key, "logfile") == 0 &&
			   getenv("ODBCDEBUG") == NULL) {
			/* environment trumps everything */
			if (ODBCdebug)
				free((void *) ODBCdebug); /* discard const */
			ODBCdebug = attr;
			allocated = 1;
#endif
		} else
			free(attr);
		free(key);
	}
	if (n < 0)
		goto nomem;

	if (dsn) {
		if (uid == NULL) {
			n = SQLGetPrivateProfileString(dsn, "uid", "", buf, sizeof(buf), "odbc.ini");
			if (n > 0 && buf[0]) {
				uid = strdup(buf);
				if (uid == NULL)
					goto nomem;
			}
		}
		if (pwd == NULL) {
			n = SQLGetPrivateProfileString(dsn, "pwd", "", buf, sizeof(buf), "odbc.ini");
			if (n > 0 && buf[0]) {
				pwd = strdup(buf);
				if (pwd == NULL)
					goto nomem;
			}
		}
		if (host == NULL) {
			n = SQLGetPrivateProfileString(dsn, "host", "", buf, sizeof(buf), "odbc.ini");
			if (n > 0 && buf[0]) {
				host = strdup(buf);
				if (host == NULL)
					goto nomem;
			}
		}
		if (port == 0) {
			n = SQLGetPrivateProfileString(dsn, "port", "", buf, sizeof(buf), "odbc.ini");
			if (n > 0 && buf[0]) {
				port = atoi(buf);
			}
		}
		if (dbname == NULL) {
			n = SQLGetPrivateProfileString(dsn, "database", "", buf, sizeof(buf), "odbc.ini");
			if (n > 0 && buf[0]) {
				dbname = strdup(buf);
				if (dbname == NULL)
					goto nomem;
			}
		}
#ifdef ODBCDEBUG
		if (!allocated && getenv("ODBCDEBUG") == NULL) {
			/* if not set from InConnectionString argument
			 * or environment, look in profile */
			n = SQLGetPrivateProfileString(dsn, "logfile", "", buf, sizeof(buf), "odbc.ini");
			if (n > 0 && buf[0]) {
				if (ODBCdebug)
					free((void *) ODBCdebug); /* discard const */
				ODBCdebug = strdup(buf);
			}
		}
#endif
	}

	if (uid != NULL && pwd != NULL) {
		rc = MNDBConnect(dbc, (SQLCHAR *) dsn, SQL_NTS, (SQLCHAR *) uid, SQL_NTS, (SQLCHAR *) pwd, SQL_NTS, host, port, dbname);
		if (SQL_SUCCEEDED(rc)) {
			rc = ODBCConnectionString(rc, dbc, OutConnectionString,
						  BufferLength,
						  StringLength2Ptr,
						  dsn, uid, pwd, host, port,
						  dbname);
		}
	} else {
		if (uid == NULL) {
			if (BufferLength > 0)
				strncpy((char *) OutConnectionString, "UID:Login ID=?;", BufferLength);
			len += 15;
			OutConnectionString += 15;
			BufferLength -= 15;
		}
		if (pwd == NULL) {
			if (BufferLength > 0)
				strncpy((char *) OutConnectionString, "PWD:Password=?;", BufferLength);
			len += 15;
			OutConnectionString += 15;
			BufferLength -= 15;
		}
		if (host == NULL) {
			if (BufferLength > 0)
				strncpy((char *) OutConnectionString, "*HOST:Server=?;", BufferLength);
			len += 15;
			OutConnectionString += 15;
			BufferLength -= 15;
		}
		if (port == 0) {
			if (BufferLength > 0)
				strncpy((char *) OutConnectionString, "*PORT:Port=?;", BufferLength);
			len += 13;
			OutConnectionString += 13;
			BufferLength -= 13;
		}
		if (dbname == NULL) {
			if (BufferLength > 0)
				strncpy((char *) OutConnectionString, "*DATABASE:Database=?;", BufferLength);
			len += 21;
			OutConnectionString += 21;
			BufferLength -= 21;
		}
#ifdef ODBCDEBUG
		if (ODBCdebug == NULL) {
			if (BufferLength > 0)
				strncpy((char *) OutConnectionString, "*LOGFILE:Debug log file=?;", BufferLength);
			len += 26;
			OutConnectionString += 26;
			BufferLength -= 26;
		}
#endif

		if (StringLength2Ptr)
			*StringLength2Ptr = len;

		rc = SQL_NEED_DATA;
	}

  bailout:
	if (dsn)
		free(dsn);
	if (uid)
		free(uid);
	if (pwd)
		free(pwd);
	if (host)
		free(host);
	if (dbname)
		free(dbname);
	return rc;

  nomem:
	/* Memory allocation error */
	addDbcError(dbc, "HY001", NULL, 0);
	rc = SQL_ERROR;
	goto bailout;
}
Example #25
0
static int
mymain(void)
{
    int ret = 0;
    char *map = NULL;

    abs_top_srcdir = getenv("abs_top_srcdir");
    if (!abs_top_srcdir)
        abs_top_srcdir = "..";

    if (virAsprintf(&map, "%s/src/cpu/cpu_map.xml", abs_top_srcdir) < 0 ||
        cpuMapOverride(map) < 0) {
        VIR_FREE(map);
        return EXIT_FAILURE;
    }

#define DO_TEST(arch, api, name, host, cpu,                             \
                models, nmodels, preferred, result)                     \
    do {                                                                \
        struct data data = {                                            \
            arch, api, host, cpu, models,                               \
            models == NULL ? NULL : #models,                            \
            nmodels, preferred, result    \
        };                                                              \
        if (cpuTestRun(name, &data) < 0)                                \
            ret = -1;                                                   \
    } while (0)

#define DO_TEST_COMPARE(arch, host, cpu, result)                        \
    DO_TEST(arch, API_COMPARE,                                          \
            host "/" cpu " (" #result ")",                              \
            host, cpu, NULL, 0, NULL, result)

#define DO_TEST_UPDATE(arch, host, cpu, result)                         \
    do {                                                                \
        DO_TEST(arch, API_UPDATE,                                       \
                cpu " on " host,                                        \
                host, cpu, NULL, 0, NULL, 0);                           \
        DO_TEST_COMPARE(arch, host, host "+" cpu, result);              \
    } while (0)

#define DO_TEST_BASELINE(arch, name, result)                            \
    DO_TEST(arch, API_BASELINE, name, NULL, "baseline-" name,           \
            NULL, 0, NULL, result)

#define DO_TEST_HASFEATURE(arch, host, feature, result)                 \
    DO_TEST(arch, API_HAS_FEATURE,                                      \
            host "/" feature " (" #result ")",                          \
            host, feature, NULL, 0, NULL, result)

#define DO_TEST_GUESTDATA(arch, host, cpu, models, preferred, result)   \
    DO_TEST(arch, API_GUEST_DATA,                                       \
            host "/" cpu " (" #models ", pref=" #preferred ")",         \
            host, cpu, models,                                          \
            models == NULL ? 0 : sizeof(models) / sizeof(char *),       \
            preferred, result)

    /* host to host comparison */
    DO_TEST_COMPARE("x86", "host", "host", IDENTICAL);
    DO_TEST_COMPARE("x86", "host", "host-better", INCOMPATIBLE);
    DO_TEST_COMPARE("x86", "host", "host-worse", SUPERSET);
    DO_TEST_COMPARE("x86", "host", "host-amd-fake", INCOMPATIBLE);
    DO_TEST_COMPARE("x86", "host", "host-incomp-arch", INCOMPATIBLE);
    DO_TEST_COMPARE("x86", "host", "host-no-vendor", IDENTICAL);
    DO_TEST_COMPARE("x86", "host-no-vendor", "host", INCOMPATIBLE);

    /* guest to host comparison */
    DO_TEST_COMPARE("x86", "host", "bogus-model", ERROR);
    DO_TEST_COMPARE("x86", "host", "bogus-feature", ERROR);
    DO_TEST_COMPARE("x86", "host", "min", SUPERSET);
    DO_TEST_COMPARE("x86", "host", "pentium3", SUPERSET);
    DO_TEST_COMPARE("x86", "host", "exact", SUPERSET);
    DO_TEST_COMPARE("x86", "host", "exact-forbid", INCOMPATIBLE);
    DO_TEST_COMPARE("x86", "host", "exact-forbid-extra", SUPERSET);
    DO_TEST_COMPARE("x86", "host", "exact-disable", SUPERSET);
    DO_TEST_COMPARE("x86", "host", "exact-disable2", SUPERSET);
    DO_TEST_COMPARE("x86", "host", "exact-disable-extra", SUPERSET);
    DO_TEST_COMPARE("x86", "host", "exact-require", SUPERSET);
    DO_TEST_COMPARE("x86", "host", "exact-require-extra", INCOMPATIBLE);
    DO_TEST_COMPARE("x86", "host", "exact-force", SUPERSET);
    DO_TEST_COMPARE("x86", "host", "strict", INCOMPATIBLE);
    DO_TEST_COMPARE("x86", "host", "strict-full", IDENTICAL);
    DO_TEST_COMPARE("x86", "host", "strict-disable", IDENTICAL);
    DO_TEST_COMPARE("x86", "host", "strict-force-extra", IDENTICAL);
    DO_TEST_COMPARE("x86", "host", "guest", SUPERSET);
    DO_TEST_COMPARE("x86", "host", "pentium3-amd", INCOMPATIBLE);
    DO_TEST_COMPARE("x86", "host-amd", "pentium3-amd", SUPERSET);
    DO_TEST_COMPARE("x86", "host-worse", "nehalem-force", IDENTICAL);

    /* guest updates for migration
     * automatically compares host CPU with the result */
    DO_TEST_UPDATE("x86", "host", "min", IDENTICAL);
    DO_TEST_UPDATE("x86", "host", "pentium3", IDENTICAL);
    DO_TEST_UPDATE("x86", "host", "guest", SUPERSET);
    DO_TEST_UPDATE("x86", "host", "host-model", IDENTICAL);
    DO_TEST_UPDATE("x86", "host", "host-model-nofallback", IDENTICAL);
    DO_TEST_UPDATE("x86", "host", "host-passthrough", IDENTICAL);

    /* computing baseline CPUs */
    DO_TEST_BASELINE("x86", "incompatible-vendors", -1);
    DO_TEST_BASELINE("x86", "no-vendor", 0);
    DO_TEST_BASELINE("x86", "some-vendors", 0);
    DO_TEST_BASELINE("x86", "1", 0);
    DO_TEST_BASELINE("x86", "2", 0);

    /* CPU features */
    DO_TEST_HASFEATURE("x86", "host", "vmx", YES);
    DO_TEST_HASFEATURE("x86", "host", "lm", YES);
    DO_TEST_HASFEATURE("x86", "host", "sse4.1", YES);
    DO_TEST_HASFEATURE("x86", "host", "3dnowext", NO);
    DO_TEST_HASFEATURE("x86", "host", "skinit", NO);
    DO_TEST_HASFEATURE("x86", "host", "foo", FAIL);

    /* computing guest data and decoding the data into a guest CPU XML */
    DO_TEST_GUESTDATA("x86", "host", "guest", NULL, NULL, 0);
    DO_TEST_GUESTDATA("x86", "host-better", "pentium3", NULL, NULL, 0);
    DO_TEST_GUESTDATA("x86", "host-better", "pentium3", NULL, "pentium3", 0);
    DO_TEST_GUESTDATA("x86", "host-better", "pentium3", NULL, "core2duo", 0);
    DO_TEST_GUESTDATA("x86", "host-worse", "guest", NULL, NULL, 0);
    DO_TEST_GUESTDATA("x86", "host", "strict-force-extra", NULL, NULL, 0);
    DO_TEST_GUESTDATA("x86", "host", "nehalem-force", NULL, NULL, 0);
    DO_TEST_GUESTDATA("x86", "host", "guest", model486, NULL, 0);
    DO_TEST_GUESTDATA("x86", "host", "guest", models, NULL, 0);
    DO_TEST_GUESTDATA("x86", "host", "guest", models, "Penryn", 0);
    DO_TEST_GUESTDATA("x86", "host", "guest", models, "qemu64", 0);
    DO_TEST_GUESTDATA("x86", "host", "guest", nomodel, NULL, -1);
    DO_TEST_GUESTDATA("x86", "host", "guest-nofallback", models, "Penryn", -1);
    DO_TEST_GUESTDATA("x86", "host", "host+host-model", models, "Penryn", 0);
    DO_TEST_GUESTDATA("x86", "host", "host+host-model-nofallback",
                      models, "Penryn", -1);

    VIR_FREE(map);
    return (ret == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
}
Example #26
0
int main(int argc,char *argv[]) {

	int c,rcode=0,colnum=0,srcfsize;
	long int numLines=10000, fsize=5, pref_indicator=0;
	char seperator=',';
	char *col_stmt=NULL;
	char *ifname=NULL,*ofname=NULL;
	FILE *ofile=NULL, *ifile=NULL;
	short int prefix_select=0;
	//char buff[MAX_LENGTH];
	char buff[2048];
	int quot_val = 0;

	arg_options argopts = { 0 , 0, 0, 0, 0, 0, 0, 0, 0 };

	while ((c = getopt(argc, argv, "vs:hnaf:o:il:z:c:")) != -1 ) 
		switch(c) {
			case 'v':
				argopts.ver_opt = 1;
			break;
			
			case 's':
				seperator = optarg[0];
			break;

			case 'h':
				Help(0);
			break;

			case 'n':
				argopts.num_opt = 1;
			break;

			case 'a':
				argopts.alph_opt = 1;
			break;

			case 'f':
				ifname = optarg;
				argopts.ifile_opt = 1;
			break;

			case 'o':
				argopts.ofile_opt = 1;
				ofname = optarg;

			break;
		
			case 'i':
				argopts.incl_opt = 1;
			break;

			case 'l':
				argopts.line_opt =1;
				numLines = atoi(optarg);
			break;

			case 'z':
				argopts.size_opt =1;
				fsize = atoi(optarg);
			break;
			
			case 'c':
				col_stmt = optarg;
			break;	

			default:
				Help(1);
			break;
		}

	if (argopts.ifile_opt == 0) {
		fprintf(stderr,"an input file must be specified\n");
		Help(1);
	}

	if ( (argopts.num_opt == 1) && (argopts.alph_opt == 1 ) ) {
		fprintf(stderr,"only one of the arguments should be specified ( -n  \\ -a) \n");
		Help(2);
	}
	else if ( argopts.alph_opt == 1 )
		fsize = fsize * 1024;

	if (argopts.alph_opt == 1 )
		prefix_select = 1;
	else
		prefix_select = 0;

	if (getenv("CSVS_SEPERATOR"))
		strncpy(&seperator,getenv("CSVS_SEPERATOR"),1);

	if (getenv("CSVS_OUTPUT"))
		ofname = getenv("CSVS_OUTPUT");

	if (getenv("CSVS_LINE_NUMBER"))
		numLines = atoi(getenv("CSVS_LINE_NUMBER"));

	if ( (getenv("CSVS_FILE_SIZE")) && (!getenv("CSVS_LINE_NUMBER")) ) 
		fsize = atoi(getenv("CSVS_FILE_SIZE")) * 1024;
	
	if ( getenv("CSVS_COLUMNS_NAME") )
		col_stmt = getenv("CSVS_COLUMNS_NAME");	
	
	//  openning the read file 
	
	if (ifile = fopen(ifname,"r")){
		if ( argopts.ver_opt == 1 )
			printf("the file %s is o.k.\n",ifname);

		argopts.ifile_opt = 1;
	}

	else {
		fprintf(stderr,"the file \"%s\" can not be opened\n",ifname);
		exit(1);
	}

	// 1) chicking if the read file is not empty 
	
	if (ifile) {

		fseek (ifile ,0, SEEK_END);
		srcfsize = ftell(ifile);

		if ( srcfsize == 0 ) {
			fclose(ifile);
			fprintf(stderr,"The Input file is empty !!!, exiting\n");
			exit(4);
		}
	}	
	
	// 2) setting the new file name according to user choice & \
	// creating the new file for writing (with a function)

	if ( argopts.ofile_opt == 0 ) {
	
		ofname = ifname;
		ofname =  basename(ofname);
	}


	if (argopts.alph_opt == 1 ) 
		strcat(ofname,".a");
	else
		strcat(ofname,".1");
	
 	if ( argopts.ver_opt == 1 )
		printf("the first output file name is : %s \n",ofname);

	// going over the read file and making sure each line is CSV competable
	

	fseek (ifile ,0, SEEK_SET);

	while( fgets(buff,2048,ifile) != NULL )  {


                if (strlen(buff) < (colnum+1))
                        break;
	
		if ( col_stmt == NULL ) {
		
			colnum = firstlinetst(buff,argopts.ver_opt,seperator,&quot_val);	
			col_stmt = (char *)calloc(strlen(buff),sizeof(char));
			strcpy(col_stmt,buff);
			continue;
		}

		

	}

	// 5) for each approved line inserting it to the new file while checking predefine limits
	// 6) if the write file as reached a limit start a new file
	// 7) if the read file is done , close all the files
	// 8) 
	


   return rcode;
}
Example #27
0
int sulogin_main(int argc UNUSED_PARAM, char **argv)
{
	char *cp;
	int timeout = 0;
	struct passwd *pwd;
	const char *shell;
#if ENABLE_FEATURE_SHADOWPASSWDS
	/* Using _r function to avoid pulling in static buffers */
	char buffer[256];
	struct spwd spw;
#endif

	logmode = LOGMODE_BOTH;
	openlog(applet_name, 0, LOG_AUTH);

	opt_complementary = "t+"; /* -t N */
	getopt32(argv, "t:", &timeout);

	if (argv[optind]) {
		close(0);
		close(1);
		dup(xopen(argv[optind], O_RDWR));
		close(2);
		dup(0);
	}

	/* Malicious use like "sulogin /dev/sda"? */
	if (!isatty(0) || !isatty(1) || !isatty(2)) {
		logmode = LOGMODE_SYSLOG;
		bb_error_msg_and_die("not a tty");
	}

	/* Clear dangerous stuff, set PATH */
	sanitize_env_if_suid();

// bb_askpass() already handles this
//	signal(SIGALRM, catchalarm);

	pwd = getpwuid(0);
	if (!pwd) {
		goto auth_error;
	}

#if ENABLE_FEATURE_SHADOWPASSWDS
	{
		/* getspnam_r may return 0 yet set result to NULL.
		 * At least glibc 2.4 does this. Be extra paranoid here. */
		struct spwd *result = NULL;
		int r = getspnam_r(pwd->pw_name, &spw, buffer, sizeof(buffer), &result);
		if (r || !result) {
			goto auth_error;
		}
		pwd->pw_passwd = result->sp_pwdp;
	}
#endif

	while (1) {
		char *encrypted;
		int r;

		/* cp points to a static buffer that is zeroed every time */
		cp = bb_askpass(timeout,
				"Give root password for system maintenance\n"
				"(or type Control-D for normal startup):");

		if (!cp || !*cp) {
			bb_info_msg("Normal startup");
			return 0;
		}
		encrypted = pw_encrypt(cp, pwd->pw_passwd, 1);
		r = strcmp(encrypted, pwd->pw_passwd);
		free(encrypted);
		if (r == 0) {
			break;
		}
		bb_do_delay(FAIL_DELAY);
		bb_error_msg("login incorrect");
	}
	memset(cp, 0, strlen(cp));
//	signal(SIGALRM, SIG_DFL);

	bb_info_msg("System Maintenance Mode");

	USE_SELINUX(renew_current_security_context());

	shell = getenv("SUSHELL");
	if (!shell)
		shell = getenv("sushell");
	if (!shell) {
		shell = "/bin/sh";
		if (pwd->pw_shell[0])
			shell = pwd->pw_shell;
	}
	/* Exec login shell with no additional parameters. Never returns. */
	run_shell(shell, 1, NULL, NULL);

 auth_error:
	bb_error_msg_and_die("no password entry for root");
}
Example #28
0
int
main(int argc, char *argv[])
{
	char exepath[MAX_PATH];
	char linkpath[MAX_PATH];
	HRESULT hres;
	char *install_dir;
	char *exe;
	char *linkname;

	(void) get_version_info();

	/* Pull in the parameter. */
	if (argc != 4) {
	    	fprintf(stderr, "usage: %s install-dir exe linkname\n",
			argv[0]);
		return 1;
	}
	install_dir = argv[1];
	exe = argv[2];
	linkname = argv[3];
	sprintf(exepath, "%s\\%s", install_dir, exe);

	/* Figure out the link path. */
	if (is_nt) {
	    	char *userprof;

		userprof = getenv("USERPROFILE");
		if (userprof == NULL) {
			fprintf(stderr, "Sorry, I can't figure out where your user "
				"profile is.\n");
			return 1;
		}
		sprintf(linkpath, "%s\\Desktop\\%s.lnk", userprof, linkname);
	} else {
		char *windir;

		windir = getenv("WinDir");
		if (windir == NULL) {
			printf("Sorry, I can't figure out where %%WinDir%% "
				"is.\n");
			return -1;
		}
		sprintf(linkpath, "%s\\Desktop\\%s.pif", windir, linkname);
	}

	/* Create the link. */
	if (is_nt)
		hres = CreateLink(
			exepath,
			linkpath,
			NULL,
			NULL,
			install_dir,
			44,
			80,
			L"Lucida Console",
			0,
			0);
	else
	    	hres = Piffle(
			linkname,
			exepath,
			linkpath,
			"",
			"",
			install_dir,
			44,
			80,
			"Lucida Console");

	if (hres) {
		fprintf(stderr, "Link creation failed.\n");
	}

	return hres;
}
Example #29
0
int
main(void)
{

  XGCValues       controlGCVals;
  int             i,code;
  view2DStruct    viewData;

  char property[256];
  char *prop = &property[0];
  char *str_type[20];
  XrmValue value;


  /**** Set up display ****/
  if ((dsply = XOpenDisplay(getenv("DISPLAY"))) == NULL)
    fprintf(stderr,"Could not open the display.\n");
  scrn  = DefaultScreen(dsply);
  rtWindow  = RootWindow(dsply,scrn);

  /**** link Xwindows to viewports - X10 feature ****/
  table        = XCreateAssocTable(nbuckets);

  /**** Create FriCAS color map ****/
  totalColors = XInitSpadFill(dsply,scrn,&colorMap,
                              &totalHues,&totalSolidShades,
                              &totalDitheredAndSolids,&totalShades);

  if (totalColors < 0) {
    fprintf(stderr,">>Error: Could not allocate all the necessary colors.\n");
    exitWithAck(RootWindow(dsply,scrn),Window,-1);
  }

  mergeDatabases();


  /*** Determine whether monochrome or color is used ***/
  if (XrmGetResource(rDB,"Axiom.2D.monochrome","",str_type,&value) == True)
    (void) strncpy(prop,value.addr,(int)value.size);
  else
    (void) strcpy(prop, "off");

  mono = ((totalSolid == 2) || (strcmp(prop,"on") == 0));

  if (XrmGetResource(rDB,"Axiom.2D.inverse","",str_type,&value) == True)
    (void) strncpy(prop,value.addr,(int)value.size);
  else
    (void) strcpy(prop, "off");

  if (mono)
    if (strcmp(prop,"on") == 0) {             /* 0 if equal (inverse video) */
      foregroundColor = WhitePixel(dsply,scrn);
      backgroundColor = BlackPixel(dsply,scrn);
    } else {                                  /* off (no inverse video) */
      foregroundColor = BlackPixel(dsply,scrn);
      backgroundColor = WhitePixel(dsply,scrn);
    }
  else   /* inverse of inverse in color (for some strange reason) */
    if (strcmp(prop,"on") == 0) {         /* 0 if equal (inverse video) */
      foregroundColor = WhitePixel(dsply,scrn);
      backgroundColor = BlackPixel(dsply,scrn);
    } else {                                  /* off (no inverse video) */
      foregroundColor = BlackPixel(dsply,scrn);
      backgroundColor = WhitePixel(dsply,scrn);
    }


  /* read default file name for postScript output */
  if (XrmGetResource(rDB,
                     "Axiom.2D.postscriptFile",
                     "",
                     str_type, &value) == True)
    (void) strncpy(prop,value.addr,(int)value.size);
  else
    (void) strcpy(prop, "axiom2D.ps");

  PSfilename = (char *)malloc(strlen(prop)+1);
  strcpy(PSfilename,prop);



  /**** Open global fonts ****/
  serverFont = XQueryFont(dsply,XGContextFromGC(DefaultGC(dsply,scrn)));

  if (XrmGetResource(rDB,
                     "Axiom.2D.messageFont",
                     "Axiom.2D.Font",
                     str_type, &value) == True)
    (void) strncpy(prop,value.addr,(int)value.size);
  else
    (void) strcpy(prop,messageFontDefault);
  if ((globalFont = XLoadQueryFont(dsply, prop)) == NULL) {
    fprintf(stderr,
            "Warning:  could not get the %s font for messageFont\n",prop);
    globalFont = serverFont;
  }

  if (XrmGetResource(rDB,
                     "Axiom.2D.buttonFont",
                     "Axiom.2D.Font",
                     str_type, &value) == True)
    (void) strncpy(prop,value.addr,(int)value.size);
  else
    (void) strcpy(prop,buttonFontDefault);
  if ((buttonFont = XLoadQueryFont(dsply, prop)) == NULL) {
    fprintf(stderr,
            "Warning:  could not get the %s font for buttonFont\n",prop);
    buttonFont = serverFont;
  }

  if (XrmGetResource(rDB,
                     "Axiom.2D.headerFont",
                     "Axiom.2D.Font",
                     str_type, &value) == True)
     (void) strncpy(prop,value.addr,(int)value.size);
  else
    (void) strcpy(prop,headerFontDefault);

  if ((headerFont = XLoadQueryFont(dsply, prop)) == NULL) {
    fprintf(stderr,
            "Warning:  could not get the %s font for headerFont\n",prop);
    headerFont = serverFont;
  }

  if (XrmGetResource(rDB,
                     "Axiom.2D.titleFont",
                     "Axiom.2D.Font",
                     str_type,&value) == True)
    (void) strncpy(prop,value.addr,(int)value.size);
  else
    (void) strcpy(prop,titleFontDefault);

  if ((titleFont = XLoadQueryFont(dsply, prop)) == NULL) {
    fprintf(stderr,
            "Warning:  could not get the %s font for titleFont\n",prop);
    titleFont = serverFont;
  }

  if (XrmGetResource(rDB,
                     "Axiom.2D.graphFont",
                     "Axiom.2D.Font",
                     str_type,&value) == True)
    (void) strncpy(prop,value.addr,(int)value.size);
  else
    (void) strcpy(prop,graphFontDefault);

  if ((graphFont = XLoadQueryFont(dsply, prop)) == NULL) {
    fprintf(stderr,
            "Warning:  could not get the %s font for graphFont\n",prop);
    graphFont = serverFont;
  }

  if (XrmGetResource(rDB,
                     "Axiom.2D.unitFont",
                     "Axiom.2D.Font",
                     str_type,&value) == True)
    (void) strncpy(prop,value.addr,(int)value.size);
  else
    (void) strcpy(prop,unitFontDefault);

  if ((unitFont = XLoadQueryFont(dsply, prop)) == NULL) {
     fprintf(stderr,
             "Warning:  could not get the %s font for unitFont\n",prop);
     unitFont = serverFont;
  }


  /**** Create widely used Graphic Contexts ****/
  PSGlobalInit();
  /* must initiate before using any G/PS functions
     need character name: used as postscript GC variable
     need to create ps GCs for all GCs used by drawings in viewWindow */

  /* globalGC1 */

  controlGCVals.foreground = monoColor(axesColorDefault);
  controlGCVals.background = backgroundColor;
  globalGC1 = XCreateGC(dsply,rtWindow,GCForeground | GCBackground ,
                        &controlGCVals);
  carefullySetFont(globalGC1,globalFont);


  /* create the equivalent GCs for ps */
  PSCreateContext(globalGC1, "globalGC1", psNormalWidth, psButtCap,
                  psMiterJoin, psWhite, psBlack);

  /* controlMessageGC */

  controlGCVals.foreground = controlMessageColor;
  controlMessageGC = XCreateGC(dsply,rtWindow,GCForeground | GCBackground
                               ,&controlGCVals);
  carefullySetFont(controlMessageGC,globalFont);

  /* globalGC2 */

  controlGCVals.foreground = monoColor(labelColor);
  controlGCVals.background = backgroundColor;
  globalGC2 = XCreateGC(dsply,rtWindow,GCForeground | GCBackground,
                        &controlGCVals);
  carefullySetFont(globalGC2,buttonFont);
  PSCreateContext(globalGC2, "globalGC2", psNormalWidth, psButtCap,
                  psMiterJoin, psWhite, psBlack);

  /* trashGC  */

  trashGC = XCreateGC(dsply,rtWindow,0,&controlGCVals);
  carefullySetFont(trashGC,buttonFont);
  PSCreateContext(trashGC, "trashGC", psNormalWidth, psButtCap,
                  psMiterJoin, psWhite, psBlack);

  /* globGC */

  globGC = XCreateGC(dsply,rtWindow,0,&controlGCVals);
  carefullySetFont(globGC,headerFont);
  PSCreateContext(globGC, "globGC", psNormalWidth, psButtCap,
                  psMiterJoin, psWhite, psBlack);

  /* anotherGC  */

  controlGCVals.line_width = colorWidth;
  anotherGC  = XCreateGC(dsply,rtWindow,GCBackground,&controlGCVals);
  carefullySetFont(anotherGC,titleFont);
  PSCreateContext(anotherGC, "anotherGC", psNormalWidth, psButtCap,
                  psMiterJoin, psWhite, psBlack);

  /* processGC */

  gcVals.background = backgroundColor;
  processGC         = XCreateGC(dsply,rtWindow,GCBackground ,&gcVals);
  carefullySetFont(processGC,buttonFont);

  /* graphGC */

  graphGC           = XCreateGC(dsply,rtWindow,GCBackground,&gcVals);
  carefullySetFont(graphGC,graphFont);
  PSCreateContext(graphGC, "graphGC", psNormalWidth, psButtCap,
                  psMiterJoin, psWhite, psBlack);

  /* unitGC */

  unitGC            = XCreateGC(dsply,rtWindow,GCBackground ,&gcVals);
  carefullySetFont(unitGC,unitFont);
  PSCreateContext(unitGC, "unitGC", psNormalWidth, psButtCap,
                  psMiterJoin, psWhite, psBlack);

  /**** Initialize Graph States ****/

  for (i=0; i<maxGraphs; i++) {
    graphStateArray[i].scaleX = 0.9;
    graphStateArray[i].scaleY = 0.9;
    graphStateArray[i].deltaX = 0.0;
    graphStateArray[i].deltaY = 0.0;
    graphStateArray[i].centerX = 0.0;
    graphStateArray[i].centerY = 0.0;
    graphStateArray[i].pointsOn  = yes;
    graphStateArray[i].connectOn = yes;
    graphStateArray[i].splineOn  = no;
    graphStateArray[i].axesOn    = yes;
    graphStateArray[i].unitsOn   = no;
    graphStateArray[i].showing   = no;
    graphStateArray[i].selected  = no;
    graphStateBackupArray[i] = graphStateArray[i];
  }

  /**** Get Data from the Viewport Manager ****/

  i = 123;
  code=check(write(Socket,&i,intSize));

  /* Check if I am getting stuff from FriCAS or, if I am viewAlone. */
  readViewman(&viewAloned,intSize);
  readViewman(&viewData,sizeof(view2DStruct));
  readViewman(&i,intSize);

  if (!(viewData.title = (char *)malloc(i))) {
    fprintf(stderr,
            "ERROR: Ran out of memory trying to receive the title.\n");
    exitWithAck(RootWindow(dsply,scrn),Window,-1);
  }
  readViewman(viewData.title,i);

  for (i=0; i<maxGraphs; i++) {
    readViewman(&(graphArray[i].key),intSize);
    if (graphArray[i].key) {            /** this graph slot has data **/
      getGraphFromViewman(i);
    } /* if graph exists (graphArray[i].key is not zero) */
  } /* for i in graphs */

  viewport = makeView2D(&viewData);
  control = viewport->controlPanel;

  bsdSignal(SIGTERM,goodbye,DontRestartSystemCalls);

  /* send acknowledgement to viewport manager */
  i = 345;
  check(write(Socket,&(viewport->viewWindow),sizeof(Window)));

  processEvents();

  goodbye(-1);
  return(0);  /* control never reaches here but compiler complains */
} /* main() */
Example #30
0
int telnet_main(int argc, char **argv)
{
	char *host;
	int port;
	int len;
#ifdef USE_POLL
	struct pollfd ufds[2];
#else
	fd_set readfds;
	int maxfd;
#endif

	INIT_G();

#if ENABLE_FEATURE_AUTOWIDTH
	get_terminal_width_height(0, &G.win_width, &G.win_height);
#endif

#if ENABLE_FEATURE_TELNET_TTYPE
	G.ttype = getenv("TERM");
#endif

	if (tcgetattr(0, &G.termios_def) >= 0) {
		G.do_termios = 1;
		G.termios_raw = G.termios_def;
		cfmakeraw(&G.termios_raw);
	}

	if (argc < 2)
		bb_show_usage();

#if ENABLE_FEATURE_TELNET_AUTOLOGIN
	if (1 & getopt32(argv, "al:", &G.autologin))
		G.autologin = getenv("USER");
	argv += optind;
#else
	argv++;
#endif
	if (!*argv)
		bb_show_usage();
	host = *argv++;
	port = bb_lookup_port(*argv ? *argv++ : "telnet", "tcp", 23);
	if (*argv) /* extra params?? */
		bb_show_usage();

	G.netfd = create_and_connect_stream_or_die(host, port);

	setsockopt(G.netfd, SOL_SOCKET, SO_KEEPALIVE, &const_int_1, sizeof(const_int_1));

	signal(SIGINT, fgotsig);

#ifdef USE_POLL
	ufds[0].fd = 0; ufds[1].fd = G.netfd;
	ufds[0].events = ufds[1].events = POLLIN;
#else
	FD_ZERO(&readfds);
	FD_SET(0, &readfds);
	FD_SET(G.netfd, &readfds);
	maxfd = G.netfd + 1;
#endif

	while (1) {
#ifndef USE_POLL
		fd_set rfds = readfds;

		switch (select(maxfd, &rfds, NULL, NULL, NULL))
#else
		switch (poll(ufds, 2, -1))
#endif
		{
		case 0:
			/* timeout */
		case -1:
			/* error, ignore and/or log something, bay go to loop */
			if (G.gotsig)
				conescape();
			else
				sleep(1);
			break;
		default:

#ifdef USE_POLL
			if (ufds[0].revents) /* well, should check POLLIN, but ... */
#else
			if (FD_ISSET(0, &rfds))
#endif
			{
				len = read(0, G.buf, DATABUFSIZE);
				if (len <= 0)
					doexit(0);
				TRACE(0, ("Read con: %d\n", len));
				handlenetoutput(len);
			}

#ifdef USE_POLL
			if (ufds[1].revents) /* well, should check POLLIN, but ... */
#else
			if (FD_ISSET(G.netfd, &rfds))
#endif
			{
				len = read(G.netfd, G.buf, DATABUFSIZE);
				if (len <= 0) {
					write_str(1, "Connection closed by foreign host\r\n");
					doexit(1);
				}
				TRACE(0, ("Read netfd (%d): %d\n", G.netfd, len));
				handlenetinput(len);
			}
		}
	}
}