Exemple #1
0
static void
test_double_vtable (void)
{
  if (g_test_subprocess ())
    {
      GMemVTable vtable = { malloc, realloc, free, NULL, NULL, NULL };

      g_mem_set_vtable (&vtable);
      g_mem_set_vtable (&vtable);
      exit (0);
    }
  g_test_trap_subprocess (NULL, 0, 0);
  g_test_trap_assert_failed ();
  g_test_trap_assert_stderr ("*can only be set once*");
}
Exemple #2
0
static void
gimp_init_malloc (void)
{
#ifdef GIMP_GLIB_MEM_PROFILER
  g_mem_set_vtable (glib_mem_profiler_table);
  g_atexit (g_mem_profile);
#endif

#ifdef __GLIBC__
  /* Tweak memory allocation so that memory allocated in chunks >= 4k
   * (64x64 pixel 1bpp tile) gets returned to the system when free()'d.
   *
   * The default value for M_MMAP_THRESHOLD in glibc-2.3 is 128k.
   * This is said to be an empirically derived value that works well
   * in most systems. Lowering it to 4k is thus probably not the ideal
   * solution.
   *
   * An alternative to tuning this parameter would be to use
   * malloc_trim(), for example after releasing a large tile-manager.
   */
#if 0
  mallopt (M_MMAP_THRESHOLD, TILE_WIDTH * TILE_HEIGHT);
#endif
#endif
}
Exemple #3
0
void gsk_set_debug_mem_vtable (const char *executable_filename)
{
  assert (executable_filename != NULL);
  exe_name = strdup (executable_filename);
  assert (exe_name != NULL);
  g_mem_set_vtable (&debug_mem_vtable);
}
/**
 * initialize the basic components of the chassis
 */
int chassis_frontend_init_glib() {
	const gchar *check_str = NULL;
#if 0
	g_mem_set_vtable(glib_mem_profiler_table);
#endif

	if (!GLIB_CHECK_VERSION(2, 6, 0)) {
		g_critical("the glib header are too old, need at least 2.6.0, got: %d.%d.%d", 
				GLIB_MAJOR_VERSION, GLIB_MINOR_VERSION, GLIB_MICRO_VERSION);

		return -1;
	}

	check_str = glib_check_version(GLIB_MAJOR_VERSION, GLIB_MINOR_VERSION, GLIB_MICRO_VERSION);

	if (check_str) {
		g_critical("%s, got: lib=%d.%d.%d, headers=%d.%d.%d", 
			check_str,
			glib_major_version, glib_minor_version, glib_micro_version,
			GLIB_MAJOR_VERSION, GLIB_MINOR_VERSION, GLIB_MICRO_VERSION);

		return -1;
	}

	if (!g_module_supported()) {
		g_critical("loading modules is not supported on this platform");
		return -1;
	}

	g_thread_init(NULL);

	return 0;
}
Exemple #5
0
static void
test_profiler (void)
{
  if (g_test_subprocess ())
    {
      gpointer p;
      g_mem_set_vtable (glib_mem_profiler_table);
      p = g_malloc (100);
      p = g_realloc (p, 200);
      g_free (p);
      p = g_malloc0 (1000);
      g_free (p);
      p = g_try_malloc (2000);
      p = g_try_realloc (p, 3000);
      g_free (p);
      p = g_malloc (0);
      p = g_malloc0 (0);
      p = g_realloc (NULL, 0);
      p = g_try_malloc (0);
      p = g_try_realloc (NULL, 0);
      g_mem_profile ();
      exit (0);
    }
  g_test_trap_subprocess (NULL, 0, 0);
  g_test_trap_assert_passed ();
  g_test_trap_assert_stdout ("*GLib Memory statistics*");
}
Exemple #6
0
int main (int argc, char *argv[]) {
	char *locale_dir = NULL;


#ifdef GW_DEBUG_MODE
#ifdef HAVE_GTK20
	g_mem_set_vtable ( glib_mem_profiler_table);
#endif

	gw_am_log_msg ( 0, __FILE__, __LINE__, __PRETTY_FUNCTION__, "application is starting ==> memory status : ");
	g_mem_profile ( );
#endif


#ifdef ENABLE_NLS
#ifdef GW_DEBUG_MODE
	gw_am_log_msg ( 0, __FILE__, __LINE__, __PRETTY_FUNCTION__, "NLS enabled");
#endif
	setlocale ( LC_ALL, "");
	if ( (locale_dir = gw_package_get_locale_dir ( )) != NULL) {
#ifdef GW_DEBUG_MODE
		gw_am_log_msg ( 0, __FILE__, __LINE__, __PRETTY_FUNCTION__, "Locale is %s", locale_dir);
#endif

		bindtextdomain ( PACKAGE, locale_dir);
		textdomain ( PACKAGE);
		g_free ( locale_dir);
	}
#endif

	gtk_set_locale ( );

//	g_log_set_handler ( "Gtk", G_LOG_LEVEL_WARNING, (GLogFunc) gtk_false, NULL);
//	g_log_set_handler ( "Gtk", G_LOG_LEVEL_WARNING, g_log_default_handler, NULL);
	gtk_init ( &argc, &argv);

#ifdef GW_DEBUG_MODE
	gw_am_log_msg ( 0, __FILE__, __LINE__, __PRETTY_FUNCTION__, "application is initializing ==> memory status : ");
	g_mem_profile ( );
#endif

	gw_am_init ( argc, argv);

#ifdef GW_DEBUG_MODE
	gw_am_log_msg ( 0, __FILE__, __LINE__, __PRETTY_FUNCTION__, "application is loading catalog ==> memory status : ");
	g_mem_profile ( );
#endif

	/* Enter the main loop */
	gtk_main ( );

#ifdef GW_DEBUG_MODE
	gw_am_log_msg ( 0, __FILE__, __LINE__, __PRETTY_FUNCTION__, "application is exited ==> memory status : ");
	g_mem_profile ( );
#endif

	return 0;
}
int
main (int argc, char **argv)
{
    int ret;
    g_mem_set_vtable (glib_mem_profiler_table);
    ret = rsvg_tools_main (&argc, &argv);
    g_mem_profile ();
    return ret;
}
Exemple #8
0
/* init/free */

static void
#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ > 4)
__attribute__ ((constructor))
#endif /* !__GNUC__ */
mp_init (void)
{
  GMemVTable mp_mem_table = {
    mp_malloc,
    mp_realloc,
    mp_free,
    NULL,
    NULL,
    NULL,
  };

#if 0
  gchar *envvar;

  unlink(MP_TIME_LOG);
  unlink(MP_FRAG_LOG);
  unlink(MP_USE_LOG);
  unlink(MP_BT_LOG);
  
  if( (envvar = getenv ("MP_TRACE_SIZE"))) {
    mp_trace_size = atoi (envvar);
  }
  if( (envvar = getenv ("MP_TRACE_INTERACTIVE"))) {
    mp_trace_interactive = atoi (envvar);
  }
  if( (envvar = getenv ("MP_USAGE_SCALE"))) {
    mp_usage_scale = atoi (envvar);
  }
  if( (envvar = getenv ("MP_LOG_START"))) {
    mp_log_start = atof (envvar);
  }
  if(!(mp_log_base = getenv ("MP_LOG_BASE"))) {
    mp_log_base = "/tmp/mp_";
  }
  
  /*
  if (!(time_log = fopen (MP_TIME_LOG, "wt"))) {
    fprintf(stderr,"cannot open "MP_TIME_LOG" for writing\n");
    return;
  }
  if (!(use_log = fopen (MP_USE_LOG, "wt"))) {
    fprintf(stderr,"cannot open "MP_USE_LOG" for writing\n");
    return;
  }
  */
  signal_setup();
#endif

  g_mem_set_vtable (&mp_mem_table);

#if 0
  its = mp_get_timestamp();
#endif
}
Exemple #9
0
void
mono_summarize_toggle_assertions (gboolean enable)
{
#if defined(ENABLE_CHECKED_BUILD_CRASH_REPORTING) && defined (ENABLE_OVERRIDABLE_ALLOCATORS)
	static GMemVTable g_mem_vtable_backup;
	static gboolean saved;

	if (enable) {
		g_mem_get_vtable (&g_mem_vtable_backup);
		saved = TRUE;

		GMemVTable g_mem_vtable_assert = { assert_not_reached_fn_ptr_malloc, assert_not_reached_fn_ptr_realloc, assert_not_reached_fn_ptr_free, assert_not_reached_fn_ptr_calloc };
		g_mem_set_vtable (&g_mem_vtable_assert);
	} else if (saved) {
		g_mem_set_vtable (&g_mem_vtable_backup);
		saved = FALSE;
	}

	mono_memory_barrier ();
#endif
}
Exemple #10
0
void setGeneralMemoryHandler()
{
	GMemVTable general_memory_table;

	general_memory_table.malloc=gMalloc;
	general_memory_table.realloc=gRealloc;
	general_memory_table.free=gFree;
	general_memory_table.calloc=NULL;
	general_memory_table.try_malloc=NULL;
	general_memory_table.try_realloc=NULL;

	g_mem_set_vtable(&general_memory_table);
}
Exemple #11
0
static void
test_fallback_calloc (void)
{
  if (g_test_subprocess ())
    {
      GMemVTable vtable = { malloc, realloc, free, NULL, NULL, NULL };
      gpointer p;

      g_mem_set_vtable (&vtable);
      p = g_malloc0 (1000);
      g_free (p);
      exit (0);
    }
  g_test_trap_subprocess (NULL, 0, 0);
  g_test_trap_assert_passed ();
}
Exemple #12
0
int
main (int argc, char *argv[])
{
	g_mem_set_vtable (glib_mem_profiler_table);

#if !GLIB_CHECK_VERSION (2, 35, 0)
	g_type_init ();
#endif

	test_query_events ();

	/* Print memory usage data */
	g_mem_profile ();

	return 0;
}
Exemple #13
0
int main (int argc, char *argv[])
{
	struct version v;
	show_version(&v);
	g_log_set_default_handler(logger_stdout_log, NULL);

	struct options *opt = malloc(sizeof(struct options));
	memset(opt, 0, sizeof(struct options));

	if( options_parse(opt, argc, argv) == false )
	{
		g_error("Could not parse options!\n");
	}

	if( options_validate(opt) == false )
	{
		g_error("Invalid options");
	}

	g_log_set_default_handler(logger_stdout_log, opt->stdOUT.filter);
	// gc
	if( opt->garbage != NULL )
	{
#ifdef HAVE_LIBGC
		g_message("gc mode %s", opt->garbage);
		if( g_mem_gc_friendly != TRUE )
		{
			g_error("export G_DEBUG=gc-friendly\nexport G_SLICE=always-malloc\n for gc");
		}


		static GMemVTable memory_vtable =
		{
			.malloc = GC_malloc,
			.realloc = GC_realloc,
			.free   = GC_free,
		};

		g_mem_set_vtable(&memory_vtable);
		if( strcmp(opt->garbage, "debug") == 0 )
			GC_find_leak = 1;

		// set libev allocator
		typedef void *(*moron)(void *ptr, long size);
		ev_set_allocator((moron)GC_realloc);
#endif
	}
Exemple #14
0
static void
test_incomplete_vtable (void)
{
  if (g_test_subprocess ())
    {
      GMemVTable vtable = { malloc, realloc, NULL, NULL, NULL, NULL };
      gpointer p;

      g_mem_set_vtable (&vtable);
      p = g_malloc0 (1000);
      g_free (p);
      exit (0);
    }
  g_test_trap_subprocess (NULL, 0, 0);
  g_test_trap_assert_failed ();
  g_test_trap_assert_stderr ("*lacks one of*");
}
Exemple #15
0
void eh_init_glib( void )
{
#if defined( USE_MY_VTABLE )
   static GMemVTable my_vtable;

   my_vtable.malloc      = &eh_malloc_c_style;
   my_vtable.realloc     = &eh_realloc_c_style;
   my_vtable.free        = &eh_free_c_style;
   my_vtable.calloc      = &eh_calloc_c_style;
   my_vtable.try_malloc  = &eh_malloc_c_style;
   my_vtable.try_realloc = &eh_realloc_c_style;

   g_mem_set_vtable( &my_vtable );
#else
//   g_mem_set_vtable( glib_mem_profiler_table );
#endif
}
Exemple #16
0
void
libspectrum_mem_set_vtable( libspectrum_mem_vtable_t *table )
{
  libspectrum_malloc_fn = table->malloc;
  libspectrum_calloc_fn = table->calloc;
  libspectrum_realloc_fn = table->realloc;
  libspectrum_free_fn = table->free;

#ifdef HAVE_LIB_GLIB
  {
    GMemVTable glib_table;

    glib_table.malloc = table->malloc;
    glib_table.realloc = table->realloc;
    glib_table.free = table->free;

    g_mem_set_vtable( &glib_table );
  }
#endif                  /* #ifdef HAVE_LIB_GLIB */
}
Exemple #17
0
void
frida_agent_environment_init (void)
{
  GMemVTable mem_vtable = {
    gum_malloc,
    gum_realloc,
    gum_free,
    gum_calloc,
    gum_malloc,
    gum_realloc
  };

#if defined (G_OS_WIN32) && DEBUG_HEAP_LEAKS
  int tmp_flag;

  /*_CrtSetBreakAlloc (1337);*/

  _CrtSetReportMode (_CRT_ERROR, _CRTDBG_MODE_FILE);
  _CrtSetReportFile (_CRT_ERROR, _CRTDBG_FILE_STDERR);

  tmp_flag = _CrtSetDbgFlag (_CRTDBG_REPORT_FLAG);

  tmp_flag |= _CRTDBG_ALLOC_MEM_DF;
  tmp_flag |= _CRTDBG_LEAK_CHECK_DF;
  tmp_flag &= ~_CRTDBG_CHECK_CRT_DF;

  _CrtSetDbgFlag (tmp_flag);
#endif

  gum_memory_init ();
  g_mem_set_vtable (&mem_vtable);
#if DEBUG_HEAP_LEAKS
  g_setenv ("G_SLICE", "always-malloc", TRUE);
#endif
  glib_init ();
  g_log_set_default_handler (frida_agent_on_log_message, NULL);
  g_log_set_always_fatal (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING);
  gio_init ();
  gum_init ();
}
Exemple #18
0
/**
 * Main function
 *
 * @param argc number of arguments
 * @param argv arguments
 *
 * @return Nothing
 */
int main ( int argc, char **argv )
{
#if IS_DEVELOPMENT_VERSION == 1
        initialize_debugging ( );
#endif

#if GSB_GMEMPROFILE
    g_mem_set_vtable(glib_mem_profiler_table);
#endif

#ifdef _WIN32
    main_win_32 (  argc, argv );
#else
    #ifdef GTKOSXAPPLICATION
        main_mac_osx ( argc, argv );
    #else
        main_linux ( argc, argv );
    #endif /* GTKOSXAPPLICATION || linux */
#endif /* _WIN32 */

    exit ( 0 );
}
Exemple #19
0
int
main (int argc, char *argv[])
{
  static GMemVTable secure_mem =
    {
      secentry_malloc,
      secentry_realloc,
      secentry_free,
      NULL,
      NULL,
      NULL
    };

  g_mem_set_vtable (&secure_mem);

  pinentry_init (PGMNAME);

#ifdef FALLBACK_CURSES
  if (pinentry_have_display (argc, argv))
    gtk_init (&argc, &argv);
  else
    pinentry_cmd_handler = curses_cmd_handler;
#else
  gtk_init (&argc, &argv);
#endif

  /* Consumes all arguments.  */
  if (pinentry_parse_opts (argc, argv))
    {
      printf(PGMNAME " " VERSION "\n");
      exit(EXIT_SUCCESS);
    }

  if (pinentry_loop ())
    return 1;

  return 0;
}
Exemple #20
0
Fichier : main.c Projet : juhp/ibus
gint
main (gint argc, gchar **argv)
{
    GOptionContext *context;
    BusServer *server;
    IBusBus *bus;

    GError *error = NULL;

    setlocale (LC_ALL, "");

    context = g_option_context_new ("- ibus daemon");

    g_option_context_add_main_entries (context, entries, "ibus-daemon");

    g_argv = g_strdupv (argv);
    if (!g_option_context_parse (context, &argc, &argv, &error)) {
        g_printerr ("Option parsing failed: %s\n", error->message);
        exit (-1);
    }

    if (g_mempro) {
        g_mem_set_vtable (glib_mem_profiler_table);
        signal (SIGUSR2, _sig_usr2_handler);
    }

    /* check uid */
    {
        const gchar *username = ibus_get_user_name ();
        uid_t uid = getuid ();
        struct passwd *pwd = getpwuid (uid);

        if (pwd == NULL || g_strcmp0 (pwd->pw_name, username) != 0) {
            g_printerr ("Please run ibus-daemon with login user! Do not run ibus-daemon with sudo or su.\n");
            exit (-1);
        }
    }

    /* daemonize process */
    if (daemonize) {
        if (daemon (1, 0) != 0) {
            g_printerr ("Can not daemonize ibus.\n");
            exit (-1);
        }
    }

    /* create a new process group */
    setpgrp ();

    g_type_init ();

    g_log_set_handler (G_LOG_DOMAIN,
        G_LOG_LEVEL_WARNING | G_LOG_LEVEL_DEBUG | G_LOG_FLAG_FATAL | G_LOG_FLAG_RECURSION,
        _my_log_handler,
        NULL);

    /* check if ibus-daemon is running in this session */
    if (ibus_get_address () != NULL) {
        bus = ibus_bus_new ();

        if (ibus_bus_is_connected (bus)) {
            if (!replace) {
                g_printerr ("current session already has an ibus-daemon.\n");
                exit (-1);
            }
            ibus_bus_exit (bus, FALSE);
            while (ibus_bus_is_connected (bus)) {
                g_main_context_iteration (NULL, TRUE);
            }
        }
        g_object_unref (bus);
        bus = NULL;
    }

    /* create ibus server */
    server = bus_server_get_default ();
    bus_server_listen (server);

    if (!single) {
        /* execute config component */
        if (g_strcmp0 (config, "default") == 0) {
            IBusComponent *component;
            component = bus_registry_lookup_component_by_name (BUS_DEFAULT_REGISTRY, IBUS_SERVICE_CONFIG);
            if (component == NULL || !ibus_component_start (component, g_verbose)) {
                g_printerr ("Can not execute default config program\n");
                exit (-1);
            }
        } else if (g_strcmp0 (config, "disable") != 0 && g_strcmp0 (config, "") != 0) {
            if (!execute_cmdline (config))
                exit (-1);
        }

        /* execut panel component */
        if (g_strcmp0 (panel, "default") == 0) {
            IBusComponent *component;
            component = bus_registry_lookup_component_by_name (BUS_DEFAULT_REGISTRY, IBUS_SERVICE_PANEL);
            if (component == NULL || !ibus_component_start (component, g_verbose)) {
                g_printerr ("Can not execute default panel program\n");
                exit (-1);
            }
        } else if (g_strcmp0 (panel, "disable") != 0 && g_strcmp0 (panel, "") != 0) {
            if (!execute_cmdline (panel))
                exit (-1);
        }
    }

    /* execute ibus xim server */
    if (xim) {
        if (!execute_cmdline (LIBEXECDIR"/ibus-x11 --kill-daemon"))
            exit (-1);
    }

    bus_server_run (server);

    return 0;
}
Exemple #21
0
gint
main (gint argc, gchar **argv)
{
    setlocale (LC_ALL, "");

    GOptionContext *context = g_option_context_new ("- ibus daemon");
    g_option_context_add_main_entries (context, entries, "ibus-daemon");

    g_argv = g_strdupv (argv);
    GError *error = NULL;
    if (!g_option_context_parse (context, &argc, &argv, &error)) {
        g_printerr ("Option parsing failed: %s\n", error->message);
        g_error_free (error);
        exit (-1);
    }
    if (g_gdbus_timeout < -1) {
        g_printerr ("Bad timeout (must be >= -1): %d\n", g_gdbus_timeout);
        exit (-1);
    }

    if (g_mempro) {
        g_mem_set_vtable (glib_mem_profiler_table);
        signal (SIGUSR2, _sig_usr2_handler);
    }

    /* check uid */
    {
        const gchar *username = ibus_get_user_name ();
        uid_t uid = getuid ();
        struct passwd *pwd = getpwuid (uid);

        if (pwd == NULL || g_strcmp0 (pwd->pw_name, username) != 0) {
            g_printerr ("Please run ibus-daemon with login user! Do not run ibus-daemon with sudo or su.\n");
            exit (-1);
        }
    }

    /* daemonize process */
    if (daemonize) {
        if (daemon (1, 0) != 0) {
            g_printerr ("Can not daemonize ibus.\n");
            exit (-1);
        }
    }

    /* create a new process group. this is important to kill all of its children by SIGTERM at a time in bus_ibus_impl_destroy. */
    setpgid (0, 0);

    ibus_init ();

    ibus_set_log_handler (g_verbose);

    /* check if ibus-daemon is running in this session */
    if (ibus_get_address () != NULL) {
        IBusBus *bus = ibus_bus_new ();

        if (ibus_bus_is_connected (bus)) {
            if (!replace) {
                g_printerr ("current session already has an ibus-daemon.\n");
                exit (-1);
            }
            ibus_bus_exit (bus, FALSE);
            while (ibus_bus_is_connected (bus)) {
                g_main_context_iteration (NULL, TRUE);
            }
        }
        g_object_unref (bus);
    }

    bus_server_init ();
    if (!single) {
        /* execute config component */
        if (g_strcmp0 (config, "default") == 0) {
            BusComponent *component;
            component = bus_ibus_impl_lookup_component_by_name (
                            BUS_DEFAULT_IBUS, IBUS_SERVICE_CONFIG);
            if (component) {
                bus_component_set_restart (component, restart);
            }
            if (component == NULL || !bus_component_start (component, g_verbose)) {
                g_printerr ("Can not execute default config program\n");
                exit (-1);
            }
        } else if (g_strcmp0 (config, "disable") != 0 && g_strcmp0 (config, "") != 0) {
            if (!execute_cmdline (config))
                exit (-1);
        }

        /* execute panel component */
        if (g_strcmp0 (panel, "default") == 0) {
            BusComponent *component;
            component = bus_ibus_impl_lookup_component_by_name (
                            BUS_DEFAULT_IBUS, IBUS_SERVICE_PANEL);
            if (component) {
                bus_component_set_restart (component, restart);
            }
            if (component == NULL || !bus_component_start (component, g_verbose)) {
                g_printerr ("Can not execute default panel program\n");
                exit (-1);
            }
        } else if (g_strcmp0 (panel, "disable") != 0 && g_strcmp0 (panel, "") != 0) {
            if (!execute_cmdline (panel))
                exit (-1);
        }
    }

    /* execute ibus xim server */
    if (xim) {
        if (!execute_cmdline (LIBEXECDIR "/ibus-x11 --kill-daemon"))
            exit (-1);
    }

    bus_server_run ();
    return 0;
}
Exemple #22
0
int main(const int ac, const char* av[])
{
  poptContext optCon=0;
  gint rc;
  gint status = 0;
  const gchar* arg;
  struct error* err;

#ifdef __DEBUG  
  g_mem_set_vtable(glib_mem_profiler_table);
#endif

  err = e_new();
  /* check if we have enough privileges */
#ifndef __WIN32__
  unsetenv("LD_LIBRARY_PATH");
#else
  putenv("LD_LIBRARY_PATH");
  putenv("LD_LIBRARY_PATH=");
#endif  

  /* load blacklists from SPKG_CONFDIR */
  gchar** bl_symopts = load_blacklist(SPKG_CONFDIR "/symopts_blacklist");
  if (bl_symopts)
    cmd_opts.bl_symopts = bl_symopts;

  /* preset ROOT */
  cmd_opts.root = getenv("ROOT");

  /* initialize popt context */
  optCon = poptGetContext("spkg", ac, av, opts, 0);
  poptSetOtherOptionHelp(optCon, "<command> [options] [packages...]");

  /* parse options */
  while ((rc = poptGetNextOpt(optCon)) != -1)
  {
    if (rc == 1)
      verbose++;
    else if (rc == 2)
      quiet++;
    if (rc < -1)
    {
      fprintf(stderr, "ERROR: Invalid argument: %s (%s)\n",
        poptStrerror(rc),
        poptBadOption(optCon, POPT_BADOPTION_NOALIAS));
      goto err_1;
    }
  }

  /* these are help handlers */
  if (help)
  {
    printf(
      PACKAGE_STRING "\n"
      "\n"
      "Written by Ondrej Jirman, 2005-2006.\n"
      "\n"
      "This is free software. Not like a beer or like in a \"freedom\",\n"
      "but like in \"I don't care what you are going to do with it.\"\n"
      "\n"
    );
    poptPrintHelp(optCon, stdout, 0);
    printf(
      "\n"
      "Examples:\n"
      "  spkg -i <packages>     [--install]\n"
      "  spkg -u <packages>     [--upgrade]\n"
      "  spkg -vd <packages>    [--verbose --remove]\n"
      "  spkg -l kde*           [--list]\n"
      "  spkg -vnu <packages>   [--upgrade --verbose --dry-run]\n"
      "\n"
      "Official website: http://spkg.megous.com\n"
      "Bug reports can be sent to <*****@*****.**>.\n"
    );
    goto out;
  }
  if (usage)
  {
    printf("Usage: spkg [-i|-u|-d|-l] [--root=ROOT] [-n] [-s] [-q] [-v] [packages...]\n");
    goto out;
  }
  if (version)
  {
    printf("%s\n", PACKAGE_STRING);
    goto out;
  }

  /* check verbosity options */
  if (verbose && quiet)
  {
    fprintf(stderr, "ERROR: Verbose or quiet?\n");
    goto err_1;
  }
  cmd_opts.verbosity += verbose;
  cmd_opts.verbosity -= quiet;

  /* check command options */
  switch (command)
  {
    case CMD_INSTALL:
      if (!cmd_opts.dryrun && !is_root())
        goto err_noroot;
      if (poptPeekArg(optCon) == 0)
        goto err_nopackages;
    break;
    case CMD_UPGRADE:
      if (!cmd_opts.dryrun && !is_root())
        goto err_noroot;
      if (poptPeekArg(optCon) == 0)
        goto err_nopackages;
    break;
    case CMD_REMOVE:
      if (!cmd_opts.dryrun && !is_root())
        goto err_noroot;
      if (poptPeekArg(optCon) == 0)
        goto err_nopackages;
    break;
    case CMD_LIST:
    break;
    case 0:
      if (poptPeekArg(optCon) == 0)
      {
        printf("Usage: spkg [-i|-u|-d|-l] [--root=ROOT] [-n] [-s] [-q] [-v] [packages...]\n");
        goto out;
      }
      if (!cmd_opts.dryrun && !is_root())
        goto err_noroot;
      command = CMD_UPGRADE;
      install_new = TRUE;
    break;
    default:
      fprintf(stderr, "ERROR: Schizofrenic command usage.\n");
      goto err_1;
  }

  /* init signal trap */
  if (sig_trap(err))
    goto err_2;

  /* open db */
  gboolean readonly = cmd_opts.dryrun || !is_root();
  if (db_open(cmd_opts.root, readonly, err))
    goto err_2;

  switch (command)
  {
    case CMD_INSTALL:
    {
      while ((arg = poptGetArg(optCon)) != 0 && !sig_break)
      {
        if (cmd_install(arg, &cmd_opts, err))
        {
          if (e_errno(err) & CMD_EXIST)
          {
            gchar* pkgname = parse_pkgname(arg, 5);
            _inform("Skipping package %s (package with same base name is already installed)...", pkgname ? pkgname : arg);
            g_free(pkgname);
            e_clean(err);
          }
          else
          {
            e_print(err);
            e_clean(err);
            status = 2;
          }
        }
      }
    }
    break;
    case CMD_UPGRADE:
    {
      while ((arg = poptGetArg(optCon)) != 0 && !sig_break)
      {
        if (cmd_upgrade(arg, &cmd_opts, err))
        {
          if (install_new && (e_errno(err) & CMD_NOTEX))
          {
            e_clean(err);
            if (cmd_install(arg, &cmd_opts, err))
            {
              e_print(err);
              e_clean(err);
              status = 2;
            }
          }
          else if (e_errno(err) & CMD_NOTEX)
          {
            gchar* pkgname = parse_pkgname(arg, 5);
            _inform("Skipping package %s (package with same base name is NOT installed)...", pkgname ? pkgname : arg);
            g_free(pkgname);
            e_clean(err);
          }
          else if (e_errno(err) & CMD_EXIST)
          {
            gchar* pkgname = parse_pkgname(arg, 5);
            _inform("Skipping package %s (already uptodate)...", pkgname ? pkgname : arg);
            g_free(pkgname);
            e_clean(err);
          }
          else
          {
            e_print(err);
            e_clean(err);
            status = 2;
          }
        }
      }
    }
    break;
    case CMD_REMOVE:
    {
      while ((arg = poptGetArg(optCon)) != 0 && !sig_break)
      {
        if (cmd_remove(arg, &cmd_opts, err))
        {
          e_print(err);
          e_clean(err);
          status = 2;
        }
      }
    }
    break;
    case CMD_LIST:
    {
      GSList* arglist = NULL;
      while ((arg = poptGetArg(optCon)) != 0)
        arglist = g_slist_append(arglist, g_strdup(arg));
      if (cmd_list(arglist, &cmd_opts, err))
      {
        e_print(err);
        e_clean(err);
        status = 2;
      }
      g_slist_foreach(arglist, (GFunc)g_free, 0);
      g_slist_free(arglist);
    }
    break;
  }

  db_close();

 out:
  poptFreeContext(optCon);
  e_free(err);

#ifdef __DEBUG  
  g_mem_profile();
#endif

  /* 0 = all ok
   * 1 = command line error
   * 2 = package manager error
   */
  return status;
 err_1:
  status = 1;
  goto out;
 err_2:
  status = 2;
  e_print(err);
  goto out;
 err_nopackages:
  fprintf(stderr, "ERROR: No packages specified.\n");
  goto err_1;
 err_noroot:
  fprintf(stderr, "ERROR: You need root privileges to run this command. Try using --dry-run.\n");
  goto err_1;
}
Exemple #23
0
int
main(int argc, char **argv)
{
	GdkScreen *screen;
	GdkColormap *colormap;
	GtkWidget *window, *widget,*hbox = NULL, *scrollbar, *scrolled_window = NULL;
	VteTerminal *terminal;
	char *env_add[] = {
#ifdef VTE_DEBUG
		(char *) "FOO=BAR", (char *) "BOO=BIZ",
#endif
		NULL};
	const char *background = NULL;
	gboolean transparent = FALSE, audible = TRUE, blink = TRUE,
		 debug = FALSE, dingus = FALSE, dbuffer = TRUE,
		 console = FALSE, scroll = FALSE, keep = FALSE,
		 icon_title = FALSE, shell = TRUE, highlight_set = FALSE,
		 cursor_set = FALSE, reverse = FALSE, use_geometry_hints = TRUE,
		 antialias = TRUE, use_scrolled_window = FALSE,
                 show_object_notifications = FALSE;
        char *geometry = NULL;
	gint lines = 100;
	const char *message = "Launching interactive shell...\r\n";
	const char *font = NULL;
	const char *termcap = NULL;
	const char *command = NULL;
	const char *working_directory = NULL;
	const char *output_file = NULL;
        char *pty_flags_string = NULL;
        char *cursor_shape_string = NULL;
        char *scrollbar_policy_string = NULL;
	GdkColor fore, back, tint, highlight, cursor;
	const GOptionEntry options[]={
		{
			"antialias", 'A', G_OPTION_FLAG_REVERSE,
			G_OPTION_ARG_NONE, &antialias,
			"Disable the use of anti-aliasing", NULL
		},
		{
			"background", 'B', 0,
			G_OPTION_ARG_FILENAME, &background,
			"Specify a background image", NULL
		},
		{
			"console", 'C', 0,
			G_OPTION_ARG_NONE, &console,
			"Watch /dev/console", NULL
		},
		{
			"dingus", 'D', 0,
			G_OPTION_ARG_NONE, &dingus,
			"Highlight URLs inside the terminal", NULL
		},
		{
			"shell", 'S', G_OPTION_FLAG_REVERSE,
			G_OPTION_ARG_NONE, &shell,
			"Disable spawning a shell inside the terminal", NULL
		},
		{
			"transparent", 'T', 0,
			G_OPTION_ARG_NONE, &transparent,
			"Enable the use of a transparent background", NULL
		},
		{
			"double-buffer", '2', G_OPTION_FLAG_REVERSE,
			G_OPTION_ARG_NONE, &dbuffer,
			"Disable double-buffering", NULL
		},
		{
			"audible", 'a', G_OPTION_FLAG_REVERSE,
			G_OPTION_ARG_NONE, &audible,
			"Use visible, instead of audible, terminal bell",
			NULL
		},
		{
			"blink", 'b', G_OPTION_FLAG_REVERSE,
			G_OPTION_ARG_NONE, &blink,
			"Disable the blinking cursor", NULL
		},
		{
			"command", 'c', 0,
			G_OPTION_ARG_STRING, &command,
			"Execute a command in the terminal", NULL
		},
		{
			"debug", 'd', 0,
			G_OPTION_ARG_NONE, &debug,
			"Enable various debugging checks", NULL
		},
		{
			"font", 'f', 0,
			G_OPTION_ARG_STRING, &font,
			"Specify a font to use", NULL
		},
		{
			"geometry", 'g', 0,
			G_OPTION_ARG_STRING, &geometry,
			"Set the size (in characters) and position", "GEOMETRY"
		},
		{
			"highlight", 'h', 0,
			G_OPTION_ARG_NONE, &highlight_set,
			"Enable the cursor highlighting", NULL
		},
		{
			"icon-title", 'i', 0,
			G_OPTION_ARG_NONE, &icon_title,
			"Enable the setting of the icon title", NULL
		},
		{
			"keep", 'k', 0,
			G_OPTION_ARG_NONE, &keep,
			"Live on after the window closes", NULL
		},
		{
			"scrollback-lines", 'n', 0,
			G_OPTION_ARG_INT, &lines,
			"Specify the number of scrollback-lines", NULL
		},
		{
			"color-cursor", 'r', 0,
			G_OPTION_ARG_NONE, &cursor_set,
			"Enable a colored cursor", NULL
		},
		{
			"cursor-shape", 0, 0,
			G_OPTION_ARG_STRING, &cursor_shape_string,
			"Set cursor shape (block|underline|ibeam)", NULL
		},
		{
			"scroll-background", 's', 0,
			G_OPTION_ARG_NONE, &scroll,
			"Enable a scrolling background", NULL
		},
		{
			"termcap", 't', 0,
			G_OPTION_ARG_STRING, &termcap,
			"Specify the terminal emulation to use", NULL
		},
		{
			"working-directory", 'w', 0,
			G_OPTION_ARG_FILENAME, &working_directory,
			"Specify the initial working directory of the terminal",
			NULL
		},
		{
			"reverse", 0, 0,
			G_OPTION_ARG_NONE, &reverse,
			"Reverse foreground/background colors", NULL
		},
		{
			"no-geometry-hints", 'G', G_OPTION_FLAG_REVERSE,
			G_OPTION_ARG_NONE, &use_geometry_hints,
			"Allow the terminal to be resized to any dimension, not constrained to fit to an integer multiple of characters",
			NULL
		},
		{
			"scrolled-window", 'W', 0,
			G_OPTION_ARG_NONE, &use_scrolled_window,
			"Use a GtkScrolledWindow as terminal container",
			NULL
		},
		{
			"scrollbar-policy", 'P', 0,
			G_OPTION_ARG_STRING, &scrollbar_policy_string,
			"Set the policy for the vertical scroolbar in the scrolled window (always|auto|never; default:always)",
			NULL
		},
		{
			"object-notifications", 'N', 0,
			G_OPTION_ARG_NONE, &show_object_notifications,
			"Print VteTerminal object notifications",
			NULL
		},
		{
			"output-file", 0, 0,
			G_OPTION_ARG_STRING, &output_file,
			"Save terminal contents to file at exit", NULL
		},
		{
			"pty-flags", 0, 0,
			G_OPTION_ARG_STRING, &pty_flags_string,
			"PTY flags set from default|no-utmp|no-wtmp|no-lastlog|no-helper|no-fallback", NULL
		},
		{ NULL }
	};
	GOptionContext *context;
	GError *error = NULL;
        VteTerminalCursorShape cursor_shape = VTE_CURSOR_SHAPE_BLOCK;
        GtkPolicyType scrollbar_policy = GTK_POLICY_ALWAYS;
        VtePtyFlags pty_flags = VTE_PTY_DEFAULT;

	/* Have to do this early. */
	if (getenv("VTE_PROFILE_MEMORY")) {
		if (atol(getenv("VTE_PROFILE_MEMORY")) != 0) {
			g_mem_set_vtable(glib_mem_profiler_table);
		}
	}

	context = g_option_context_new (" - test VTE terminal emulation");
	g_option_context_add_main_entries (context, options, NULL);
	g_option_context_add_group (context, gtk_get_option_group (TRUE));
	g_option_context_parse (context, &argc, &argv, &error);
	g_option_context_free (context);
	if (error != NULL) {
		g_printerr ("Failed to parse command line arguments: %s\n",
				error->message);
		g_error_free (error);
		return 1;
	}

        if (cursor_shape_string) {
                cursor_shape = parse_enum(VTE_TYPE_TERMINAL_CURSOR_SHAPE, cursor_shape_string);
                g_free(cursor_shape_string);
        }
        if (scrollbar_policy_string) {
                scrollbar_policy = parse_enum(GTK_TYPE_POLICY_TYPE, scrollbar_policy_string);
                g_free(scrollbar_policy_string);
        }
        if (pty_flags_string) {
                pty_flags |= parse_flags(VTE_TYPE_PTY_FLAGS, pty_flags_string);
                g_free(pty_flags_string);
        }

	if (!reverse) {
		back.red = back.green = back.blue = 0xffff;
		fore.red = fore.green = fore.blue = 0x0000;
	} else {
		back.red = back.green = back.blue = 0x0000;
		fore.red = fore.green = fore.blue = 0xffff;
	}

	highlight.red = highlight.green = highlight.blue = 0xc000;
	cursor.red = 0xffff;
	cursor.green = cursor.blue = 0x8000;
	tint.red = tint.green = tint.blue = 0;
	tint = back;

	gdk_window_set_debug_updates(debug);

	/* Create a window to hold the scrolling shell, and hook its
	 * delete event to the quit function.. */
	window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
	gtk_container_set_resize_mode(GTK_CONTAINER(window),
				      GTK_RESIZE_IMMEDIATE);

	/* Set ARGB colormap */
	screen = gtk_widget_get_screen (window);
	colormap = gdk_screen_get_rgba_colormap (screen);
	if (colormap)
	    gtk_widget_set_colormap(window, colormap);

        if (use_scrolled_window) {
                scrolled_window = gtk_scrolled_window_new (NULL, NULL);
                gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolled_window),
                                               GTK_POLICY_NEVER, scrollbar_policy);
                gtk_container_add(GTK_CONTAINER(window), scrolled_window);
        } else {
                /* Create a box to hold everything. */
                hbox = gtk_hbox_new(0, FALSE);
                gtk_container_add(GTK_CONTAINER(window), hbox);
        }

	/* Create the terminal widget and add it to the scrolling shell. */
	widget = vte_terminal_new();
	terminal = VTE_TERMINAL (widget);
	if (!dbuffer) {
		gtk_widget_set_double_buffered(widget, dbuffer);
	}
        g_signal_connect(terminal, "child-exited", G_CALLBACK(child_exit_cb), NULL);
        if (show_object_notifications)
                g_signal_connect(terminal, "notify", G_CALLBACK(terminal_notify_cb), NULL);
        if (use_scrolled_window) {
                gtk_container_add(GTK_CONTAINER(scrolled_window), GTK_WIDGET(terminal));
        } else {
                gtk_box_pack_start(GTK_BOX(hbox), widget, TRUE, TRUE, 0);
        }

	/* Connect to the "char_size_changed" signal to set geometry hints
	 * whenever the font used by the terminal is changed. */
	if (use_geometry_hints) {
		char_size_changed(widget, 0, 0, window);
		g_signal_connect(widget, "char-size-changed",
				 G_CALLBACK(char_size_changed), window);
		g_signal_connect(widget, "realize",
				 G_CALLBACK(char_size_realized), window);
	}

	/* Connect to the "window_title_changed" signal to set the main
	 * window's title. */
	g_signal_connect(widget, "window-title-changed",
			 G_CALLBACK(window_title_changed), window);
	if (icon_title) {
		g_signal_connect(widget, "icon-title-changed",
				 G_CALLBACK(icon_title_changed), window);
	}

	/* Connect to the "status-line-changed" signal. */
	g_signal_connect(widget, "status-line-changed",
			 G_CALLBACK(status_line_changed), widget);

	/* Connect to the "button-press" event. */
	g_signal_connect(widget, "button-press-event",
			 G_CALLBACK(button_pressed), widget);

	/* Connect to application request signals. */
	g_signal_connect(widget, "iconify-window",
			 G_CALLBACK(iconify_window), window);
	g_signal_connect(widget, "deiconify-window",
			 G_CALLBACK(deiconify_window), window);
	g_signal_connect(widget, "raise-window",
			 G_CALLBACK(raise_window), window);
	g_signal_connect(widget, "lower-window",
			 G_CALLBACK(lower_window), window);
	g_signal_connect(widget, "maximize-window",
			 G_CALLBACK(maximize_window), window);
	g_signal_connect(widget, "restore-window",
			 G_CALLBACK(restore_window), window);
	g_signal_connect(widget, "refresh-window",
			 G_CALLBACK(refresh_window), window);
	g_signal_connect(widget, "resize-window",
			 G_CALLBACK(resize_window), window);
	g_signal_connect(widget, "move-window",
			 G_CALLBACK(move_window), window);

	/* Connect to font tweakage. */
	g_signal_connect(widget, "increase-font-size",
			 G_CALLBACK(increase_font_size), window);
	g_signal_connect(widget, "decrease-font-size",
			 G_CALLBACK(decrease_font_size), window);

        if (!use_scrolled_window) {
                /* Create the scrollbar for the widget. */
                scrollbar = gtk_vscrollbar_new(terminal->adjustment);
                gtk_box_pack_start(GTK_BOX(hbox), scrollbar, FALSE, FALSE, 0);
        }

	/* Set some defaults. */
	vte_terminal_set_audible_bell(terminal, audible);
	vte_terminal_set_visible_bell(terminal, !audible);
	vte_terminal_set_cursor_blink_mode(terminal, blink ? VTE_CURSOR_BLINK_SYSTEM : VTE_CURSOR_BLINK_OFF);
	vte_terminal_set_scroll_background(terminal, scroll);
	vte_terminal_set_scroll_on_output(terminal, FALSE);
	vte_terminal_set_scroll_on_keystroke(terminal, TRUE);
	vte_terminal_set_scrollback_lines(terminal, lines);
	vte_terminal_set_mouse_autohide(terminal, TRUE);
	if (background != NULL) {
		vte_terminal_set_background_image_file(terminal,
						       background);
	}
	if (transparent) {
		vte_terminal_set_background_transparent(terminal,
							TRUE);
	}
	vte_terminal_set_background_tint_color(terminal, &tint);
	vte_terminal_set_colors(terminal, &fore, &back, NULL, 0);
	vte_terminal_set_opacity(terminal, 0xdddd);
	if (highlight_set) {
		vte_terminal_set_color_highlight(terminal,
						 &highlight);
	}
	if (cursor_set) {
		vte_terminal_set_color_cursor(terminal, &cursor);
	}
	if (termcap != NULL) {
		vte_terminal_set_emulation(terminal, termcap);
	}
        vte_terminal_set_cursor_shape(terminal, cursor_shape);

	/* Set the default font. */
	vte_terminal_set_font_from_string_full(terminal, font,
					       antialias ? VTE_ANTI_ALIAS_USE_DEFAULT : VTE_ANTI_ALIAS_FORCE_DISABLE);

	/* Match "abcdefg". */
	if (dingus) {
		int id;
		GRegex *regex;
		regex = g_regex_new (DINGUS1, 0, 0, NULL);
		id = vte_terminal_match_add_gregex(terminal, regex, 0);
		g_regex_unref (regex);
		vte_terminal_match_set_cursor_type(terminal,
						   id, GDK_GUMBY);
		regex = g_regex_new (DINGUS2, 0, 0, NULL);
		id = vte_terminal_match_add_gregex(terminal, regex, 0);
		g_regex_unref (regex);
		vte_terminal_match_set_cursor_type(terminal,
						   id, GDK_HAND1);
	}

	if (console) {
		/* Open a "console" connection. */
		int consolefd = -1, yes = 1, watch;
		GIOChannel *channel;
		consolefd = open("/dev/console", O_RDONLY | O_NOCTTY);
		if (consolefd != -1) {
			/* Assume failure. */
			console = FALSE;
#ifdef TIOCCONS
			if (ioctl(consolefd, TIOCCONS, &yes) != -1) {
				/* Set up a listener. */
				channel = g_io_channel_unix_new(consolefd);
				watch = g_io_add_watch(channel,
						       G_IO_IN,
						       read_and_feed,
						       widget);
				g_signal_connect(widget,
						 "eof",
						 G_CALLBACK(disconnect_watch),
						 GINT_TO_POINTER(watch));
				g_signal_connect(widget,
						 "child-exited",
						 G_CALLBACK(disconnect_watch),
						 GINT_TO_POINTER(watch));
				g_signal_connect(widget,
						 "realize",
						 G_CALLBACK(take_xconsole_ownership),
						 NULL);
#ifdef VTE_DEBUG
				vte_terminal_feed(terminal,
						  "Console log for ...\r\n",
						  -1);
#endif
				/* Record success. */
				console = TRUE;
			}
#endif
		} else {
			/* Bail back to normal mode. */
			g_warning(_("Could not open console.\n"));
			close(consolefd);
			console = FALSE;
		}
	}

	if (!console) {
		if (shell) {
                        GError *err = NULL;
                        char **command_argv = NULL;
                        int command_argc;
                        GPid pid = -1;

			_VTE_DEBUG_IF(VTE_DEBUG_MISC)
				vte_terminal_feed(terminal, message, -1);

                        if (command == NULL)
                                command = "/bin/sh"; // FIXMEchpe

                        if (command != NULL) {
                                if (!g_shell_parse_argv(command, &command_argc, &command_argv, &err) ||
                                    !vte_terminal_fork_command_full(terminal,
                                                                    pty_flags,
                                                                    NULL,
                                                                    command_argv,
                                                                    env_add,
                                                                    G_SPAWN_SEARCH_PATH,
                                                                    NULL, NULL,
                                                                    &pid,
                                                                    &err)) {
                                        g_warning("Failed to fork: %s\n", err->message);
                                        g_error_free(err);
                                } else {
                                        g_print("Fork succeeded, PID %d\n", pid);
                                }
                        }
                        g_strfreev(command_argv);
	#ifdef VTE_DEBUG
			if (command == NULL) {
				vte_terminal_feed_child(terminal,
							"pwd\n", -1);
			}
	#endif
		} else {
			long i;
			i = vte_terminal_forkpty(terminal,
						 env_add, working_directory,
						 TRUE, TRUE, TRUE);
			switch (i) {
			case -1:
				/* abnormal */
				g_warning("Error in vte_terminal_forkpty(): %s",
					  strerror(errno));
				break;
			case 0:
				/* child */
				for (i = 0; ; i++) {
					switch (i % 3) {
					case 0:
					case 1:
						g_print("%ld\n", i);
						break;
					case 2:
						g_printerr("%ld\n", i);
						break;
					}
					sleep(1);
				}
				_exit(0);
				break;
			default:
				g_print("Child PID is %ld (mine is %ld).\n",
					(long) i, (long) getpid());
				/* normal */
				break;
			}
		}
	}

	g_object_set_data (G_OBJECT (widget), "output_file", (gpointer) output_file);

	/* Go for it! */
	g_signal_connect(widget, "child-exited", G_CALLBACK(child_exited), window);
	g_signal_connect(window, "delete-event", G_CALLBACK(delete_event), widget);

	add_weak_pointer(G_OBJECT(widget), &widget);
	add_weak_pointer(G_OBJECT(window), &window);

        gtk_widget_realize(widget);
        if (geometry) {
                if (!gtk_window_parse_geometry (GTK_WINDOW(window), geometry)) {
                        g_warning (_("Could not parse the geometry spec passed to --geometry"));
                }
        }

	gtk_widget_show_all(window);

	gtk_main();

	g_assert(widget == NULL);
	g_assert(window == NULL);

	if (keep) {
		while (TRUE) {
			sleep(60);
		}
	}

	return 0;
}
Exemple #24
0
/**
 * Configure NuAuth:
 *   - Init. glib threads: g_thread_init() ;
 *   - Read command line options: parse_options() ;
 *   - Read NuAuth configuration file: init_nuauthconf() ;
 *   - Build configuration options: build_prenuauthconf() ;
 *   - Init SSL library: nussl_init() ;
 *   - Create credentials: create_x509_credentials() ;
 *   - Daemonize the process if asked: daemonize().
 */
void configure_app(int argc, char **argv)
{
	command_line_params_t params;
	int ret;
	struct rlimit r_limit;
	struct nuauth_params initconf;
	struct nuauth_params *conf;

	/* Avoid creation of core file which may contains username and password */
	if (getrlimit(RLIMIT_CORE, &r_limit) == 0) {
#ifdef DEBUG_ENABLE
		r_limit.rlim_cur = RLIM_INFINITY;
#else
		r_limit.rlim_cur = 0;
#endif
		setrlimit(RLIMIT_CORE, &r_limit);
	}

	if (getrlimit(RLIMIT_NOFILE, &r_limit) == 0) {
		r_limit.rlim_cur = 8096;
		r_limit.rlim_max = 8096;
		setrlimit(RLIMIT_NOFILE, &r_limit);
	}

#ifndef DEBUG_ENABLE
	/* Move to root directory to not block current working directory */
	(void) chdir("/");
#endif

#ifdef DEBUG_MEMORY
	g_mem_set_vtable(glib_mem_profiler_table);
#endif

	/* Initialize glib thread system */
	g_thread_init(NULL);
	g_thread_pool_set_max_unused_threads(5);

	/* init nuauthdatas */
	nuauthdatas = g_new0(struct nuauth_datas, 1);
	nuauthdatas->is_starting = TRUE;
	nuauthdatas->reload_cond = g_cond_new();
	nuauthdatas->reload_cond_mutex = g_mutex_new();
	nuauthdatas->program_fullpath = g_strdup(argv[0]);


	/* set default parameters */
	params.debug_level = 0;
	params.daemonize = 0;
	params.client_srv = NULL;
	params.nufw_srv = NULL;
	params.userpckt_port = NULL;
	params.authreq_port = NULL;
	params.configfile = NULL;

	nuauthconf = &initconf;
	/* check if configuration file is not given on command line */
	parse_options(argc, argv, &params);

	if (params.debug_level) {
		nuauthconf->debug_level = params.debug_level;
	} else {
		nuauthconf->debug_level = DEFAULT_DEBUG_LEVEL;
	}
	nuauthconf->debug_areas = DEFAULT_DEBUG_AREAS;

	if (params.configfile == NULL) {
		nuauthconf->configfile = g_strdup(DEFAULT_CONF_FILE);
	} else {
		nuauthconf->configfile = g_strdup(params.configfile);
	}

	ret = nuauth_parse_configuration(nuauthconf->configfile);
	if (ret < 0) {
		log_message(FATAL, DEBUG_AREA_MAIN,
			    "Cannot load configuration (file '%s')",
			    nuauthconf->configfile);
		exit(EXIT_FAILURE);
	}

	/* load configuration */
	if (!init_nuauthconf(&conf)) {
		log_message(FATAL, DEBUG_AREA_MAIN,
				"Unable to load configuration");
		exit(EXIT_FAILURE);
	}

	conf->configfile = nuauthconf->configfile;
	nuauthconf = conf;
	/* build configuration by overwritting config file option by
	 * command line one */
	nuauthconf_from_cmdline(&params);

	build_prenuauthconf(nuauthconf, NULL, 0);

	ret = nussl_init();
	if ( ret != NUSSL_OK ) {
		log_message(FATAL, DEBUG_AREA_MAIN,
			"FATAL ERROR: NuSSL global initialisation failed.");
		exit(EXIT_FAILURE);

	}

	if (nuauthconf->uses_utf8) {
		setlocale(LC_ALL, "");
	}

	/* debug cannot be above 10 */
	if (nuauthconf->debug_level > MAX_DEBUG_LEVEL)
		nuauthconf->debug_level = MAX_DEBUG_LEVEL;
	if (nuauthconf->debug_level < MIN_DEBUG_LEVEL)
		nuauthconf->debug_level = MIN_DEBUG_LEVEL;
	log_message(INFO, DEBUG_AREA_MAIN,
			"Debug_level is %i", nuauthconf->debug_level);

#if 0
	/* init credential */
	if (! create_x509_credentials()) {
		log_area_printf(DEBUG_AREA_MAIN, DEBUG_LEVEL_FATAL,
				"Certificate initialization failed");
		exit(EXIT_FAILURE);
	}
#endif
	/* free command line structure */
	g_free(params.client_srv);
	g_free(params.nufw_srv);
	g_free(params.userpckt_port);
	g_free(params.authreq_port);
	g_free(params.configfile);

	debug_areas = DEFAULT_DEBUG_AREAS;
	debug_level = nuauthconf->debug_level;

	/* init gcrypt and gnutls */
	if (params.daemonize == 1) {
		daemonize();
		/* default: use only syslog */
		set_glib_loghandlers(0, nuauthconf->log_to_syslog);

	} else {
		int use_stdout = (quiet_mode == 0);
		/* default: use both stdout and syslog */
		set_glib_loghandlers(use_stdout, nuauthconf->log_to_syslog);
		log_message(FATAL, DEBUG_AREA_MAIN,
				"[+] NuAuth " NUAUTH_FULL_VERSION " with config %s",
				nuauthconf->configfile);
		log_message(FATAL, DEBUG_AREA_MAIN,
		"Nuauth started in foreground (without -D option), "
		"logging on stderr, stdout and syslog");
	}

	/* declare default capabilities */
	register_client_capa("HELLO", &(nuauthdatas->hello_capa));
	register_client_capa("TCP", &(nuauthdatas->tcp_capa));
	register_client_capa("UDP", &(nuauthdatas->udp_capa));
}
Exemple #25
0
void
gum_init_embedded (void)
{
  ffi_mem_callbacks ffi_callbacks = {
    (void * (*) (size_t)) gum_malloc,
    (void * (*) (size_t, size_t)) gum_calloc,
    gum_free,
    gum_on_ffi_allocate,
    gum_on_ffi_deallocate
  };
  GThreadCallbacks thread_callbacks = {
    gum_on_thread_init,
    gum_on_thread_realize,
    gum_on_thread_dispose,
    gum_on_thread_finalize
  };
  GFDCallbacks fd_callbacks = {
    gum_on_fd_opened,
    gum_on_fd_closed
  };
#if !DEBUG_HEAP_LEAKS && !defined (HAVE_ASAN)
  GMemVTable mem_vtable = {
    gum_malloc,
    gum_realloc,
    gum_free,
    gum_calloc,
    gum_malloc,
    gum_realloc
  };
#endif
#if defined (G_OS_WIN32) && DEBUG_HEAP_LEAKS
  int tmp_flag;
#endif

  if (gum_initialized)
    return;
  gum_initialized = TRUE;

#if defined (G_OS_WIN32) && DEBUG_HEAP_LEAKS
  /*_CrtSetBreakAlloc (1337);*/

  _CrtSetReportMode (_CRT_ERROR, _CRTDBG_MODE_FILE);
  _CrtSetReportFile (_CRT_ERROR, _CRTDBG_FILE_STDERR);

  tmp_flag = _CrtSetDbgFlag (_CRTDBG_REPORT_FLAG);

  tmp_flag |= _CRTDBG_ALLOC_MEM_DF;
  tmp_flag |= _CRTDBG_LEAK_CHECK_DF;
  tmp_flag &= ~_CRTDBG_CHECK_CRT_DF;

  _CrtSetDbgFlag (tmp_flag);
#endif

  gum_memory_init ();
  ffi_set_mem_callbacks (&ffi_callbacks);
  g_thread_set_callbacks (&thread_callbacks);
  g_platform_audit_set_fd_callbacks (&fd_callbacks);
#if !DEBUG_HEAP_LEAKS && !defined (HAVE_ASAN)
  if (RUNNING_ON_VALGRIND)
  {
    g_setenv ("G_SLICE", "always-malloc", TRUE);
  }
  else
  {
    g_mem_set_vtable (&mem_vtable);
  }
#else
  g_setenv ("G_SLICE", "always-malloc", TRUE);
#endif
  glib_init ();
  g_assertion_set_handler (gum_on_assert_failure, NULL);
  g_log_set_default_handler (gum_on_log_message, NULL);
  gum_do_init ();

  g_set_prgname ("frida");

#if defined (HAVE_LINUX) && defined (HAVE_GLIBC)
  gum_libdl_prevent_unload ();
#endif

  gum_cached_interceptor = gum_interceptor_obtain ();
}
/**
 * CGstMediaManager::Init().
 *
 * @param   data    user-defined data. Pointer to this.
 * @return  Java long reference to the media.
 */
uint32_t CGstMediaManager::Init()
{
    GError*     pError = NULL;
    uint32_t    uRetCode = ERROR_NONE;

#if ENABLE_LOWLEVELPERF && TARGET_OS_MAC
    g_mem_set_vtable (glib_mem_profiler_table);
#endif

#if ENABLE_VISUAL_STUDIO_MEMORY_LEAKS_DETECTION && TARGET_OS_WIN32
    _CrtSetDbgFlag ( 0 );
#endif // ENABLE_VISUAL_STUDIO_MEMORY_LEAKS_DETECTION

    //***** Try to initialize the GStreamer system
    if (!g_thread_supported())
        g_thread_init (NULL);

    LOWLEVELPERF_EXECTIMESTART("gst_init_check()");
    // disable installing SIGSEGV signal handling as it interferes with Java's signal handling
    gst_segtrap_set_enabled(false);
    if (!gst_init_check(NULL, NULL, NULL))
    {
        LOGGER_LOGMSG(LOGGER_DEBUG, "Could not init GStreamer!\n");
        return ERROR_MANAGER_ENGINEINIT_FAIL;
    }
    LOWLEVELPERF_EXECTIMESTOP("gst_init_check()");

#if ENABLE_VISUAL_STUDIO_MEMORY_LEAKS_DETECTION && TARGET_OS_WIN32
    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
#endif // ENABLE_VISUAL_STUDIO_MEMORY_LEAKS_DETECTION

    //***** Create mutex and condition variable
    m_pRunloopCond = g_cond_new();
    m_pRunloopMutex = g_mutex_new();

#if ENABLE_VISUAL_STUDIO_MEMORY_LEAKS_DETECTION && TARGET_OS_WIN32
    _CrtSetDbgFlag(0);
#endif // ENABLE_VISUAL_STUDIO_MEMORY_LEAKS_DETECTION

    //***** Create the primary run loop
    m_pMainLoopThread = g_thread_create((GThreadFunc)run_loop, this, FALSE, &pError);
    if (m_pMainLoopThread == NULL)
    {
        LOGGER_LOGMSG(LOGGER_DEBUG, "Could not create main GThread!!\n");
        LOGGER_LOGMSG(LOGGER_DEBUG, pError->message);
        return ERROR_MANAGER_RUNLOOP_FAIL;
    }

#if ENABLE_VISUAL_STUDIO_MEMORY_LEAKS_DETECTION && TARGET_OS_WIN32
    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
#endif // ENABLE_VISUAL_STUDIO_MEMORY_LEAKS_DETECTION

    //***** Wait till the run loop has fully initialized.  Bad things happen if we do not do this, including crashers.
    g_mutex_lock(m_pRunloopMutex);
    while (NULL == m_pMainLoop)
        g_cond_wait(m_pRunloopCond, m_pRunloopMutex);
    g_mutex_unlock(m_pRunloopMutex);

    if (m_bMainLoopCreateFailed)
        uRetCode = ERROR_GSTREAMER_MAIN_LOOP_CREATE;

    // Free no longer needed GCond.
    if (NULL != m_pRunloopCond)
    {
        g_cond_free(m_pRunloopCond);
        m_pRunloopCond = NULL;
    }

    // Free no longer needed GMutex.
    if (NULL != m_pRunloopMutex)
    {
        g_mutex_free(m_pRunloopMutex);
        m_pRunloopMutex = NULL;
    }

    // Set the default Glib log handler.
    g_log_set_default_handler (GlibLogFunc, this);

    return uRetCode;
}
Exemple #27
0
int
main(int argc, char **argv)
{
    GListPtr lpc = NULL;
    gboolean process = TRUE;
    gboolean all_good = TRUE;
    enum transition_status graph_rc = -1;
    crm_graph_t *transition = NULL;
    ha_time_t *a_date = NULL;
    cib_t *cib_conn = NULL;

    xmlNode *cib_object = NULL;
    int argerr = 0;
    int flag;

    char *msg_buffer = NULL;
    gboolean optional = FALSE;
    pe_working_set_t data_set;

    const char *source = NULL;
    const char *xml_file = NULL;
    const char *dot_file = NULL;
    const char *graph_file = NULL;
    const char *input_file = NULL;
    const char *input_xml = NULL;

    /* disable glib's fancy allocators that can't be free'd */
    GMemVTable vtable;

    vtable.malloc = malloc;
    vtable.realloc = realloc;
    vtable.free = free;
    vtable.calloc = calloc;
    vtable.try_malloc = malloc;
    vtable.try_realloc = realloc;

    g_mem_set_vtable(&vtable);

    crm_log_init_quiet(NULL, LOG_CRIT, FALSE, FALSE, argc, argv);
    crm_set_options(NULL, "[-?Vv] -[Xxp] {other options}", long_options,
                    "Calculate the cluster's response to the supplied cluster state\n"
                    "\nSuperceeded by crm_simulate and likely to be removed in a future release\n\n");

    while (1) {
        int option_index = 0;

        flag = crm_get_option(argc, argv, &option_index);
        if (flag == -1)
            break;

        switch (flag) {
            case 'S':
                do_simulation = TRUE;
                break;
            case 'a':
                all_actions = TRUE;
                break;
            case 'w':
                inhibit_exit = TRUE;
                break;
            case 'X':
                /*use_stdin = TRUE;*/
                input_xml = optarg;
                break;
            case 's':
                show_scores = TRUE;
                break;
            case 'U':
                show_utilization = TRUE;
                break;
            case 'x':
                xml_file = optarg;
                break;
            case 'd':
                use_date = optarg;
                break;
            case 'D':
                dot_file = optarg;
                break;
            case 'G':
                graph_file = optarg;
                break;
            case 'I':
                input_file = optarg;
                break;
            case 'V':
                crm_bump_log_level();
                break;
            case 'L':
                USE_LIVE_CIB = TRUE;
                break;
            case '$':
            case '?':
                crm_help(flag, 0);
                break;
            default:
                fprintf(stderr, "Option -%c is not yet supported\n", flag);
                ++argerr;
                break;
        }
    }

    if (optind < argc) {
        printf("non-option ARGV-elements: ");
        while (optind < argc) {
            printf("%s ", argv[optind++]);
        }
        printf("\n");
    }

    if (optind > argc) {
        ++argerr;
    }

    if (argerr) {
        crm_err("%d errors in option parsing", argerr);
        crm_help('?', 1);
    }

    update_all_trace_data();    /* again, so we see which trace points got updated */

    if (USE_LIVE_CIB) {
        int rc = cib_ok;

        source = "live cib";
        cib_conn = cib_new();
        rc = cib_conn->cmds->signon(cib_conn, "ptest", cib_command);

        if (rc == cib_ok) {
            crm_info("Reading XML from: live cluster");
            cib_object = get_cib_copy(cib_conn);

        } else {
            fprintf(stderr, "Live CIB query failed: %s\n", cib_error2string(rc));
            return 3;
        }
        if (cib_object == NULL) {
            fprintf(stderr, "Live CIB query failed: empty result\n");
            return 3;
        }

    } else if (xml_file != NULL) {
        source = xml_file;
        cib_object = filename2xml(xml_file);

    } else if (use_stdin) {
        source = "stdin";
        cib_object = filename2xml(NULL);
    } else if (input_xml) {
        source = "input string";
        cib_object = string2xml(input_xml);
    }

    if (cib_object == NULL && source) {
        fprintf(stderr, "Could not parse configuration input from: %s\n", source);
        return 4;

    } else if (cib_object == NULL) {
        fprintf(stderr, "No configuration specified\n");
        crm_help('?', 1);
    }

    if (get_object_root(XML_CIB_TAG_STATUS, cib_object) == NULL) {
        create_xml_node(cib_object, XML_CIB_TAG_STATUS);
    }

    if (cli_config_update(&cib_object, NULL, FALSE) == FALSE) {
        free_xml(cib_object);
        return cib_STALE;
    }

    if (validate_xml(cib_object, NULL, FALSE) != TRUE) {
        free_xml(cib_object);
        return cib_dtd_validation;
    }

    if (input_file != NULL) {
        FILE *input_strm = fopen(input_file, "w");

        if (input_strm == NULL) {
            crm_perror(LOG_ERR, "Could not open %s for writing", input_file);
        } else {
            msg_buffer = dump_xml_formatted(cib_object);
            if (fprintf(input_strm, "%s\n", msg_buffer) < 0) {
                crm_perror(LOG_ERR, "Write to %s failed", input_file);
            }
            fflush(input_strm);
            fclose(input_strm);
            crm_free(msg_buffer);
        }
    }

    if (use_date != NULL) {
        a_date = parse_date(&use_date);
        log_date(LOG_WARNING, "Set fake 'now' to", a_date, ha_log_date | ha_log_time);
        log_date(LOG_WARNING, "Set fake 'now' to (localtime)",
                 a_date, ha_log_date | ha_log_time | ha_log_local);
    }

    set_working_set_defaults(&data_set);
    if (process) {
        if (show_scores && show_utilization) {
            fprintf(stdout, "Allocation scores and utilization information:\n");
        } else if (show_scores) {
            fprintf(stdout, "Allocation scores:\n");
        } else if (show_utilization) {
            fprintf(stdout, "Utilization information:\n");
        }
        do_calculations(&data_set, cib_object, a_date);
    }

    msg_buffer = dump_xml_formatted(data_set.graph);
    if (safe_str_eq(graph_file, "-")) {
        fprintf(stdout, "%s\n", msg_buffer);
        fflush(stdout);
    } else if (graph_file != NULL) {
        FILE *graph_strm = fopen(graph_file, "w");

        if (graph_strm == NULL) {
            crm_perror(LOG_ERR, "Could not open %s for writing", graph_file);
        } else {
            if (fprintf(graph_strm, "%s\n\n", msg_buffer) < 0) {
                crm_perror(LOG_ERR, "Write to %s failed", graph_file);
            }
            fflush(graph_strm);
            fclose(graph_strm);
        }
    }
    crm_free(msg_buffer);

    if (dot_file != NULL) {
        dot_strm = fopen(dot_file, "w");
        if (dot_strm == NULL) {
            crm_perror(LOG_ERR, "Could not open %s for writing", dot_file);
        }
    }

    if (dot_strm == NULL) {
        goto simulate;
    }

    init_dotfile();
    for (lpc = data_set.actions; lpc != NULL; lpc = lpc->next) {
        action_t *action = (action_t *) lpc->data;
        const char *style = "filled";
        const char *font = "black";
        const char *color = "black";
        const char *fill = NULL;
        char *action_name = create_action_name(action);

        crm_trace("Action %d: %p", action->id, action);

        if (is_set(action->flags, pe_action_pseudo)) {
            font = "orange";
        }

        style = "dashed";
        if (is_set(action->flags, pe_action_dumped)) {
            style = "bold";
            color = "green";

        } else if (action->rsc != NULL && is_not_set(action->rsc->flags, pe_rsc_managed)) {
            color = "purple";
            if (all_actions == FALSE) {
                goto dont_write;
            }

        } else if (is_set(action->flags, pe_action_optional)) {
            color = "blue";
            if (all_actions == FALSE) {
                goto dont_write;
            }

        } else {
            color = "red";
            CRM_CHECK(is_set(action->flags, pe_action_runnable) == FALSE,;
                );
        }

        set_bit_inplace(action->flags, pe_action_dumped);
        dot_write("\"%s\" [ style=%s color=\"%s\" fontcolor=\"%s\"  %s%s]",
                  action_name, style, color, font, fill ? "fillcolor=" : "", fill ? fill : "");
  dont_write:
        crm_free(action_name);
    }
Exemple #28
0
int main(int argc, char **argv){
	GMainLoop *main_loop;
	GSocketService *service;
	GInetAddress *iaddr;
	GSocketAddress *saddr;
	AppData *app_data;
	GError *error = NULL;

	// Init
	g_set_prgname(argv[0]);
	g_mem_set_vtable(glib_mem_profiler_table);
	g_type_init();

	// Start the daemon
	start_daemon(g_get_prgname(), LOG_LOCAL0);
	syslog(LOG_NOTICE, "-----------------------------------\n");
	syslog(LOG_NOTICE, "Daemon has been started\n");


//	atexit(cleanup);

	// Initialize App Data structire
	app_data = g_slice_new0(AppData);
	app_data->queue = g_queue_new();
	app_data->hosts = NULL;
	app_data->running_backups = NULL;

	// For global access to app_data
	app_data_aux_ptr = app_data;

	// Read configuration
	if (!read_config(app_data)){
		syslog(LOG_ERR, "Failed to read config file \"%s\"", CONFIG_FILE);
		exit(-1);
	}

	// If no hosts configured in config file, try reading from MySQL

	if (g_list_length(app_data->hosts) == 0){
		syslog(LOG_NOTICE, "No hosts configured in /etc/busy/busy.conf, now reading hosts from MySQL");
		app_data->hosts = db_read_hosts(app_data->mysql);
	}

	if (g_list_length(app_data->hosts) == 0){
		syslog(LOG_ERR, "Absolutely no hosts configured! Please configure at least one host either in %s or use the Web frontend", CONFIG_FILE);
		//~ syslog(LOG_ERR, "I won't waste any more cpu time now and exit");
		//~ exit(0);
	}
	else {
		GList *p;
		for (p = app_data->hosts; p != NULL; p = p->next){
			Host *host = p->data;
			host_dump(host);
			syslog(LOG_NOTICE, "%s %f", host_get_name(host), host_get_max_age(host));
		}
	}

	// Setup listener for incoming TCP (localhost port 4000)
	service = g_socket_service_new();
	iaddr = g_inet_address_new_from_string("127.0.0.1");
	saddr = g_inet_socket_address_new(iaddr, 4000);
	g_socket_listener_add_address(G_SOCKET_LISTENER(service), saddr, G_SOCKET_TYPE_STREAM, G_SOCKET_PROTOCOL_TCP, NULL, NULL, &error);
	g_object_unref(iaddr);
	g_object_unref(saddr);
	g_socket_service_start(service);
	g_signal_connect(service, "incoming", (GCallback)on_incoming, app_data);

	// Call wakeup and archive function once
	wakeup(app_data);
	do_archive(app_data);

	// Check preiodically for backups, queue and archives,
	g_timeout_add_seconds(WAKEUP_INTERVAL, (GSourceFunc)wakeup, app_data);
	g_timeout_add_seconds(10, (GSourceFunc)do_backup, app_data);
	g_timeout_add_seconds(6 * 3600, (GSourceFunc)do_archive, app_data);

	// Run main loop
	main_loop = g_main_loop_new(NULL, FALSE);
	g_main_loop_run(main_loop);

	return (EXIT_SUCCESS);
}
Exemple #29
0
int main(SIPE_UNUSED_PARAMETER int argc, SIPE_UNUSED_PARAMETER char **argv)
{
	sipe_xml *xml;
	const sipe_xml *child1, *child2;

#if 0
	/*
	 * No idea why the memory leak checks work on some platforms
	 * but fail on others :-( Disable for now...
	 */
	g_mem_set_vtable(&memory_leak_check);
#else
	(void) memory_leak_check;
#endif

	/* empty XML */
	xml = assert_parse(NULL, FALSE);
	assert_stringify(xml, 1, NULL);
	sipe_xml_free(xml);
	xml = assert_parse("",   FALSE);
	sipe_xml_free(xml);
	xml = assert_parse("<?xml version=\"1.0\" ?>", FALSE);
	sipe_xml_free(xml);

	/* one node */
	xml = assert_parse("<test></test>", TRUE);
	assert_name(xml, "test");
	assert_data(xml, NULL);
	assert_stringify(xml, 1, "<test/>");
	sipe_xml_free(xml);
	xml = assert_parse("<test/>", TRUE);
	assert_name(xml, "test");
	assert_data(xml, NULL);
	assert_stringify(xml, 1, teststring);
	sipe_xml_free(xml);
	xml = assert_parse("<test>a</test>", TRUE);
	assert_name(xml, "test");
	assert_data(xml, "a");
	assert_stringify(xml, 1, teststring);
	sipe_xml_free(xml);
	xml = assert_parse("<test>a\nb</test>", TRUE);
	assert_name(xml, "test");
	assert_data(xml, "a\nb");
	assert_stringify(xml, 1, teststring);
	sipe_xml_free(xml);

	/* child node */
	xml = assert_parse("<test>a<child>b</child></test>", TRUE);
	assert_name(xml, "test");
	assert_data(xml, "a");
	child1 = assert_child(xml, NULL, FALSE);
	child1 = assert_child(xml, "child", TRUE);
	assert_name(child1, "child");
	assert_data(child1, "b");
	child1 = assert_child(xml, "shouldnotmatch", FALSE);
	assert_data(child1, NULL);
	assert_stringify(xml, 1, teststring);
	sipe_xml_free(xml);

	xml = assert_parse("<test>a<child/></test>", TRUE);
	assert_name(xml, "test");
	assert_data(xml, "a");
	child1 = assert_child(xml, "child", TRUE);
	assert_name(child1, "child");
	assert_data(child1, NULL);
	child1 = assert_child(xml, "shouldnotmatch", FALSE);
	assert_data(child1, NULL);
	assert_stringify(xml, 1, teststring);
	sipe_xml_free(xml);

	xml = assert_parse("<test>a<child>b<inner>c</inner></child></test>", TRUE);
	assert_name(xml, "test");
	assert_data(xml, "a");
	child1 = assert_child(xml, "child", TRUE);
	assert_name(child1, "child");
	assert_data(child1, "b");
	child1 = assert_child(child1, "inner", TRUE);
	assert_name(child1, "inner");
	assert_data(child1, "c");
	child1 = assert_child(xml, "child/inner", TRUE);
	assert_name(child1, "inner");
	assert_data(child1, "c");
	assert_stringify(xml, 1, teststring);
	sipe_xml_free(xml);

	xml = assert_parse("<test>a<child>b<inner>c<innerinner>d</innerinner></inner></child></test>", TRUE);
	assert_name(xml, "test");
	assert_data(xml, "a");
	child1 = assert_child(xml, "child", TRUE);
	assert_name(child1, "child");
	assert_data(child1, "b");
	child2 = assert_child(child1, "inner/innerinner", TRUE);
	assert_name(child2, "innerinner");
	assert_data(child2, "d");
	child1 = assert_child(child1, "inner", TRUE);
	assert_name(child1, "inner");
	assert_data(child1, "c");
	child1 = assert_child(child1, "innerinner", TRUE);
	assert_name(child1, "innerinner");
	assert_data(child1, "d");
	child1 = assert_child(xml, "child/inner", TRUE);
	assert_name(child1, "inner");
	assert_data(child1, "c");
	child1 = assert_child(xml, "child/inner/innerinner", TRUE);
	assert_name(child1, "innerinner");
	assert_data(child1, "d");
	assert_stringify(xml, 1, teststring);
	sipe_xml_free(xml);

	/* attributes */
	xml = assert_parse("<test a=\"\">a</test>", TRUE);
	assert_name(xml, "test");
	assert_data(xml, "a");
	assert_attribute(xml, NULL, NULL);
	assert_attribute(xml, "a", "");
	assert_attribute(xml, "b", NULL);
	assert_stringify(xml, 1, teststring);
	sipe_xml_free(xml);

	xml = assert_parse("<test a=\"1\" b=\"abc\">a</test>", TRUE);
	assert_name(xml, "test");
	assert_data(xml, "a");
	assert_attribute(xml, "a", "1");
	assert_int_attribute(xml, "a", 1, 0);
	assert_attribute(xml, "b", "abc");
	assert_attribute(xml, "c", NULL);
	assert_int_attribute(xml, "d", 100, 200);
	/* the attribute order depends on glib hashing :-( */
	assert_stringify(xml, 2, teststring, "<test b=\"abc\" a=\"1\">a</test>");
	sipe_xml_free(xml);

	/* attributes with namespace */
	xml = assert_parse("<m:row m:uri=\"sip:\" m:displayName=\"X\" m:title=\"Y\" m:office=\"Z\" m:phone=\"0\" m:company=\"A\" m:city=\"B\" m:state=\"C\" m:country=\"D\" m:email=\"E\" />", TRUE);
	assert_name(xml, "row");
	assert_data(xml, NULL);
	assert_attribute(xml, "uri", "sip:");
	assert_attribute(xml, "displayName", "X");
	assert_attribute(xml, "title", "Y");
	assert_attribute(xml, "office", "Z");
	assert_attribute(xml, "phone", "0");
	assert_attribute(xml, "company", "A");
	assert_attribute(xml, "city", "B");
	assert_attribute(xml, "state", "C");
	assert_attribute(xml, "country", "D");
	assert_attribute(xml, "email", "E");
	sipe_xml_free(xml);

	xml = assert_parse("<state xsi:type=\"aggregateState\" lastActive=\"date\" xmlns:xsi=\"http://one\" xmlns=\"http://two\"><availability>15500</availability></state>", TRUE);
	assert_name(xml, "state");
	assert_data(xml, NULL);
	assert_attribute(xml, "type", "aggregateState");
	assert_attribute(xml, "lastActive", "date");
	assert_attribute(xml, "xsi", "http://one");
	assert_attribute(xml, "xmlns", "http://two");
	child1 = assert_child(xml, "availability", TRUE);
	assert_name(child1, "availability");
	assert_data(child1, "15500");
	sipe_xml_free(xml);

	/* broken XML */
	xml = assert_parse("t", FALSE);
	sipe_xml_free(xml);
	xml = assert_parse("<>", FALSE);
	sipe_xml_free(xml);
	xml = assert_parse("<></>", FALSE);
	sipe_xml_free(xml);
	xml = assert_parse("<test>", FALSE);
	sipe_xml_free(xml);
	xml = assert_parse("<a a=\"1\" a=\"2\"></a>", FALSE);
	sipe_xml_free(xml);

	if (allocated) {
		printf("MEMORY LEAK: %" G_GSIZE_FORMAT " still allocated\n", allocated);
		failed++;
	} else {
		printf("MEMORY LEAK CHECK OK\n");
		succeeded++;
	}

	printf("Result: %d PASSED %d FAILED\n", succeeded, failed);
	return(failed);
}
Exemple #30
0
int main(int argc, char **argv)
{
	static int version = 0;
	static GOptionEntry options[] = {
		{ "dummy", 'd', 0, G_OPTION_ARG_NONE, &dummy, "Use the dummy terminal mode", NULL },
		{ "version", 'v', 0, G_OPTION_ARG_NONE, &version, "Display irssi version", NULL },
		{ NULL }
	};

#ifdef USE_GC
	g_mem_set_vtable(&gc_mem_table);
#endif

	core_register_options();
	fe_common_core_register_options();
	args_register(options);
	args_execute(argc, argv);

 	if (version) {
		printf(PACKAGE_TARNAME" " PACKAGE_VERSION" (%d %04d)\n",
		       IRSSI_VERSION_DATE, IRSSI_VERSION_TIME);
		return 0;
	}

	srand(time(NULL));

	dummy = FALSE;
	quitting = FALSE;
	core_preinit(argv[0]);

	check_files();

#ifdef WIN32
        winsock_init();
#endif
#ifdef HAVE_SOCKS
	SOCKSinit(argv[0]);
#endif

	/* setlocale() must be called at the beginning before any calls that
	   affect it, especially regexps seem to break if they're generated
	   before this call.

	   locales aren't actually used for anything else than autodetection
	   of UTF-8 currently..  

	   furthermore to get the users's charset with g_get_charset() properly 
	   you have to call setlocale(LC_ALL, "") */
	setlocale(LC_ALL, "");

	textui_init();

	if (!dummy && !term_init()) {
		fprintf(stderr, "Can't initialize screen handling, quitting.\n");
		fprintf(stderr, "You can still use the dummy mode with -d parameter\n");
		return 1;
	}

	textui_finish_init();
	main_loop = g_main_new(TRUE);

	/* Does the same as g_main_run(main_loop), except we
	   can call our dirty-checker after each iteration */
	while (!quitting) {
#ifdef USE_GC
		GC_collect_a_little();
#endif
		if (!dummy) term_refresh_freeze();
		g_main_iteration(TRUE);
                if (!dummy) term_refresh_thaw();

		if (reload_config) {
                        /* SIGHUP received, do /RELOAD */
			reload_config = FALSE;
                        signal_emit("command reload", 1, "");
		}

		dirty_check();
	}

	g_main_destroy(main_loop);
	textui_deinit();

        session_upgrade(); /* if we /UPGRADEd, start the new process */
	return 0;
}