Exemple #1
0
int
main (void)
{
  struct re_pattern_buffer regbuf;
  const char *err;
  size_t i;
  int ret = 0;

#ifdef HAVE_MCHECK_H
  mtrace ();
#endif

  for (i = 0; i < sizeof (tests) / sizeof (tests[0]); ++i)
    {
      int start;
      re_set_syntax (tests[i].syntax);
      memset (&regbuf, '\0', sizeof (regbuf));
      err = re_compile_pattern (tests[i].pattern, strlen (tests[i].pattern),
                                &regbuf);
      if (err != NULL)
	{
	  printf ("re_compile_pattern failed: %s\n", err);
	  ret = 1;
	  continue;
	}

      start = re_search (&regbuf, tests[i].string, strlen (tests[i].string),
                         0, strlen (tests[i].string), NULL);
      if (start != tests[i].start)
	{
	  printf ("re_search failed %d\n", start);
	  ret = 1;
	  regfree (&regbuf);
	  continue;
	}
      regfree (&regbuf);
    }

  return ret;
}
Exemple #2
0
int
main (void)
{
    regex_t re;
    regmatch_t rm[2];
    int n;

#ifdef HAVE_MCHECK_H
    mtrace ();
#endif

    n = regcomp (&re, "^#! */.*/(k|ba||pdk|z)sh", REG_EXTENDED);
    if (n != 0)
    {
        char buf[500];
        regerror (n, &re, buf, sizeof (buf));
        printf ("regcomp failed: %s\n", buf);
        exit (1);
    }

    for (n = 0; n < 20; ++n)
    {
        if (regexec (&re, text, 2, rm, 0))
        {
            puts ("regexec failed");
            exit (2);
        }
        if (rm[0].rm_so != 0 || rm[0].rm_eo != 10
                || rm[1].rm_so != 8 || rm[1].rm_eo != 8)
        {
            printf ("regexec match failure: %d %d %d %d\n",
                    rm[0].rm_so, rm[0].rm_eo, rm[1].rm_so, rm[1].rm_eo);
            exit (3);
        }
    }

    regfree (&re);

    return 0;
}
Exemple #3
0
int
zmain (void)
{
    regex_t re;
    int i;
    int ret = 0;

    mtrace ();

    for (i = 0; i < 32; ++i)
    {
        if (regcomp (&re, "X-.+:.+Y=\".*\\.(A|B|C|D|E|F|G|H|I",
                     REG_EXTENDED | REG_ICASE) == 0)
        {
            puts ("regcomp unexpectedly succeeded");
            ret = 1;
        }
        else
            regfree (&re);
    }
    return ret;
}
Exemple #4
0
int main()
{
    mtrace();
    char *data1, *data2;
    int i;

    do {
       data1 = malloc (SIZE);
       printf ("Please input your eos username: "******"%s", data1);
       if (!strcmp (data1, "quit"))
          break;
       data2 = malloc (SIZE);
       for (i=0; i<SIZE; i++)
          data2[i] = data1[i];
       free (data1);
       printf ("data2 :%s:\n", data2);
       free (data2);
       muntrace();
    } while (1);
    return 0;
}
Exemple #5
0
int main(int argc, const char *argv[])
{
#ifdef __linux
    mtrace();
#endif
    run_cases("buf_test", buf_test_cases);
    run_cases("cfg_test", cfg_test_cases);
    run_cases("datetime_test", datetime_test_cases);
    run_cases("dict_test", dict_test_cases);
    run_cases("event_test", event_test_cases);
    run_cases("heap_test", heap_test_cases);
    run_cases("ketama_test", ketama_test_cases);
    run_cases("list_test", list_test_cases);
    run_cases("log_test", log_test_cases);
    run_cases("map_test", map_test_cases);
    run_cases("queue_test", queue_test_cases);
    run_cases("skiplist_test", skiplist_test_cases);
    run_cases("stack_test", stack_test_cases);
    run_cases("strings_test", strings_test_cases);
    run_cases("utils_test", utils_test_cases);
    return 0;
}
int main(int argc, char **argv)
{
  char * leak = NULL;
  
  /* trace starts */
  mtrace();

  leak = (char*)malloc(10);
  strcpy(leak,"Data1");
  printf("test: %s\n",leak);

  /* THIS IS LEAK - now we are unable to free first malloc() data ! */
  leak = (char*)malloc(10);
  strcpy(leak,"Data2");
  printf("test: %s\n",leak);

  /* this frees only second allocation */
  free(leak);

  /* trace ends */ 
  muntrace();
  return 0;
}
PageExtractStats::PageExtractStats(QWidget * parent)
{
    MY_DEBUG;

    listwidgetFiles = new QListWidget(parent);
    listwidgetFiles->setSortingEnabled(true);

    pushbuttonFiles = new QPushButton("Files...");
    pushbuttonClearFiles = new QPushButton("Clear List");
    pushbuttonCancel = NULL;
    pushbuttonStart = NULL;

    labelLoadingApp = NULL;
    labelLoadingPercent = NULL;
    labelLoadingFileName = NULL;

    vboxlayoutFiles = new QVBoxLayout;
    gridlayout = new QGridLayout;
mtrace();
    movieLoadingApp = new QMovie("images/loading.gif");
    movieLoadingApp->setSpeed(150);
    message = Messages::instance();
}
Exemple #8
0
int
main (void)
{
  regex_t re;
  regmatch_t rm[4];
  size_t i;
  int n, ret = 0;

#ifdef HAVE_MCHECK_H
  mtrace ();
#endif

  for (i = 0; i < sizeof (tests) / sizeof (tests[0]); ++i)
    {
      n = regcomp (&re, tests[i].pattern, tests[i].flags);
      if (n != 0)
	{
	  char buf[500];
	  regerror (n, &re, buf, sizeof (buf));
	  printf ("regcomp %lu failed: %s\n", i, buf);
	  ret = 1;
	  continue;
	}

      if (! regexec (&re, tests[i].string, tests[i].nmatch,
		     tests[i].nmatch ? rm : NULL, 0))
	{
	  printf ("regexec %lu incorrectly matched\n", i);
	  ret = 1;
	}

      regfree (&re);
    }

  return ret;
}
Exemple #9
0
static void				_constructor
birth(
	void
)
{

	where = getenv( name );
	is_set = (where != NULL);
	if( !is_set )	{
		where = "mtrace.out";
		is_set = (setenv( name, where, 1 ) != -1);
	}
	if( is_set )	{
		mtrace();
	}
	if( is_set )	{
		static char	banner[] = "Memory tracing enabled.\n";
		size_t const	qty = sizeof( banner )-1;

		if( write( fileno( stderr ), banner, qty ) != (ssize_t) qty )	{
			/* Hmmm */
		}
	}
}
Exemple #10
0
/**
 * main
 */
int main(int argc, char **args) {
  list *slices;
  surface *surf;

  /* turn on memory tracing */
  putenv("MALLOC_TRACE=memtest_memtrace.txt");
  mtrace();

  /* read the slices from the file */
  slices = readSliceContours(args[1]);
  if(slices == NULL) {
    printf("couldn't read slices from %s!\n",args[1]);
    return 0;
  }

  preprocessSliceContours(slices);

  /* builds a guess at contour correspondence */
//  correspondenceMethod = HISTOGRAM;
//  correspondenceScope = LOCAL;  
  buildCorrespondenceGuess(slices);

  /* tile the slices */
//  minSliceInd = 0;
//  maxSliceInd = 40;
  surf = tileSlices(slices);

  deleteSliceContours(slices);

  fillBranchedHoles(surf);

  writeOFF(surf,"testmem.off");
  deleteSurface(surf);

  return 0;
}
Exemple #11
0
static int
do_test (void)
{
  glob_t gl;
  int errval;
  int result = 0;
  const char *fmt;
  int flags;

  mtrace ();

  memset (&gl, '\0', sizeof (gl));

  gl.gl_closedir = my_closedir;
  gl.gl_readdir = my_readdir;
  gl.gl_opendir = my_opendir;
  gl.gl_lstat = my_stat;
  gl.gl_stat = my_stat;

#define test(a, b, r, c...) \
  fmt = a;								      \
  flags = GLOB_ALTDIRFUNC | b;						      \
  errval = glob (fmt, flags, NULL, &gl);				      \
  if (errval != r)							      \
    {									      \
      if (r == 0)							      \
	printf ("glob (\"%s\", %s) failed: %s\n", fmt, flagstr (flags),	      \
		errval >= 0 && errval < nglob_errstring			      \
		? glob_errstring[errval] : "???");			      \
      else								      \
	printf ("glob (\"%s\", %s) did not fail\n", fmt, flagstr (flags));    \
      result = 1;							      \
    }									      \
  else if (r == 0)							      \
    result |= test_result (fmt, flags, &gl, (const char *[]) { c, NULL });    \
  else									      \
    printf ("result for glob (\"%s\", %s) = %s\n\n", fmt, flagstr (flags),    \
	    errstr (errval))

  test ("*/*/*", 0, 0,
	"dir1lev1/dir2lev2/dir1lev3",
	"dir1lev1/dir2lev2/file1lev3",
	"dir1lev1/dir2lev2/file2lev3",
	"dir1lev1/dir3lev2/file3lev3",
	"dir1lev1/dir3lev2/file4lev3");

  test ("*/*/*", GLOB_PERIOD, 0,
	"dir1lev1/dir1lev2/.",
	"dir1lev1/dir1lev2/..",
	"dir1lev1/dir2lev2/.",
	"dir1lev1/dir2lev2/..",
	"dir1lev1/dir2lev2/.foo",
	"dir1lev1/dir2lev2/dir1lev3",
	"dir1lev1/dir2lev2/file1lev3",
	"dir1lev1/dir2lev2/file2lev3",
	"dir1lev1/dir3lev2/.",
	"dir1lev1/dir3lev2/..",
	"dir1lev1/dir3lev2/file3lev3",
	"dir1lev1/dir3lev2/file4lev3",
	"dir2lev1/dir1lev2/.",
	"dir2lev1/dir1lev2/..",
	"dir2lev1/dir1lev2/.dir",
	"dir2lev1/dir1lev2/.foo");

  test ("*/*/.*", 0, 0,
	"dir1lev1/dir1lev2/.",
	"dir1lev1/dir1lev2/..",
	"dir1lev1/dir2lev2/.",
	"dir1lev1/dir2lev2/..",
	"dir1lev1/dir2lev2/.foo",
	"dir1lev1/dir3lev2/.",
	"dir1lev1/dir3lev2/..",
	"dir2lev1/dir1lev2/.",
	"dir2lev1/dir1lev2/..",
	"dir2lev1/dir1lev2/.dir",
	"dir2lev1/dir1lev2/.foo");

  test ("*1*/*2*/.*", 0, 0,
	"dir1lev1/dir1lev2/.",
	"dir1lev1/dir1lev2/..",
	"dir1lev1/dir2lev2/.",
	"dir1lev1/dir2lev2/..",
	"dir1lev1/dir2lev2/.foo",
	"dir1lev1/dir3lev2/.",
	"dir1lev1/dir3lev2/..",
	"dir2lev1/dir1lev2/.",
	"dir2lev1/dir1lev2/..",
	"dir2lev1/dir1lev2/.dir",
	"dir2lev1/dir1lev2/.foo");

  test ("*1*/*1*/.*", 0, 0,
	"dir1lev1/dir1lev2/.",
	"dir1lev1/dir1lev2/..",
	"dir2lev1/dir1lev2/.",
	"dir2lev1/dir1lev2/..",
	"dir2lev1/dir1lev2/.dir",
	"dir2lev1/dir1lev2/.foo");

  test ("\\/*", 0, 0,
	"/dir1lev1",
	"/dir2lev1",
	"/file1lev1",
	"/file2lev1");

  test ("*/*/", 0 , 0,
	"dir1lev1/dir1lev2/",
	"dir1lev1/dir2lev2/",
	"dir1lev1/dir3lev2/",
	"dir2lev1/dir1lev2/");

  test ("", 0, GLOB_NOMATCH, NULL);

  test ("", GLOB_NOCHECK, 0, "");

  globfree (&gl);

  return result;
}
Exemple #12
0
int
main (int argc, char **argv)
{
  int ret = 0;
  char *line = NULL;
  size_t line_len = 0;
  ssize_t len;
  FILE *f;
  static int test_utf8 = 0;
  static const struct option options[] =
    {
      {"utf8",	no_argument,	&test_utf8,	1},
      {NULL,	0,		NULL,		0 }
    };

#ifdef HAVE_MCHECK_H
  mtrace ();
#endif

  while (getopt_long (argc, argv, "", options, NULL) >= 0);

  if (optind + 1 != argc)
    {
      fprintf (stderr, "Missing test filename\n");
      return 1;
    }

  f = fopen (argv[optind], "r");
  if (f == NULL)
    {
      fprintf (stderr, "Couldn't open %s\n", argv[optind]);
      return 1;
    }

  while ((len = getline (&line, &line_len, f)) > 0)
    {
      char *pattern, *flagstr, *string, *expect, *matches, *p;
      int cflags = REG_EXTENDED, eflags = 0, try_bre_ere = 0;

      if (line[len - 1] == '\n')
        line[len - 1] = '\0';

      /* Skip comments and empty lines.  */
      if (*line == '#' || *line == '\0')
	continue;

      puts (line);
      fflush (stdout);

      pattern = strtok (line, "\t");
      if (pattern == NULL)
        continue;

      if (strcmp (pattern, "\"\"") == 0)
	pattern += 2;

      flagstr = strtok (NULL, "\t");
      if (flagstr == NULL)
        continue;

      string = strtok (NULL, "\t");
      if (string == NULL)
        continue;

      if (strcmp (string, "\"\"") == 0)
	string += 2;

      for (p = flagstr; *p; ++p)
	switch (*p)
	  {
	  case '-':
	    break;
	  case 'b':
	    cflags &= ~REG_EXTENDED;
	    break;
	  case '&':
	    try_bre_ere = 1;
	    break;
	  case 'C':
	    eflags = -1;
	    break;
	  case 'i':
	    cflags |= REG_ICASE;
	    break;
	  case 's':
	    cflags |= REG_NOSUB;
	    break;
	  case 'n':
	    cflags |= REG_NEWLINE;
	    break;
	  case '^':
	    eflags |= REG_NOTBOL;
	    break;
	  case '$':
	    eflags |= REG_NOTEOL;
	    break;
	  case 'm':
	  case 'p':
	  case '#':
	    /* Not supported.  */
	    flagstr = NULL;
	    break;
	  }

      if (flagstr == NULL)
	continue;

      replace_special_chars (pattern);
      glibc_re_syntax (pattern);
      if (eflags != -1)
        replace_special_chars (string);

      expect = strtok (NULL, "\t");
      matches = NULL;
      if (expect != NULL)
        {
	  replace_special_chars (expect);
	  matches = strtok (NULL, "\t");
	  if (matches != NULL)
	    replace_special_chars (matches);
        }

      if (setlocale (LC_ALL, "C") == NULL)
	{
	  puts ("setlocale C failed");
	  ret = 1;
	}
      if (test (pattern, cflags, string, eflags, expect, matches, "FAIL")
	  || (try_bre_ere
	      && test (pattern, cflags & ~REG_EXTENDED, string, eflags,
		       expect, matches, "FAIL")))
	ret = 1;
      else if (test_utf8)
	{
	  if (setlocale (LC_ALL, "cs_CZ.UTF-8") == NULL)
	    {
	      puts ("setlocale cs_CZ.UTF-8 failed");
	      ret = 1;
	    }
	  else if (test (pattern, cflags, string, eflags, expect, matches,
			 "UTF-8 FAIL")
		   || (try_bre_ere
		       && test (pattern, cflags & ~REG_EXTENDED, string,
				eflags, expect, matches, "UTF-8 FAIL")))
	    ret = 1;
	  else if (mb_tests (pattern, cflags, string, eflags, expect, matches)
		   || (try_bre_ere
		       && mb_tests (pattern, cflags & ~REG_EXTENDED, string,
				    eflags, expect, matches)))
	    ret = 1;
	}
    }

  free (line);
  fclose (f);
  return ret;
}
Exemple #13
0
int
main(int argc, char **argv)
{
	int flag;
	int argerr = 0;
	const char *xml_file = NULL;
	crm_data_t *xml_graph = NULL;
  
	set_crm_log_level(0);
/* 	crm_log_init("ttest"); */
	g_log_set_handler(NULL,
			  G_LOG_LEVEL_ERROR      | G_LOG_LEVEL_CRITICAL
			  | G_LOG_LEVEL_WARNING  | G_LOG_LEVEL_MESSAGE
			  | G_LOG_LEVEL_INFO     | G_LOG_LEVEL_DEBUG
			  | G_LOG_FLAG_RECURSION | G_LOG_FLAG_FATAL,
			  cl_glib_msg_handler, NULL);

	/* and for good measure... - this enum is a bit field (!) */
	g_log_set_always_fatal((GLogLevelFlags)0); /*value out of range*/
	set_crm_log_level(LOG_WARNING);

	transition_trigger = G_main_add_TriggerHandler(
		G_PRIORITY_LOW, te_graph_trigger, NULL, NULL);

	set_graph_functions(&ttest_graph_fns);

	while (1) {
		flag = getopt(argc, argv, OPTARGS);
		if (flag == -1)
			break;
    
		switch(flag) {
			case 'X':
				xml_file = crm_strdup(optarg);
				break;

			case 'V':
				cl_log_enable_stderr(TRUE);
				alter_debug(DEBUG_INC);
				break;
			default:
				printf("?? getopt returned character code 0%o ??\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_debug("=#=#=#=#= Getting XML =#=#=#=#=");
	if(xml_file != NULL) {
		FILE *xml_strm = fopen(xml_file, "r");
		if(xml_strm) {
			xml_graph = file2xml(xml_strm, FALSE);
			fclose(xml_strm);
			
		} else {
			cl_perror("Could not open %s for reading", xml_file);
			xml_file = NULL;
		}
		
	}
	if(xml_file == NULL) {
		xml_graph = stdin2xml();
	}

#ifdef MTRACE  
	mtrace();
#endif

	transition_graph = unpack_graph(xml_graph);
	trigger_graph();
	print_graph(LOG_DEBUG, transition_graph);
	transition_graph->completion_action = tg_shutdown;

	mainloop = g_main_new(FALSE);
	
	g_main_run(mainloop);
	
	crm_info("Exiting ttest");
	
#ifdef MTRACE  
	muntrace();
#endif
	crm_debug_4("Transition complete...");

	return 0;
}
int
main (void)
{
  char *linebuf = NULL;
  size_t linebuflen = 0;
  int ntests = 0;
  int nfailed = 0;
  char *escinput = NULL;
  size_t escinputlen = 0;
  char *escpattern = NULL;
  size_t escpatternlen = 0;
  int nr = 0;

  mtrace ();

  /* Read lines from stdin with the following format:

       locale  input-string  match-string  flags  result

     where `result' is either 0 or 1.  If the first character of a
     string is '"' we read until the next '"' and handled escaped '"'.  */
  while (! feof (stdin))
    {
      ssize_t n = getline (&linebuf, &linebuflen, stdin);
      char *cp;
      const char *locale;
      const char *input;
      const char *pattern;
      const char *result_str;
      int result;
      const char *flags;
      int flags_val;
      int fnmres;
      char numbuf[24];

      if (n == -1)
	break;

      if (n == 0)
	/* Maybe an empty line.  */
	continue;

      /* Skip over all leading white spaces.  */
      cp = linebuf;

      locale = next_input (&cp, 1, 0);
      if (locale == NULL)
	continue;

      input = next_input (&cp, 0, 0);
      if (input == NULL)
	continue;

      pattern = next_input (&cp, 0, 0);
      if (pattern == NULL)
	continue;

      result_str = next_input (&cp, 0, 0);
      if (result_str == NULL)
	continue;

      if (strcmp (result_str, "0") == 0)
	result = 0;
      else if  (strcasecmp (result_str, "NOMATCH") == 0)
	result = FNM_NOMATCH;
      else
	{
	  char *endp;
	  result = strtol (result_str, &endp, 0);
	  if (*endp != '\0')
	    continue;
	}

      flags = next_input (&cp, 0, 1);
      if (flags == NULL)
	/* We allow the flags missing.  */
	flags = "";

      /* Convert the text describing the flags in a numeric value.  */
      flags_val = convert_flags (flags);
      if (flags_val == -1)
	/* Something went wrong.  */
	continue;

      /* Now run the actual test.  */
      ++ntests;

      if (setlocale (LC_COLLATE, locale) == NULL
	  || setlocale (LC_CTYPE, locale) == NULL)
	{
	  puts ("*** Cannot set locale");
	  ++nfailed;
	  continue;
	}

      fnmres = fnmatch (pattern, input, flags_val);

      printf ("%3d: fnmatch (\"%s\", \"%s\", %s) = %s%c",
	      ++nr,
	      escape (pattern, &escpatternlen, &escpattern),
	      escape (input, &escinputlen, &escinput),
	      flag_output (flags_val),
	      (fnmres == 0
	       ? "0" : (fnmres == FNM_NOMATCH
			? "FNM_NOMATCH"
			: (sprintf (numbuf, "%d", fnmres), numbuf))),
	      (fnmres != 0) != (result != 0) ? ' ' : '\n');

      if ((fnmres != 0) != (result != 0))
	{
	  printf ("(FAIL, expected %s) ***\n",
		  result == 0
		  ? "0" : (result == FNM_NOMATCH
			   ? "FNM_NOMATCH"
			   : (sprintf (numbuf, "%d", result), numbuf)));
	  ++nfailed;
	}
    }

  printf ("=====================\n%3d tests, %3d failed\n", ntests, nfailed);

  free (escpattern);
  free (escinput);
  free (linebuf);

  return nfailed != 0;
}
Exemple #15
0
int main(int argc, char** argv, char** envp)
{
	if (argc == 1)
	{
		std::cerr << "This is Darling dyld for " ARCH_NAME ".\n";
		std::cerr << "Copyright (C) 2012-2013 Lubos Dolezel\n"
			"Copyright (C) 2011 Shinichiro Hamaji\n\n";
		
		std::cerr << "Usage: " << argv[0] << " program-path [arguments...]\n\n";
		std::cerr << "Environment variables:\n"
			"\tDYLD_DEBUG=1 - enable debug info (lots of output)\n"
			"\tDYLD_MTRACE=1 - enable mtrace\n"
#ifdef DEBUG
			"\tDYLD_IGN_MISSING_SYMS=1 - replace missing symbol references with a stub function\n"
			"\tDYLD_TRAMPOLINE=1 - access all bound functions via a debug trampoline\n"
#endif
			"\tDYLD_ROOT_PATH=<path> - set the base for library path resolution (overrides autodetection)\n"
			"\tDYLD_BIND_AT_LAUNCH=1 - force dyld to bind all lazy references on startup\n";
		return 1;
	}
	
	try
	{
		if (!::realpath(argv[0], g_dyld_path))
			::strcpy(g_dyld_path, argv[0]);

		if (argc == 2)
		{
			if (!strcmp(argv[1], "--register"))
			{
				Darling::binfmtRegister(g_dyld_path);
				return 0;
			}
			else if (!strcmp(argv[1], "--deregister"))
			{
				Darling::binfmtDeregister();
				return 0;
			}
		}
		
		setupDyldPath(argv[0]);
		// sets up @executable_path
		setupExecutablePath(argv[1]);
	
		// setlocale(LC_CTYPE, "");
		if (getenv("DYLD_MTRACE") && atoi(getenv("DYLD_MTRACE")))
			mtrace();
		if (getenv("DYLD_TRAMPOLINE") && atoi(getenv("DYLD_TRAMPOLINE")))
			g_trampoline = true;
		if (getenv("DYLD_NO_WEAK"))
			g_noWeak = true;

		g_mainBinary = MachO::readFile(argv[1], ARCH_NAME);
		
		if (!g_mainBinary)
			throw std::runtime_error("Cannot open binary file");

		checkPlatform(argv[1], g_mainBinary);

		// Modify the argument list so that the dyld name disappears from the process list.
		// The Linux kernel doesn't really support this - it remembers the byte length of the cmdline, which will now decrease.
		// Any app that examines this process' /proc/.../cmdline will from now on see a group of empty arguments after the real arguments.
		// We fix this for NSProcessInfo in libobjcdarwin.
		/*	
		uintptr_t totalLen = argv[argc-1] + strlen(argv[argc-1]) + 1 - argv[0];
		uintptr_t shortenedLen = totalLen - (strlen(argv[0]) + 1);

		memmove(argv[0], argv[1], shortenedLen);
		memset(argv[0]+shortenedLen, 0, totalLen - shortenedLen);

		// Reconstruct the argv array
		for (int pos = 0, index = 1; index < argc-1; pos++)
		{
			if (!argv[0][pos])
				argv[index++] = &argv[0][pos+1];
		}
		*/

		g_argv = argv+1;
		g_argc = argc-1;
		g_loader = new MachOLoader;
		
		autoSysrootSearch();
		bool forceBind = false;
		
		if (g_trampoline || getenv("DYLD_BIND_AT_LAUNCH") != nullptr)
			forceBind = true;
		
		g_loader->run(*g_mainBinary, g_argc, g_argv, envp, forceBind);
		
		delete g_loader;
		g_loader = 0;
		return 2;
	}
	catch (fat_architecture_not_supported& e)
	{
		if (char* p = strstr(argv[0], "/" DYLD_FULL_NAME)) // multilib
		{
			// Try to automatically execute "the other" dyld on multilib systems
			// if that other dyld's platform is supported in the fat binary
			if (std::find(e.archs().begin(), e.archs().end(), ARCH_CROSS_NAME) != e.archs().end())
			{
				strcpy(p+1, DYLD_CROSS_NAME);
				execvp(argv[0], argv);
			}
		}
		
		std::cerr << argv[1] << " is a fat binary, but doesn't support the following architecture: " << ARCH_NAME << std::endl;
	}
	catch (std::exception& e)
	{
		std::cerr << e.what() << std::endl;
		return 1;
	}
}
Exemple #16
0
static int save_lua_report(udefrag_job_parameters *jp)
{
    wchar_t *path = NULL;
    WINX_FILE *f;
    wchar_t *cn;
    wchar_t compname[MAX_COMPUTERNAME_LENGTH + 1];
    char utf8_compname[(MAX_COMPUTERNAME_LENGTH + 1) * 4];
    char buffer[512];
    struct prb_traverser t;
    winx_file_info *file;
    char *comment;
    char *status;
    int length;
    winx_time tm;
    
    /* should be enough for any path in UTF-8 encoding */
    #define MAX_UTF8_PATH_LENGTH (256 * 1024)
    char *utf8_path;
    
    utf8_path = winx_tmalloc(MAX_UTF8_PATH_LENGTH);
    if(utf8_path == NULL){
        mtrace();
        return (-1);
    }
    
    path = get_report_path(jp);
    if(path == NULL)
        return UDEFRAG_NO_MEM;
    
    f = winx_fbopen(path,"w",RSB_SIZE);
    if(f == NULL){
        f = winx_fopen(path,"w");
        if(f == NULL){
            winx_free(path);
            winx_free(utf8_path);
            return (-1);
        }
    }

    /* print header */
    cn = winx_getenv(L"COMPUTERNAME");
    if(cn){
        wcsncpy(compname,cn,MAX_COMPUTERNAME_LENGTH + 1);
        compname[MAX_COMPUTERNAME_LENGTH] = 0;
        winx_free(cn);
    } else {
        wcscpy(compname,L"nil");
    }
    winx_to_utf8(utf8_compname,sizeof(utf8_compname),compname);
    memset(&tm,0,sizeof(winx_time));
    (void)winx_get_local_time(&tm);
    (void)_snprintf(buffer,sizeof(buffer),
        "-- UltraDefrag report for disk %c:\r\n\r\n"
        "format_version = 7\r\n\r\n"
        "volume_letter = \"%c\"\r\n"
        "computer_name = \"%hs\"\r\n\r\n"
        "current_time = {\r\n"
        "\tyear = %04i,\r\n"
        "\tmonth = %02i,\r\n"
        "\tday = %02i,\r\n"
        "\thour = %02i,\r\n"
        "\tmin = %02i,\r\n"
        "\tsec = %02i,\r\n"
        "\tisdst = false\r\n"
        "}\r\n\r\n"
        "files = {\r\n",
        jp->volume_letter, jp->volume_letter,utf8_compname,
        (int)tm.year,(int)tm.month,(int)tm.day,
        (int)tm.hour,(int)tm.minute,(int)tm.second
        );
    buffer[sizeof(buffer) - 1] = 0;
    (void)winx_fwrite(buffer,1,strlen(buffer),f);
    
    /* print body */
    prb_t_init(&t,jp->fragmented_files);
    file = prb_t_first(&t,jp->fragmented_files);
    while(file){
        if(is_directory(file))
            comment = "[DIR]";
        else if(is_compressed(file))
            comment = "[CMP]";
        else
            comment = " - ";
        
        /*
        * On change of status strings don't forget
        * also to adjust write_file_status routine
        * in udreportcnv.lua file.
        */
        if(is_locked(file))
            status = "locked";
        else if(is_moving_failed(file))
            status = "move failed";
        else if(is_in_improper_state(file))
            status = "invalid";
        else
            status = " - ";
        
        (void)_snprintf(buffer, sizeof(buffer),
            "\t{fragments = %u,"
            "size = %I64u,"
            "comment = \"%s\","
            "status = \"%s\","
            "path = \"",
            (UINT)file->disp.fragments,
            file->disp.clusters * jp->v_info.bytes_per_cluster,
            comment,
            status
            );
        buffer[sizeof(buffer) - 1] = 0;
        (void)winx_fwrite(buffer,1,strlen(buffer),f);

        if(file->path != NULL){
            /* skip \??\ sequence in the beginning of the path */
            length = (int)wcslen(file->path);
            if(length > 4){
                convert_to_utf8_path(utf8_path,MAX_UTF8_PATH_LENGTH,file->path + 4);
            } else {
                convert_to_utf8_path(utf8_path,MAX_UTF8_PATH_LENGTH,file->path);
            }
            (void)winx_fwrite(utf8_path,1,strlen(utf8_path),f);
        }

        (void)strcpy(buffer,"\"},\r\n");
        (void)winx_fwrite(buffer,1,strlen(buffer),f);

        file = prb_t_next(&t);
    }
    
    /* print footer */
    (void)strcpy(buffer,"}\r\n");
    (void)winx_fwrite(buffer,1,strlen(buffer),f);

    itrace("report saved to %ws",path);
    winx_fclose(f);
    winx_free(path);
    winx_free(utf8_path);
    return 0;
}
int main (int argc, char *argv[])
{
	errcode_t	retval = 0, retval2 = 0, orig_retval = 0;
	int		exit_value = FSCK_OK;
	ext2_filsys	fs = 0;
	io_manager	io_ptr;
	struct ext2_super_block *sb;
	const char	*lib_ver_date;
	int		my_ver, lib_ver;
	e2fsck_t	ctx;
	blk_t		orig_superblock;
	struct problem_context pctx;
	int flags, run_result;
	int journal_size;
	int sysval, sys_page_size = 4096;
	__u32 features[3];
	char *cp;
	klog_init();
	E2F_DBG_INFO("e2fsck start...");
#ifdef E2FSCK_PIPE_DEBUG_
	memset(pipe_msg_temp, 0, MSG_LEN);
	memcpy(pipe_msg_temp, argv[2], strlen(argv[2]));
  	pipe_open();
	pipe_write(C_IN_START);
#endif	

	clear_problem_context(&pctx);
#ifdef MTRACE
	mtrace();
#endif
#ifdef MCHECK
	mcheck(0);
#endif
#ifdef ENABLE_NLS
	setlocale(LC_MESSAGES, "");
	setlocale(LC_CTYPE, "");
	bindtextdomain(NLS_CAT_NAME, LOCALEDIR);
	textdomain(NLS_CAT_NAME);
#endif
	my_ver = ext2fs_parse_version_string(my_ver_string);
	lib_ver = ext2fs_get_library_version(0, &lib_ver_date);
	if (my_ver > lib_ver) {
		fprintf( stderr, _("Error: ext2fs library version "
			"out of date!\n"));
		show_version_only++;
	}

	retval = PRS(argc, argv, &ctx);
	if (retval) {
		com_err("e2fsck", retval,
			_("while trying to initialize program"));
		exit(FSCK_ERROR);
	}
	reserve_stdio_fds();

	init_resource_track(&ctx->global_rtrack, NULL);
	if (!(ctx->options & E2F_OPT_PREEN) || show_version_only)
		fprintf(stderr, "e2fsck %s (%s)\n", my_ver_string,
			 my_ver_date);

	if (show_version_only) {
		fprintf(stderr, _("\tUsing %s, %s\n"),
			error_message(EXT2_ET_BASE), lib_ver_date);
		exit(FSCK_OK);
	}

	check_mount(ctx);

	if (!(ctx->options & E2F_OPT_PREEN) &&
	    !(ctx->options & E2F_OPT_NO) &&
	    !(ctx->options & E2F_OPT_YES)) {
		if (!ctx->interactive)
			fatal_error(ctx,
				    _("need terminal for interactive repairs"));
	}
	ctx->superblock = ctx->use_superblock;
restart:
#ifdef CONFIG_TESTIO_DEBUG
	if (getenv("TEST_IO_FLAGS") || getenv("TEST_IO_BLOCK")) {
		io_ptr = test_io_manager;
		test_io_backing_manager = unix_io_manager;
	} else
#endif
		io_ptr = unix_io_manager;
	flags = EXT2_FLAG_NOFREE_ON_ERROR;
	if ((ctx->options & E2F_OPT_READONLY) == 0)
		flags |= EXT2_FLAG_RW;
	if ((ctx->mount_flags & EXT2_MF_MOUNTED) == 0)
		flags |= EXT2_FLAG_EXCLUSIVE;

	retval = try_open_fs(ctx, flags, io_ptr, &fs);

	if (!ctx->superblock && !(ctx->options & E2F_OPT_PREEN) &&
	    !(ctx->flags & E2F_FLAG_SB_SPECIFIED) &&
	    ((retval == EXT2_ET_BAD_MAGIC) ||
	     (retval == EXT2_ET_CORRUPT_SUPERBLOCK) ||
	     ((retval == 0) && (retval2 = ext2fs_check_desc(fs))))) {
		if (retval2 == ENOMEM) {
			retval = retval2;
			goto failure;
		}
		if (fs->flags & EXT2_FLAG_NOFREE_ON_ERROR) {
			ext2fs_free(fs);
			fs = NULL;
		}
		if (!fs || (fs->group_desc_count > 1)) {
			printf(_("%s: %s trying backup blocks...\n"),
			       ctx->program_name,
			       retval ? _("Superblock invalid,") :
			       _("Group descriptors look bad..."));
			orig_superblock = ctx->superblock;
			get_backup_sb(ctx, fs, ctx->filesystem_name, io_ptr);
			if (fs)
				ext2fs_close(fs);
			orig_retval = retval;
			retval = try_open_fs(ctx, flags, io_ptr, &fs);
			if ((orig_retval == 0) && retval != 0) {
				if (fs)
					ext2fs_close(fs);
				com_err(ctx->program_name, retval,
					"when using the backup blocks");
				printf(_("%s: going back to original "
					 "superblock\n"), ctx->program_name);
				ctx->superblock = orig_superblock;
				retval = try_open_fs(ctx, flags, io_ptr, &fs);
			}
		}
	}
	if (((retval == EXT2_ET_UNSUPP_FEATURE) ||
	     (retval == EXT2_ET_RO_UNSUPP_FEATURE)) &&
	    fs && fs->super) {
		sb = fs->super;
		features[0] = (sb->s_feature_compat &
			       ~EXT2_LIB_FEATURE_COMPAT_SUPP);
		features[1] = (sb->s_feature_incompat &
			       ~EXT2_LIB_FEATURE_INCOMPAT_SUPP);
		features[2] = (sb->s_feature_ro_compat &
			       ~EXT2_LIB_FEATURE_RO_COMPAT_SUPP);
		if (features[0] || features[1] || features[2])
			goto print_unsupp_features;
	}
failure:
	if (retval) {
		if (orig_retval)
			retval = orig_retval;
		com_err(ctx->program_name, retval, _("while trying to open %s"),
			ctx->filesystem_name);
		if (retval == EXT2_ET_REV_TOO_HIGH) {
			printf(_("The filesystem revision is apparently "
			       "too high for this version of e2fsck.\n"
			       "(Or the filesystem superblock "
			       "is corrupt)\n\n"));
			fix_problem(ctx, PR_0_SB_CORRUPT, &pctx);
		} else if (retval == EXT2_ET_SHORT_READ)
			printf(_("Could this be a zero-length partition?\n"));
		else if ((retval == EPERM) || (retval == EACCES))
			printf(_("You must have %s access to the "
			       "filesystem or be root\n"),
			       (ctx->options & E2F_OPT_READONLY) ?
			       "r/o" : "r/w");
		else if (retval == ENXIO)
			printf(_("Possibly non-existent or swap device?\n"));
		else if (retval == EBUSY)
			printf(_("Filesystem mounted or opened exclusively "
				 "by another program?\n"));
		else if (retval == ENOENT)
			printf(_("Possibly non-existent device?\n"));
#ifdef EROFS
		else if (retval == EROFS)
			printf(_("Disk write-protected; use the -n option "
			       "to do a read-only\n"
			       "check of the device.\n"));
#endif
		else
			fix_problem(ctx, PR_0_SB_CORRUPT, &pctx);
		fatal_error(ctx, 0);
	}
	/*
	 * We only update the master superblock because (a) paranoia;
	 * we don't want to corrupt the backup superblocks, and (b) we
	 * don't need to update the mount count and last checked
	 * fields in the backup superblock (the kernel doesn't update
	 * the backup superblocks anyway).  With newer versions of the
	 * library this flag is set by ext2fs_open2(), but we set this
	 * here just to be sure.  (No, we don't support e2fsck running
	 * with some other libext2fs than the one that it was shipped
	 * with, but just in case....)
	 */
	fs->flags |= EXT2_FLAG_MASTER_SB_ONLY;

	if (!(ctx->flags & E2F_FLAG_GOT_DEVSIZE)) {
		__u32 blocksize = EXT2_BLOCK_SIZE(fs->super);
		int need_restart = 0;

		pctx.errcode = ext2fs_get_device_size2(ctx->filesystem_name,
						       blocksize,
						       &ctx->num_blocks);
		/*
		 * The floppy driver refuses to allow anyone else to
		 * open the device if has been opened with O_EXCL;
		 * this is unlike other block device drivers in Linux.
		 * To handle this, we close the filesystem and then
		 * reopen the filesystem after we get the device size.
		 */
		if (pctx.errcode == EBUSY) {
			ext2fs_close(fs);
			need_restart++;
			pctx.errcode =
				ext2fs_get_device_size2(ctx->filesystem_name,
							blocksize,
							&ctx->num_blocks);
		}
		if (pctx.errcode == EXT2_ET_UNIMPLEMENTED)
			ctx->num_blocks = 0;
		else if (pctx.errcode) {
			fix_problem(ctx, PR_0_GETSIZE_ERROR, &pctx);
			ctx->flags |= E2F_FLAG_ABORT;
			fatal_error(ctx, 0);
		}
		ctx->flags |= E2F_FLAG_GOT_DEVSIZE;
		if (need_restart)
			goto restart;
	}

	ctx->fs = fs;
	fs->priv_data = ctx;
	fs->now = ctx->now;
	sb = fs->super;
	if (sb->s_rev_level > E2FSCK_CURRENT_REV) {
		com_err(ctx->program_name, EXT2_ET_REV_TOO_HIGH,
			_("while trying to open %s"),
			ctx->filesystem_name);
	get_newer:
		fatal_error(ctx, _("Get a newer version of e2fsck!"));
	}

	/*
	 * Set the device name, which is used whenever we print error
	 * or informational messages to the user.
	 */
	if (ctx->device_name == 0 &&
	    (sb->s_volume_name[0] != 0)) {
		ctx->device_name = string_copy(ctx, sb->s_volume_name,
					       sizeof(sb->s_volume_name));
	}
	if (ctx->device_name == 0)
		ctx->device_name = string_copy(ctx, ctx->filesystem_name, 0);
	for (cp = ctx->device_name; *cp; cp++)
		if (isspace(*cp) || *cp == ':')
			*cp = '_';

	ehandler_init(fs->io);

	if ((ctx->mount_flags & EXT2_MF_MOUNTED) &&
	    !(sb->s_feature_incompat & EXT3_FEATURE_INCOMPAT_RECOVER))
		goto skip_journal;

	/*
	 * Make sure the ext3 superblock fields are consistent.
	 */
	retval = e2fsck_check_ext3_journal(ctx);
	if (retval) {
		com_err(ctx->program_name, retval,
			_("while checking ext3 journal for %s"),
			ctx->device_name);
		fatal_error(ctx, 0);
	}

	/*
	 * Check to see if we need to do ext3-style recovery.  If so,
	 * do it, and then restart the fsck.
	 */
	if (sb->s_feature_incompat & EXT3_FEATURE_INCOMPAT_RECOVER) {
		if (ctx->options & E2F_OPT_READONLY) {
			printf(_("Warning: skipping journal recovery "
				 "because doing a read-only filesystem "
				 "check.\n"));
			io_channel_flush(ctx->fs->io);
		} else {
			if (ctx->flags & E2F_FLAG_RESTARTED) {
				/*
				 * Whoops, we attempted to run the
				 * journal twice.  This should never
				 * happen, unless the hardware or
				 * device driver is being bogus.
				 */
				com_err(ctx->program_name, 0,
					_("unable to set superblock flags on %s\n"), ctx->device_name);
				fatal_error(ctx, 0);
			}
			retval = e2fsck_run_ext3_journal(ctx);
			if (retval) {
				com_err(ctx->program_name, retval,
				_("while recovering ext3 journal of %s"),
					ctx->device_name);
				fatal_error(ctx, 0);
			}
			ext2fs_close(ctx->fs);
			ctx->fs = 0;
			ctx->flags |= E2F_FLAG_RESTARTED;
			goto restart;
		}
	}

skip_journal:
	/*
	 * Check for compatibility with the feature sets.  We need to
	 * be more stringent than ext2fs_open().
	 */
	features[0] = sb->s_feature_compat & ~EXT2_LIB_FEATURE_COMPAT_SUPP;
	features[1] = sb->s_feature_incompat & ~EXT2_LIB_FEATURE_INCOMPAT_SUPP;
	features[2] = (sb->s_feature_ro_compat &
		       ~EXT2_LIB_FEATURE_RO_COMPAT_SUPP);
print_unsupp_features:
	if (features[0] || features[1] || features[2]) {
		int	i, j;
		__u32	*mask = features, m;

		fprintf(stderr, _("%s has unsupported feature(s):"),
			ctx->filesystem_name);

		for (i=0; i <3; i++,mask++) {
			for (j=0,m=1; j < 32; j++, m<<=1) {
				if (*mask & m)
					fprintf(stderr, " %s",
						e2p_feature2string(i, m));
			}
		}
		putc('\n', stderr);
		goto get_newer;
	}
#ifdef ENABLE_COMPRESSION
	if (sb->s_feature_incompat & EXT2_FEATURE_INCOMPAT_COMPRESSION)
		com_err(ctx->program_name, 0,
			_("Warning: compression support is experimental.\n"));
#endif
#ifndef ENABLE_HTREE
	if (sb->s_feature_compat & EXT2_FEATURE_COMPAT_DIR_INDEX) {
		com_err(ctx->program_name, 0,
			_("E2fsck not compiled with HTREE support,\n\t"
			  "but filesystem %s has HTREE directories.\n"),
			ctx->device_name);
		goto get_newer;
	}
#endif

	/*
	 * If the user specified a specific superblock, presumably the
	 * master superblock has been trashed.  So we mark the
	 * superblock as dirty, so it can be written out.
	 */
	if (ctx->superblock &&
	    !(ctx->options & E2F_OPT_READONLY))
		ext2fs_mark_super_dirty(fs);

	/*
	 * Calculate the number of filesystem blocks per pagesize.  If
	 * fs->blocksize > page_size, set the number of blocks per
	 * pagesize to 1 to avoid division by zero errors.
	 */
#ifdef _SC_PAGESIZE
	sysval = sysconf(_SC_PAGESIZE);
	if (sysval > 0)
		sys_page_size = sysval;
#endif /* _SC_PAGESIZE */
	ctx->blocks_per_page = sys_page_size / fs->blocksize;
	if (ctx->blocks_per_page == 0)
		ctx->blocks_per_page = 1;

	if (ctx->superblock)
		set_latch_flags(PR_LATCH_RELOC, PRL_LATCHED, 0);
	ext2fs_mark_valid(fs);
	check_super_block(ctx);
	if (ctx->flags & E2F_FLAG_SIGNAL_MASK)
		fatal_error(ctx, 0);
	check_if_skip(ctx);
	check_resize_inode(ctx);
	if (bad_blocks_file)
		read_bad_blocks_file(ctx, bad_blocks_file, replace_bad_blocks);
	else if (cflag)
		read_bad_blocks_file(ctx, 0, !keep_bad_blocks); /* Test disk */
	if (ctx->flags & E2F_FLAG_SIGNAL_MASK)
		fatal_error(ctx, 0);

	/*
	 * Mark the system as valid, 'til proven otherwise
	 */
	ext2fs_mark_valid(fs);

	retval = ext2fs_read_bb_inode(fs, &fs->badblocks);
	if (retval) {
		com_err(ctx->program_name, retval,
			_("while reading bad blocks inode"));
		preenhalt(ctx);
		printf(_("This doesn't bode well,"
			 " but we'll try to go on...\n"));
	}

	/*
	 * Save the journal size in megabytes.
	 * Try and use the journal size from the backup else let e2fsck
	 * find the default journal size.
	 */
	if (sb->s_jnl_backup_type == EXT3_JNL_BACKUP_BLOCKS)
		journal_size = sb->s_jnl_blocks[16] >> 20;
	else
Exemple #18
0
int main ()
{
	
	int i = 0;
	int res = 0;
	char *pres = NULL;
	hashtab_node * node = NULL;
	struct test_node *p = NULL;
    hashtab *h = NULL;
    #ifdef MEMORY_TEST
	setenv("MALLOC_TRACE","1.txt",1);
    mtrace();
    #endif

	h = hashtab_create(5,hashtab_hvalue,hashtab_keycmp,hashtab_node_free);
    assert(h!= NULL);
	while(1)
	{
		p = (struct test_node*)malloc(sizeof(struct test_node));
		assert(p != NULL);
		printf("\r\n 请输入key 和value,当可以等于\"quit\"时退出");
        scanf("%s",p->key);
		scanf("%s",p->data);

		if(strcmp(p->key,"quit") == 0)
		{
			free(p);
			break;
		}

        res = hashtab_insert(h,p->key,p->data);
		if (res != 0)
		{
			free(p);
			printf("\r\n key[%s],data[%s] insert failed %d",p->key,p->data,res);
		}
		else
		{
			printf("\r\n key[%s],data[%s] insert success %d",p->key,p->data,res);
		}
	}

	hashtab_dump(h);

	while(1)
	{
		p = (struct test_node*)malloc(sizeof(struct test_node));
		assert(p != NULL);
		printf("\r\n 请输入key 查询value的数值,当可以等于\"quit\"时退出");
        scanf("%s",p->key);

		if(strcmp(p->key,"quit") == 0)
		{
			free(p);
			break;
		}
        pres = hashtab_search(h,p->key);
		if (pres == NULL)
		{
			printf("\r\n key[%s] search data failed",p->key);
		}
		else
		{
			printf("\r\n key[%s],search data[%s] success",p->key,pres);
		}
		free(p);
	}
	hashtab_dump(h);
	while(1)
	{
		p = (struct test_node*)malloc(sizeof(struct test_node));
		assert(p != NULL);
		printf("\r\n 请输入key 删除节点的数值,当可以等于\"quit\"时退出");
        scanf("%s",p->key);

		if(strcmp(p->key,"quit") == 0)
		{
			free(p);
			break;
		}
        node = hashtab_delete(h,p->key);
		if (node == NULL)
		{
			printf("\r\n key[%s] delete node failed ",p->key);
		}
		else
		{
			printf("\r\n key[%s],delete data[%s] success",node->key,node->data);
		    h->hash_node_free(node);
		}
		free(p);
	    hashtab_dump(h);
	}

	hashtab_destory(h);
    #ifdef MEMORY_TEST
    muntrace();
    #endif
	return 0;

}
Exemple #19
0
/**
 * main function - for clone or restore data
 */
int main(int argc, char **argv) {
#ifdef MEMTRACE
	setenv("MALLOC_TRACE", "partclone_mtrace.log", 1);
	mtrace();
#endif
	char*			source;			/// source data
	char*			target;			/// target data
	int			dfr, dfw;		/// file descriptor for source and target
	int			r_size, w_size;		/// read and write size
	unsigned		cs_size = 0;		/// checksum_size
	int			cs_reseed = 1;
	int			start, stop;		/// start, range, stop number for progress bar
	unsigned long *bitmap = NULL;		/// the point for bitmap data
	int			debug = 0;		/// debug level
	int			tui = 0;		/// text user interface
	int			pui = 0;		/// progress mode(default text)
	
	int			flag;
	int			pres = 0;
	pthread_t		prog_thread;
	void			*p_result;

	static const char *const bad_sectors_warning_msg =
		"*************************************************************************\n"
		"* WARNING: The disk has bad sectors. This means physical damage on the  *\n"
		"* disk surface caused by deterioration, manufacturing faults, or        *\n"
		"* another reason. The reliability of the disk may remain stable or      *\n"
		"* degrade quickly. Use the --rescue option to efficiently save as much  *\n"
		"* data as possible!                                                     *\n"
		"*************************************************************************\n";

	file_system_info fs_info;   /// description of the file system
	image_options    img_opt;

	init_fs_info(&fs_info);
	init_image_options(&img_opt);

	/**
	 * get option and assign to opt structure
	 * check parameter and read from argv
	 */
	parse_options(argc, argv, &opt);

	/**
	 * if "-d / --debug" given
	 * open debug file in "/var/log/partclone.log" for log message 
	 */
	memset(&fs_opt, 0, sizeof(fs_cmd_opt));
	debug = opt.debug;
	fs_opt.debug = debug;
	fs_opt.ignore_fschk = opt.ignore_fschk;

	//if(opt.debug)
	open_log(opt.logfile);

	/**
	 * using Text User Interface
	 */
	if (opt.ncurses) {
		pui = NCURSES;
		log_mesg(1, 0, 0, debug, "Using Ncurses User Interface mode.\n");
	} else
		pui = TEXT;

	tui = open_pui(pui, opt.fresh);
	if ((opt.ncurses) && (!tui)) {
		opt.ncurses = 0;
		pui = TEXT;
		log_mesg(1, 0, 0, debug, "Open Ncurses User Interface Error.\n");
	}

	/// print partclone info
	print_partclone_info(opt);

#ifndef CHKIMG
	if (geteuid() != 0)
		log_mesg(0, 1, 1, debug, "You are not logged as root. You may have \"access denied\" errors when working.\n");
	else
		log_mesg(1, 0, 0, debug, "UID is root.\n");
#endif

	/// ignore crc check
	if (opt.ignore_crc)
		log_mesg(1, 0, 1, debug, "Ignore CRC errors\n");

	/**
	 * open source and target
	 * clone mode, source is device and target is image file/stdout
	 * restore mode, source is image file/stdin and target is device
	 * dd mode, source is device and target is device !!not complete
	 */
	source = opt.source;
	target = opt.target;
	log_mesg(1, 0, 0, debug, "source=%s, target=%s \n", source, target);
	dfr = open_source(source, &opt);
	if (dfr == -1) {
		log_mesg(0, 1, 1, debug, "Error exit\n");
	}

#ifndef CHKIMG
	dfw = open_target(target, &opt);
	if (dfw == -1) {
		log_mesg(0, 1, 1, debug, "Error exit\n");
	}
#else
	dfw = -1;
#endif

	/**
	 * get partition information like super block, bitmap from device or image file.
	 */
	if (opt.clone) {

		log_mesg(1, 0, 0, debug, "Initiate image options - version %s\n", IMAGE_VERSION_CURRENT);

		img_opt.checksum_mode = opt.checksum_mode;
		img_opt.checksum_size = get_checksum_size(opt.checksum_mode, opt.debug);
		img_opt.blocks_per_checksum = opt.blocks_per_checksum;
		img_opt.reseed_checksum = opt.reseed_checksum;

		cs_size = img_opt.checksum_size;
		cs_reseed = img_opt.reseed_checksum;

		log_mesg(1, 0, 0, debug, "Initial image hdr - get Super Block from partition\n");
		log_mesg(0, 0, 1, debug, "Reading Super Block\n");

		/// get Super Block information from partition
		read_super_blocks(source, &fs_info);

		if (img_opt.checksum_mode != CSM_NONE && img_opt.blocks_per_checksum == 0) {

			const unsigned int buffer_capacity = opt.buffer_size > fs_info.block_size
				? opt.buffer_size / fs_info.block_size : 1; // in blocks

			img_opt.blocks_per_checksum = buffer_capacity;

		}
		log_mesg(1, 0, 0, debug, "%u blocks per checksum\n", img_opt.blocks_per_checksum);

		check_mem_size(fs_info, img_opt, opt);

		/// alloc a memory to store bitmap
		bitmap = pc_alloc_bitmap(fs_info.totalblock);
		if (bitmap == NULL) {
			log_mesg(0, 1, 1, debug, "%s, %i, not enough memory\n", __func__, __LINE__);
		}

		log_mesg(2, 0, 0, debug, "initial main bitmap pointer %p\n", bitmap);
		log_mesg(1, 0, 0, debug, "Initial image hdr - read bitmap table\n");

		/// read and check bitmap from partition
		log_mesg(0, 0, 1, debug, "Calculating bitmap... Please wait... \n");
		read_bitmap(source, fs_info, bitmap, pui);
		update_used_blocks_count(&fs_info, bitmap);

		if (opt.check) {

			unsigned long long needed_space = 0;

			needed_space += sizeof(image_head) + sizeof(file_system_info) + sizeof(image_options);
			needed_space += get_bitmap_size_on_disk(&fs_info, &img_opt, &opt);
			needed_space += cnv_blocks_to_bytes(0, fs_info.usedblocks, fs_info.block_size, &img_opt);

			check_free_space(&dfw, needed_space);
		}

		log_mesg(2, 0, 0, debug, "check main bitmap pointer %p\n", bitmap);
		log_mesg(1, 0, 0, debug, "Writing super block and bitmap...\n");

		write_image_desc(&dfw, fs_info, img_opt, &opt);
		write_image_bitmap(&dfw, fs_info, img_opt, bitmap, &opt);

		log_mesg(0, 0, 1, debug, "done!\n");

	} else if (opt.restore) {

		image_head_v2 img_head;

		log_mesg(1, 0, 0, debug, "restore image hdr - get information from image file\n");
		log_mesg(1, 0, 1, debug, "Reading Super Block\n");

		/// get image information from image file
		load_image_desc(&dfr, &opt, &img_head, &fs_info, &img_opt);
		cs_size = img_opt.checksum_size;
		cs_reseed = img_opt.reseed_checksum;

		check_mem_size(fs_info, img_opt, opt);

		/// alloc a memory to restore bitmap
		bitmap = pc_alloc_bitmap(fs_info.totalblock);
		if (bitmap == NULL) {
			log_mesg(0, 1, 1, debug, "%s, %i, not enough memory\n", __func__, __LINE__);
		}

		log_mesg(2, 0, 0, debug, "initial main bitmap pointer %p\n", bitmap);
		log_mesg(1, 0, 0, debug, "Initial image hdr - read bitmap table\n");

		/// read and check bitmap from image file
		log_mesg(0, 0, 1, debug, "Calculating bitmap... Please wait...\n");
		load_image_bitmap(&dfr, opt, fs_info, img_opt, bitmap);

#ifndef CHKIMG
		/// check the dest partition size.
		if (opt.restore_raw_file)
			check_free_space(&dfw, fs_info.device_size);
		else if (opt.check)
			check_size(&dfw, fs_info.device_size);
#endif

		log_mesg(2, 0, 0, debug, "check main bitmap pointer %p\n", bitmap);
		log_mesg(0, 0, 1, debug, "done!\n");

	} else if (opt.dd || opt.domain) {

		log_mesg(1, 0, 0, debug, "Initiate image options - version %s\n", IMAGE_VERSION_CURRENT);
		img_opt.checksum_mode = opt.checksum_mode;
		img_opt.checksum_size = get_checksum_size(opt.checksum_mode, opt.debug);
		img_opt.blocks_per_checksum = opt.blocks_per_checksum;
		img_opt.reseed_checksum = opt.reseed_checksum;
		log_mesg(1, 0, 0, debug, "Initial image hdr - get Super Block from partition\n");
		log_mesg(1, 0, 1, debug, "Reading Super Block\n");

		/// get Super Block information from partition
		read_super_blocks(source, &fs_info);

		check_mem_size(fs_info, img_opt, opt);

		/// alloc a memory to restore bitmap
		bitmap = pc_alloc_bitmap(fs_info.totalblock);
		if (bitmap == NULL) {
			log_mesg(0, 1, 1, debug, "%s, %i, not enough memory\n", __func__, __LINE__);
		}

		log_mesg(2, 0, 0, debug, "initial main bitmap pointer %p\n", bitmap);
		log_mesg(1, 0, 0, debug, "Initial image hdr - read bitmap table\n");

		/// read and check bitmap from partition
		log_mesg(0, 0, 1, debug, "Calculating bitmap... Please wait... ");
		read_bitmap(source, fs_info, bitmap, pui);

		/// check the dest partition size.
		if (opt.dd && opt.check) {
			check_size(&dfw, fs_info.device_size);
		}

		log_mesg(2, 0, 0, debug, "check main bitmap pointer %p\n", bitmap);
		log_mesg(0, 0, 1, debug, "done!\n");
	} else if (opt.ddd){

		if (dfr != 0)
		    read_super_blocks(source, &fs_info);
		else
		    read_super_blocks(target, &fs_info);

		img_opt.checksum_mode = opt.checksum_mode;
		img_opt.checksum_size = get_checksum_size(opt.checksum_mode, opt.debug);
		img_opt.blocks_per_checksum = opt.blocks_per_checksum;
		check_mem_size(fs_info, img_opt, opt);

		/// alloc a memory to restore bitmap
		bitmap = pc_alloc_bitmap(fs_info.totalblock);
		if (bitmap == NULL) {
			log_mesg(0, 1, 1, debug, "%s, %i, not enough memory\n", __func__, __LINE__);
		}

		log_mesg(2, 0, 0, debug, "initial main bitmap pointer %p\n", bitmap);
		log_mesg(1, 0, 0, debug, "Initial image hdr - read bitmap table\n");

		/// read and check bitmap from partition
		log_mesg(0, 0, 1, debug, "Calculating bitmap... Please wait... ");
		read_bitmap(source, fs_info, bitmap, pui);

		/// check the dest partition size.
		if (opt.check) {

		    struct stat target_stat;
		    if ((stat(opt.target, &target_stat) != -1) && (strcmp(opt.target, "-") != 0)) {
			if (S_ISBLK(target_stat.st_mode)) 
			    check_size(&dfw, fs_info.device_size);
			else {
			    unsigned long long needed_space = 0;

			    needed_space += sizeof(image_head) + sizeof(file_system_info) + sizeof(image_options);
			    needed_space += get_bitmap_size_on_disk(&fs_info, &img_opt, &opt);
			    needed_space += cnv_blocks_to_bytes(0, fs_info.usedblocks, fs_info.block_size, &img_opt);

			    check_free_space(&dfw, needed_space);
			}
		    }
		}

		log_mesg(2, 0, 0, debug, "check main bitmap pointer %p\n", bitmap);
		log_mesg(0, 0, 1, debug, "done!\n");
    
	}

	log_mesg(1, 0, 0, debug, "print image information\n");

	/// print option to log file
	if (debug)
		print_opt(opt);

	print_file_system_info(fs_info, opt);

	/**
	 * initial progress bar
	 */
	start = 0;				/// start number of progress bar
	stop = (fs_info.usedblocks);		/// get the end of progress number, only used block
	log_mesg(1, 0, 0, debug, "Initial Progress bar\n");
	/// Initial progress bar
	if (opt.no_block_detail)
		flag = NO_BLOCK_DETAIL;
	else
		flag = IO;
	progress_init(&prog, start, stop, fs_info.totalblock, flag, fs_info.block_size);
	copied = 0;				/// initial number is 0

	/**
	 * thread to print progress
	 */
	pres = pthread_create(&prog_thread, NULL, thread_update_pui, NULL);
	if(pres)
	    log_mesg(0, 1, 1, debug, "%s, %i, thread create error\n", __func__, __LINE__);


	/**
	 * start read and write data between source and destination
	 */
	if (opt.clone) {

		const unsigned long long blocks_total = fs_info.totalblock;
		const unsigned int block_size = fs_info.block_size;
		const unsigned int buffer_capacity = opt.buffer_size > block_size ? opt.buffer_size / block_size : 1; // in blocks
		unsigned char checksum[cs_size];
		unsigned int blocks_in_cs, blocks_per_cs, write_size;
		char *read_buffer, *write_buffer;

		blocks_per_cs = img_opt.blocks_per_checksum;

		log_mesg(1, 0, 0, debug, "#\nBuffer capacity = %u, Blocks per cs = %u\n#\n", buffer_capacity, blocks_per_cs);

		write_size = cnv_blocks_to_bytes(0, buffer_capacity, block_size, &img_opt);

		read_buffer = (char*)malloc(buffer_capacity * block_size);
		write_buffer = (char*)malloc(write_size + cs_size);

		if (read_buffer == NULL || write_buffer == NULL) {
			log_mesg(0, 1, 1, debug, "%s, %i, not enough memory\n", __func__, __LINE__);
		}

		/// read data from the first block
		if (lseek(dfr, 0, SEEK_SET) == (off_t)-1)
			log_mesg(0, 1, 1, debug, "source seek ERROR:%s\n", strerror(errno));

		log_mesg(0, 0, 0, debug, "Total block %llu\n", blocks_total);

		/// start clone partition to image file
		log_mesg(1, 0, 0, debug, "start backup data...\n");

		blocks_in_cs = 0;
		init_checksum(img_opt.checksum_mode, checksum, debug);

		block_id = 0;
		do {
			/// scan bitmap
			unsigned long long i, blocks_skip, blocks_read;
			unsigned int cs_added = 0, write_offset = 0;
			off_t offset;

			/// skip unused blocks
			for (blocks_skip = 0;
			     block_id + blocks_skip < blocks_total &&
			     !pc_test_bit(block_id + blocks_skip, bitmap);
			     blocks_skip++);
			if (block_id + blocks_skip == blocks_total)
				break;

			if (blocks_skip)
				block_id += blocks_skip;

			/// read blocks
			for (blocks_read = 0;
			     block_id + blocks_read < blocks_total && blocks_read < buffer_capacity &&
			     pc_test_bit(block_id + blocks_read, bitmap);
			     ++blocks_read);
			if (!blocks_read)
				break;

			offset = (off_t)(block_id * block_size);
			if (lseek(dfr, offset, SEEK_SET) == (off_t)-1)
				log_mesg(0, 1, 1, debug, "source seek ERROR:%s\n", strerror(errno));

			r_size = read_all(&dfr, read_buffer, blocks_read * block_size, &opt);
			if (r_size != (int)(blocks_read * block_size)) {
				if ((r_size == -1) && (errno == EIO)) {
					if (opt.rescue) {
						memset(read_buffer, 0, blocks_read * block_size);
						for (r_size = 0; r_size < blocks_read * block_size; r_size += PART_SECTOR_SIZE)
							rescue_sector(&dfr, offset + r_size, read_buffer + r_size, &opt);
					} else
						log_mesg(0, 1, 1, debug, "%s", bad_sectors_warning_msg);
				} else
					log_mesg(0, 1, 1, debug, "read error: %s\n", strerror(errno));
			}

			/// calculate checksum
			log_mesg(2, 0, 0, debug, "blocks_read = %i\n", blocks_read);
			for (i = 0; i < blocks_read; ++i) {

				memcpy(write_buffer + write_offset,
					read_buffer + i * block_size, block_size);

				write_offset += block_size;

				update_checksum(checksum, read_buffer + i * block_size, block_size);

				if (blocks_per_cs > 0 && ++blocks_in_cs == blocks_per_cs) {
				    log_mesg(3, 0, 0, debug, "CRC = %x%x%x%x \n", checksum[0], checksum[1], checksum[2], checksum[3]);

					memcpy(write_buffer + write_offset, checksum, cs_size);

					++cs_added;
					write_offset += cs_size;

					blocks_in_cs = 0;
					if (cs_reseed)
						init_checksum(img_opt.checksum_mode, checksum, debug);
				}
			}

			/// write buffer to target
			w_size = write_all(&dfw, write_buffer, write_offset, &opt);
			if (w_size != write_offset)
				log_mesg(0, 1, 1, debug, "image write ERROR:%s\n", strerror(errno));

			/// count copied block
			copied += blocks_read;
			log_mesg(2, 0, 0, debug, "copied = %lld\n", copied);

			/// next block
			block_id += blocks_read;

			/// read or write error
			if (r_size + cs_added * cs_size != w_size)
				log_mesg(0, 1, 1, debug, "read(%i) and write(%i) different\n", r_size, w_size);

		} while (1);

		if (blocks_in_cs > 0) {

			// Write the checksum for the latest blocks
			log_mesg(1, 0, 0, debug, "Write the checksum for the latest blocks. size = %i\n", cs_size);
			log_mesg(3, 0, 0, debug, "CRC = %x%x%x%x \n", checksum[0], checksum[1], checksum[2], checksum[3]);
			w_size = write_all(&dfw, (char*)checksum, cs_size, &opt);
			if (w_size != cs_size)
				log_mesg(0, 1, 1, debug, "image write ERROR:%s\n", strerror(errno));
		}

		free(write_buffer);
		free(read_buffer);

	// check only the size when the image does not contains checksums and does not
	// comes from a pipe
	} else if (opt.chkimg && img_opt.checksum_mode == CSM_NONE
		&& strcmp(opt.source, "-") != 0) {

		unsigned long long total_offset = (fs_info.usedblocks - 1) * fs_info.block_size;
		char last_block[fs_info.block_size];
		off_t partial_offset = INT32_MAX;

		while (total_offset) {

			if (partial_offset > total_offset)
				partial_offset = total_offset;

			if (lseek(dfr, partial_offset, SEEK_CUR) == (off_t)-1)
				log_mesg(0, 1, 1, debug, "source seek ERROR: %s\n", strerror(errno));

			total_offset -= partial_offset;
		}

		if (read_all(&dfr, last_block, fs_info.block_size, &opt) != fs_info.block_size)
			log_mesg(0, 1, 1, debug, "ERROR: source image too short\n");

	} else if (opt.restore) {

		const unsigned long long blocks_total = fs_info.totalblock;
		const unsigned int block_size = fs_info.block_size;
		const unsigned int buffer_capacity = opt.buffer_size > block_size ? opt.buffer_size / block_size : 1; // in blocks
		const unsigned int blocks_per_cs = img_opt.blocks_per_checksum;
		unsigned long long blocks_used = fs_info.usedblocks;
		unsigned int blocks_in_cs, buffer_size, read_offset;
		unsigned char checksum[cs_size];
		char *read_buffer, *write_buffer;
		unsigned long long blocks_used_fix = 0, test_block = 0;

		log_mesg(1, 0, 0, debug, "#\nBuffer capacity = %u, Blocks per cs = %u\n#\n", buffer_capacity, blocks_per_cs);

		// fix some super block record incorrect
		for (test_block = 0; test_block < blocks_total; ++test_block)
			if (pc_test_bit(test_block, bitmap))
				blocks_used_fix++;

		if (blocks_used_fix != blocks_used) {
			blocks_used = blocks_used_fix;
			log_mesg(1, 0, 0, debug, "info: fixed used blocks count\n");
		}
		buffer_size = cnv_blocks_to_bytes(0, buffer_capacity, block_size, &img_opt);

		if (img_opt.image_version != 0x0001)
			read_buffer = (char*)malloc(buffer_size);
		else {
			// Allocate more memory in case the image is affected by the 64 bits bug
			read_buffer = (char*)malloc(buffer_size + buffer_capacity * cs_size);
		}
		write_buffer = (char*)malloc(buffer_capacity * block_size);
		if (read_buffer == NULL || write_buffer == NULL) {
			log_mesg(0, 1, 1, debug, "%s, %i, not enough memory\n", __func__, __LINE__);
		}

#ifndef CHKIMG
		/// seek to the first
		if (lseek(dfw, opt.offset, SEEK_SET) == (off_t)-1)
			log_mesg(0, 1, 1, debug, "target seek ERROR:%s\n", strerror(errno));
#endif

		/// start restore image file to partition
		log_mesg(1, 0, 0, debug, "start restore data...\n");

		blocks_in_cs = 0;
		if (!opt.ignore_crc)
			init_checksum(img_opt.checksum_mode, checksum, debug);

		block_id = 0;
		do {
			unsigned int i;
			unsigned long long blocks_written, bytes_skip;
			unsigned int read_size;
			// max chunk to read using one read(2) syscall
			int blocks_read = copied + buffer_capacity < blocks_used ?
				buffer_capacity : blocks_used - copied;
			if (!blocks_read)
				break;

			log_mesg(1, 0, 0, debug, "blocks_read = %d and copied = %lld\n", blocks_read, copied);
			read_size = cnv_blocks_to_bytes(copied, blocks_read, block_size, &img_opt);

			// increase read_size to make room for the oversized checksum
			if (blocks_per_cs && blocks_read < buffer_capacity &&
					(blocks_read % blocks_per_cs) && (blocks_used % blocks_per_cs)) {
				/// it is the last read and there is a partial chunk at the end
				log_mesg(1, 0, 0, debug, "# PARTIAL CHUNK\n");
				read_size += cs_size;
			}

			// read chunk from image
			log_mesg(1, 0, 0, debug, "read more: ");

			r_size = read_all(&dfr, read_buffer, read_size, &opt);
			if (r_size != read_size)
				log_mesg(0, 1, 1, debug, "read ERROR:%s\n", strerror(errno));

			// read buffer is the follows:
			// <blocks_per_cs><cs1><blocks_per_cs><cs2>...

			// write buffer should be the following:
			// <block1><block2>...

			read_offset = 0;
			for (i = 0; i < blocks_read; ++i) {

				memcpy(write_buffer + i * block_size,
					read_buffer + read_offset, block_size);

				if (opt.ignore_crc) {
					read_offset += block_size;
					if (++blocks_in_cs == blocks_per_cs)
						read_offset += cs_size;
					continue;
				}

				update_checksum(checksum, read_buffer + read_offset, block_size);

				if (++blocks_in_cs == blocks_per_cs) {

				    unsigned char checksum_orig[cs_size];
				    memcpy(checksum_orig, read_buffer + read_offset + block_size, cs_size);
				    log_mesg(3, 0, 0, debug, "CRC = %x%x%x%x \n", checksum[0], checksum[1], checksum[2], checksum[3]);
				    log_mesg(3, 0, 0, debug, "CRC.orig = %x%x%x%x \n", checksum_orig[0], checksum_orig[1], checksum_orig[2], checksum_orig[3]);
					if (memcmp(read_buffer + read_offset + block_size, checksum, cs_size)) {
					    log_mesg(0, 1, 1, debug, "CRC error, block_id=%llu...\n ", block_id + i);
					}

					read_offset += cs_size;

					blocks_in_cs = 0;
					if (cs_reseed)
						init_checksum(img_opt.checksum_mode, checksum, debug);
				}

				read_offset += block_size;
			}
			if (blocks_in_cs && blocks_per_cs && blocks_read < buffer_capacity &&
					(blocks_read % blocks_per_cs)) {

			    log_mesg(1, 0, 0, debug, "check latest chunk's checksum covering %u blocks\n", blocks_in_cs);
			    if (memcmp(read_buffer + read_offset, checksum, cs_size)){
				unsigned char checksum_orig[cs_size];
				memcpy(checksum_orig, read_buffer + read_offset, cs_size);
				log_mesg(1, 0, 0, debug, "CRC = %x%x%x%x \n", checksum[0], checksum[1], checksum[2], checksum[3]);
				log_mesg(1, 0, 0, debug, "CRC.orig = %x%x%x%x \n", checksum_orig[0], checksum_orig[1], checksum_orig[2], checksum_orig[3]);
				log_mesg(0, 1, 1, debug, "CRC error, block_id=%llu...\n ", block_id + i);
			    }

			}


			blocks_written = 0;
			do {
				int blocks_write;

				/// count bytes to skip
				for (bytes_skip = 0;
				     block_id < blocks_total &&
				     !pc_test_bit(block_id, bitmap);
				     block_id++, bytes_skip += block_size);

#ifndef CHKIMG
				/// skip empty blocks
				if (bytes_skip > 0 && lseek(dfw, (off_t)bytes_skip, SEEK_CUR) == (off_t)-1)
					log_mesg(0, 1, 1, debug, "target seek ERROR:%s\n", strerror(errno));
#endif

				/// blocks to write
				for (blocks_write = 0;
				     block_id + blocks_write < blocks_total &&
				     blocks_written + blocks_write < blocks_read &&
				     pc_test_bit(block_id + blocks_write, bitmap);
				     blocks_write++);

#ifndef CHKIMG
				// write blocks
				if (blocks_write > 0) {
					w_size = write_all(&dfw, write_buffer + blocks_written * block_size,
						blocks_write * block_size, &opt);
					if (w_size != blocks_write * block_size) {
						if (!opt.skip_write_error)
							log_mesg(0, 1, 1, debug, "write block %llu ERROR:%s\n", block_id + blocks_written, strerror(errno));
						else
							log_mesg(0, 0, 1, debug, "skip write block %llu error:%s\n", block_id + blocks_written, strerror(errno));
					}
				}
#endif

				blocks_written += blocks_write;
				block_id += blocks_write;
				copied += blocks_write;
			} while (blocks_written < blocks_read);

		} while(1);
		free(write_buffer);
		free(read_buffer);

#ifndef CHKIMG
		/// restore_raw_file option
		if (opt.restore_raw_file && !pc_test_bit(blocks_total - 1, bitmap)) {
			if (ftruncate(dfw, (off_t)(blocks_total * block_size)) == -1)
				log_mesg(0, 0, 1, debug, "ftruncate ERROR:%s\n", strerror(errno));
		}
#endif

	} else if (opt.dd) {

		char *buffer;
		int block_size = fs_info.block_size;
		unsigned long long blocks_total = fs_info.totalblock;
		int buffer_capacity = block_size < opt.buffer_size ? opt.buffer_size / block_size : 1;

		buffer = (char*)malloc(buffer_capacity * block_size);
		if (buffer == NULL) {
			log_mesg(0, 1, 1, debug, "%s, %i, not enough memory\n", __func__, __LINE__);
		}

		block_id = 0;

		if (lseek(dfr, 0, SEEK_SET) == (off_t)-1)
			log_mesg(0, 1, 1, debug, "source seek ERROR:%d\n", strerror(errno));

		log_mesg(0, 0, 0, debug, "Total block %llu\n", blocks_total);

		/// start clone partition to partition
		log_mesg(1, 0, 0, debug, "start backup data device-to-device...\n");
		do {
			/// scan bitmap
			unsigned long long blocks_skip, blocks_read;
			off_t offset;

			/// skip unused blocks
			for (blocks_skip = 0;
			     block_id + blocks_skip < blocks_total &&
			     !pc_test_bit(block_id + blocks_skip, bitmap);
			     blocks_skip++);

			if (block_id + blocks_skip == blocks_total)
				break;

			if (blocks_skip)
				block_id += blocks_skip;

			/// read chunk from source
			for (blocks_read = 0;
			     block_id + blocks_read < blocks_total && blocks_read < buffer_capacity &&
			     pc_test_bit(block_id + blocks_read, bitmap);
			     ++blocks_read);

			if (!blocks_read)
				break;

			offset = (off_t)(block_id * block_size);
			if (lseek(dfr, offset, SEEK_SET) == (off_t)-1)
				log_mesg(0, 1, 1, debug, "source seek ERROR:%s\n", strerror(errno));
			if (lseek(dfw, offset + opt.offset, SEEK_SET) == (off_t)-1)
				log_mesg(0, 1, 1, debug, "target seek ERROR:%s\n", strerror(errno));

			r_size = read_all(&dfr, buffer, blocks_read * block_size, &opt);
			if (r_size != (int)(blocks_read * block_size)) {
				if ((r_size == -1) && (errno == EIO)) {
					if (opt.rescue) {
						memset(buffer, 0, blocks_read * block_size);
						for (r_size = 0; r_size < blocks_read * block_size; r_size += PART_SECTOR_SIZE)
							rescue_sector(&dfr, offset + r_size, buffer + r_size, &opt);
					} else
						log_mesg(0, 1, 1, debug, "%s", bad_sectors_warning_msg);
				} else
					log_mesg(0, 1, 1, debug, "source read ERROR %s\n", strerror(errno));
			}

			/// write buffer to target
			w_size = write_all(&dfw, buffer, blocks_read * block_size, &opt);
			if (w_size != (int)(blocks_read * block_size)) {
				if (opt.skip_write_error)
					log_mesg(0, 0, 1, debug, "skip write block %lli error:%s\n", block_id, strerror(errno));
				else
					log_mesg(0, 1, 1, debug, "write block %lli ERROR:%s\n", block_id, strerror(errno));
			}

			/// count copied block
			copied += blocks_read;

			/// next block
			block_id += blocks_read;

			/// read or write error
			if (r_size != w_size) {
				if (opt.skip_write_error)
					log_mesg(0, 0, 1, debug, "read and write different\n");
				else
					log_mesg(0, 1, 1, debug, "read and write different\n");
			}
		} while (1);

		free(buffer);

		/// restore_raw_file option
		if (opt.restore_raw_file && !pc_test_bit(blocks_total - 1, bitmap)) {
			if (ftruncate(dfw, (off_t)(blocks_total * block_size)) == -1)
				log_mesg(0, 0, 1, debug, "ftruncate ERROR:%s\n", strerror(errno));
		}

	} else if (opt.domain) {

		int cmp, nx_current = 0;
		unsigned long long next_block_id = 0;
		log_mesg(0, 0, 0, debug, "Total block %i\n", fs_info.totalblock);
		log_mesg(1, 0, 0, debug, "start writing domain log...\n");
		// write domain log comment and status line
		dprintf(dfw, "# Domain logfile created by %s v%s\n", get_exec_name(), VERSION);
		dprintf(dfw, "# Source: %s\n", opt.source);
		dprintf(dfw, "# Offset: 0x%08llX\n", opt.offset_domain);
		dprintf(dfw, "# current_pos  current_status\n");
		dprintf(dfw, "0x%08llX     ?\n", opt.offset_domain + (fs_info.totalblock * fs_info.block_size));
		dprintf(dfw, "#      pos        size  status\n");
		// start logging the used/unused areas
		cmp = pc_test_bit(0, bitmap);
		for (block_id = 0; block_id <= fs_info.totalblock; block_id++) {
			if (block_id < fs_info.totalblock) {
				nx_current = pc_test_bit(block_id, bitmap);
				if (nx_current)
					copied++;
			} else
				nx_current = -1;
			if (nx_current != cmp) {
				dprintf(dfw, "0x%08llX  0x%08llX  %c\n",
					opt.offset_domain + (next_block_id * fs_info.block_size),
					(block_id - next_block_id) * fs_info.block_size,
					cmp ? '+' : '?');
				next_block_id = block_id;
				cmp = nx_current;
			}
			// don't bother updating progress
		} /// end of for
	} else if (opt.ddd) {

		char *buffer;
		int block_size = fs_info.block_size;
		unsigned long long blocks_total = fs_info.totalblock;
		int blocks_in_buffer = block_size < opt.buffer_size ? opt.buffer_size / block_size : 1;

		buffer = (char*)malloc(blocks_in_buffer * block_size);
		if (buffer == NULL) {
			log_mesg(0, 1, 1, debug, "%s, %i, not enough memory\n", __func__, __LINE__);
		}

		block_id = 0;


		log_mesg(0, 0, 0, debug, "Total block %llu\n", blocks_total);

		/// start clone partition to partition
		log_mesg(1, 0, 0, debug, "start backup data device-to-device...\n");
		do {
			/// scan bitmap
			unsigned long long blocks_read;

			/// read chunk from source
			for (blocks_read = 0;
			     block_id + blocks_read < blocks_total && blocks_read < blocks_in_buffer &&
			     pc_test_bit(block_id + blocks_read, bitmap);
			     blocks_read++);

			if (!blocks_read)
				break;

			r_size = read_all(&dfr, buffer, blocks_read * block_size, &opt);
			if (r_size != (int)(blocks_read * block_size)) {
				if ((r_size == -1) && (errno == EIO)) {
					if (opt.rescue) {
						memset(buffer, 0, blocks_read * block_size);
						for (r_size = 0; r_size < blocks_read * block_size; r_size += PART_SECTOR_SIZE)
							rescue_sector(&dfr, r_size, buffer + r_size, &opt);
					} else
						log_mesg(0, 1, 1, debug, "%s", bad_sectors_warning_msg);
				} else if (r_size == 0){ // done for ddd
				    /// write buffer to target
				    w_size = write_all(&dfw, buffer, rescue_write_size, &opt);
				    break;
				} else
					log_mesg(0, 1, 1, debug, "source read ERROR %s\n", strerror(errno));
			}

			/// write buffer to target
			w_size = write_all(&dfw, buffer, blocks_read * block_size, &opt);
			if (w_size != (int)(blocks_read * block_size)) {
				if (opt.skip_write_error)
					log_mesg(0, 0, 1, debug, "skip write block %lli error:%s\n", block_id, strerror(errno));
				else
					log_mesg(0, 1, 1, debug, "write block %lli ERROR:%s\n", block_id, strerror(errno));
			}

			/// count copied block
			copied += blocks_read;

			/// next block
			block_id += blocks_read;

			/// read or write error
			if (r_size != w_size) {
				if (opt.skip_write_error)
					log_mesg(0, 0, 1, debug, "read and write different\n");
				else
					log_mesg(0, 1, 1, debug, "read and write different\n");
			}
		} while (1);

		free(buffer);

		/// restore_raw_file option
		if (opt.restore_raw_file && !pc_test_bit(blocks_total - 1, bitmap)) {
			if (ftruncate(dfw, (off_t)(blocks_total * block_size)) == -1)
				log_mesg(0, 0, 1, debug, "ftruncate ERROR:%s\n", strerror(errno));
		}



	}

	done = 1;
	pres = pthread_join(prog_thread, &p_result);
	if(pres)
	    log_mesg(0, 1, 1, debug, "%s, %i, thread join error\n", __func__, __LINE__);
	update_pui(&prog, copied, block_id, done);
#ifndef CHKIMG
	sync_data(dfw, &opt);
#endif
	print_finish_info(opt);

	/// close source
	close(dfr);
	/// close target
	if (dfw != -1)
		close(dfw);
	/// free bitmp
	free(bitmap);
	close_pui(pui);
#ifndef CHKIMG
	fprintf(stderr, "Cloned successfully.\n");
#else
	printf("Checked successfully.\n");
#endif
	if (opt.debug)
		close_log();
#ifdef MEMTRACE
	muntrace();
#endif
	return 0;      /// finish
}
int main() {
  MUT_CLASS(interval)* o1,*o2, *o3;
  MUT_CLASS(intervalSum)* s1,*s2,*s3;
  char * c1,*c2,*c3;

#ifdef HAVE_MCHECK_H
  mtrace();
#endif
  fprintf(stderr,"o1\n");
  o1=MUT_NEW(interval);
  assert(o1);
  fprintf(stderr,"o1->copy_name\n");
  MUTABOR_CLASS_FUNCTION(interval,copy_name) (o1, "id1");
  fprintf(stderr,"o1->set_factor\n");
  MUTABOR_CLASS_FUNCTION(interval,set_factor) (o1, 3.0);
  fprintf(stderr,"o2\n");
  o2 = MUT_NEW(intervalStretch);
  assert(o2);
  fprintf(stderr,"o2->copy_name\n");
  MUTABOR_CLASS_FUNCTION(identifier,copy_name)(o2,"Id2");
  fprintf(stderr,"o2->setstretch\n");
  MUTABOR_CLASS_FUNCTION(intervalStretch,setstretch)(o2,2.9);
  MUTABOR_CLASS_FUNCTION(intervalStretch,setright)(o2,o1);
  fprintf(stderr,"o3\n");
  o3 = MUT_NEW(intervalStretch);
  assert(o3);
  fprintf(stderr,"o3->copy_name\n");
  MUTABOR_CLASS_FUNCTION(identifier,copy_name)(o3,"Id2");
  fprintf(stderr,"o3->setright\n");
  MUTABOR_CLASS_FUNCTION(intervalStretch,setright)(o3,o2);
  printf("%s\n%s\n%s\n",c1=MUT_VIRTCALL(identifier,o1,tostring)(o1),
	 c2=MUT_VIRTCALL(object,o2,tostring)(o2),
	 c3=MUT_VIRTCALL(object,o3,tostring)(o3));
  free(c1);free(c2);free(c3);
  fprintf(stderr,"Compare: %d\n",(*(MUT_VIRTTABLE(object)**) o1)->compare(o1,o2));

  s1 = MUT_NEW(intervalSum);
  MUTABOR_CLASS_FUNCTION(identifier,copy_name)(s1,"Summe 1");
  printf("%s\n",c1=MUT_VIRTCALL(identifier,s1,tostring)(s1));
  free(c1);
  MUTABOR_CLASS_FUNCTION(intervalSum,setleft)(s1,o1);
  MUTABOR_CLASS_FUNCTION(intervalSum,setright)(s1,o2);
  printf("%s\n",c1=MUT_VIRTCALL(identifier,s1,tostring)(s1));
  free(c1);
  
  s2 = MUT_NEW(intervalSum);
  MUTABOR_CLASS_FUNCTION (identifier, copy_name) (s2, "Summe 2");
  printf ("%s\n",c1=MUT_VIRTCALL(identifier, s2, tostring) (s2));
  free(c1);
  MUTABOR_CLASS_FUNCTION (intervalSum, setleft) (s2, s1);
  MUTABOR_CLASS_FUNCTION (intervalSum, setright) (s2, o2);
  printf ("%s\n",c1= MUT_VIRTCALL (identifier, s2, tostring) (s2));
  free(c1);
  
  s3=MUT_NEW(intervalDiff);
  MUTABOR_CLASS_FUNCTION(identifier,copy_name)(s3,"Differenz");
  printf("%s\n",c1=MUT_VIRTCALL(identifier,s3,tostring)(s3));
  free(c1);
  MUTABOR_CLASS_FUNCTION(intervalSum,setright)(s3,s1);
  MUTABOR_CLASS_FUNCTION(intervalSum,setleft)(s3,s2);
  printf("%s\n",c1=MUT_VIRTCALL(identifier,s3,tostring)(s3));
  free(c1);
  


  fprintf(stderr,"Deleting s1...\n");
  mutabor_delete(s1);
  fprintf(stderr,"Deleting s2...\n");
  mutabor_delete(s2);
  fprintf(stderr,"Deleting s3...\n");
  mutabor_delete(s3);
  fprintf(stderr,"Deleting o1...\n");
  mutabor_delete(o1);
  fprintf(stderr,"Deleting o2...\n");
  mutabor_delete(o2);
#ifdef HAVE_MCHECK_H
  muntrace();
#endif
  return 0;
}
Exemple #21
0
int
main (int argc, char **argv)
{
  int ret = 0, n;
  char *line = NULL;
  size_t line_len = 0;
  ssize_t len;
  FILE *f;
  char *pattern, *string;
  int flags = REG_EXTENDED;
  int eflags = 0;
  regex_t re;
  regmatch_t rm[20];

  mtrace ();

  if (argc < 2)
    {
      fprintf (stderr, "Missing test filename\n");
      return 1;
    }

  f = fopen (argv[1], "r");
  if (f == NULL)
    {
      fprintf (stderr, "Couldn't open %s\n", argv[1]);
      return 1;
    }

  while ((len = getline (&line, &line_len, f)) > 0)
    {
      char *p, *q;
      int i;

      if (line[len - 1] == '\n')
	line[--len] = '\0';

      puts (line);

      if (line[0] == ';')
	continue;

      if (line[0] == '\0')
	continue;

      if (line[0] == '-')
	{
	  if (strstr (line, "REG_BASIC"))
	    flags = 0;
	  else
	    flags = REG_EXTENDED;
	  if (strstr (line, "REG_ICASE"))
	    flags |= REG_ICASE;
	  if (strstr (line, "REG_NEWLINE"))
	    flags |= REG_NEWLINE;
	  eflags = 0;
	  if (strstr (line, "REG_NOTBOL"))
	    eflags |= REG_NOTBOL;
	  if (strstr (line, "REG_NOTEOL"))
	    eflags |= REG_NOTEOL;
	  continue;
	}

      pattern = line + strspn (line, " \t");
      if (*pattern == '\0')
	continue;
      p = pattern + strcspn (pattern, " \t");
      if (*p == '\0')
	continue;
      *p++ = '\0';

      string = p + strspn (p, " \t");
      if (*string == '\0')
	continue;
      if (*string == '"')
	{
	  string++;
	  p = strchr (string, '"');
	  if (p == NULL)
	    continue;
	  *p++ = '\0';
	}
      else
	{
	  p = string + strcspn (string, " \t");
	  if (*string == '!')
	    string = NULL;
	  else if (*p == '\0')
	    continue;
	  else
	    *p++ = '\0';
	}

      frob_escapes (pattern, 1);
      if (string != NULL)
	frob_escapes (string, 0);

      n = regcomp (&re, pattern, flags);
      if (n != 0)
	{
	  if (string != NULL)
	    {
	      char buf[500];
	      regerror (n, &re, buf, sizeof (buf));
	      printf ("FAIL regcomp unexpectedly failed: %s\n",
		      buf);
	      ret = 1;
	    }
	  continue;
	}
      else if (string == NULL)
	{
	  regfree (&re);
	  puts ("FAIL regcomp unpexpectedly succeeded");
	  ret = 1;
	  continue;
	}

      if (regexec (&re, string, 20, rm, eflags))
	{
	  for (i = 0; i < 20; ++i)
	    {
	      rm[i].rm_so = -1;
	      rm[i].rm_eo = -1;
	    }
	}

      regfree (&re);

      for (i = 0; i < 20 && *p != '\0'; ++i)
	{
	  int rm_so, rm_eo;

	  rm_so = strtol (p, &q, 10);
	  if (p == q)
	    break;
	  p = q;

	  rm_eo = strtol (p, &q, 10);
	  if (p == q)
	    break;
	  p = q;

	  if (rm[i].rm_so != rm_so || rm[i].rm_eo != rm_eo)
	    {
	      printf ("FAIL rm[%d] %d..%d != expected %d..%d\n",
		      i, rm[i].rm_so, rm[i].rm_eo, rm_so, rm_eo);
	      ret = 1;
	      break;
	    }
	}
    }

  free (line);
  fclose (f);
  return ret;
}
Exemple #22
0
static int
do_test (void)
{
  char buf[25];
  size_t i;
  int res = 0;
  int fd;

  mtrace ();

  strcpy (buf, "/tmp/test-vfprintfXXXXXX");
  fd = mkstemp (buf);
  if (fd == -1)
    {
      printf ("cannot open temporary file: %m\n");
      exit (1);
    }
  unlink (buf);

  for (i = 0; i < array_length (locs); ++i)
    {
      FILE *fp;
      struct stat st;
      int fd2;

      setlocale (LC_ALL, locs[i]);

      memset (large, '\1', sizeof (large));
      large[sizeof (large) - 1] = '\0';

      fd2 = dup (fd);
      if (fd2 == -1)
	{
	  printf ("cannot dup for locale %s: %m\n",
		  setlocale (LC_ALL, NULL));
	  exit (1);
	}

      if (ftruncate (fd2, 0) != 0)
	{
	  printf ("cannot truncate file for locale %s: %m\n",
		  setlocale (LC_ALL, NULL));
	  exit (1);
	}

      fp = fdopen (fd2, "a");
      if (fp == NULL)
	{
	  printf ("cannot create FILE for locale %s: %m\n",
		  setlocale (LC_ALL, NULL));
	  exit (1);
	}

      fprintf (fp, "%s", large);
      fprintf (fp, "%.*s", 30000, large);
      large[20000] = '\0';
      /* We're testing a large format string here and need to generate it
         to avoid this source file being ridiculous.  So disable the warning
         about a generated format string.  */
      DIAG_PUSH_NEEDS_COMMENT;
      DIAG_IGNORE_NEEDS_COMMENT (4.9, "-Wformat-security");
      fprintf (fp, large);
      DIAG_POP_NEEDS_COMMENT;
      fprintf (fp, "%-1.300000000s", "hello");

      if (fflush (fp) != 0 || ferror (fp) != 0 || fclose (fp) != 0)
	{
	  printf ("write error for locale %s: %m\n",
		  setlocale (LC_ALL, NULL));
	  exit (1);
	}

      if (fstat (fd, &st) != 0)
	{
	  printf ("cannot stat for locale %s: %m\n",
		  setlocale (LC_ALL, NULL));
	  exit (1);
	}
      else if (st.st_size != 50000 + 30000 + 19999 + 5)
	{
	  printf ("file size incorrect for locale %s: %jd instead of %jd\n",
		  setlocale (LC_ALL, NULL),
		  (intmax_t) st.st_size,
		  (intmax_t) 50000 + 30000 + 19999 + 5);
	  res = 1;
	}
      else
	printf ("locale %s OK\n", setlocale (LC_ALL, NULL));
    }

  close (fd);

  return res;
}
Exemple #23
0
int main(int argc, const char ** argv)
	/*@globals pass2, fileSystem, internalState @*/
	/*@modifies pass2, fileSystem, internalState @*/
{
    int rc;
    int ec = 0;
    poptContext optCon;
    const char ** rest;
    int help = 0;
    int usage = 0;

#if defined(HAVE_MCHECK_H) && defined(HAVE_MTRACE)
    /*@-moduncon -noeffectuncon@*/
    mtrace();   /* Trace malloc only if MALLOC_TRACE=mtrace-output-file. */
    /*@=moduncon =noeffectuncon@*/
#endif

/*@-modobserver@*/
    resetVars();
/*@=modobserver@*/
/*@-temptrans@*/
    optCon = poptGetContext("test1", argc, argv, options, 0);
/*@=temptrans@*/
    (void) poptReadConfigFile(optCon, "./test-poptrc");

#if 1
    while ((rc = poptGetNextOpt(optCon)) > 0)	/* Read all the options ... */
	{};

    poptResetContext(optCon);			/* ... and then start over. */
/*@-modobserver@*/
    resetVars();
/*@=modobserver@*/
#endif

    pass2 = 1;
    if ((rc = poptGetNextOpt(optCon)) < -1) {
	fprintf(stderr, "test1: bad argument %s: %s\n",
		poptBadOption(optCon, POPT_BADOPTION_NOALIAS),
		poptStrerror(rc));
	ec = 2;
	goto exit;
    }

    if (help) {
	poptPrintHelp(optCon, stdout, 0);
	goto exit;
    }
    if (usage) {
	poptPrintUsage(optCon, stdout, 0);
	goto exit;
    }

    fprintf(stdout, "arg1: %d arg2: %s", arg1, arg2);

    if (arg3)
	fprintf(stdout, " arg3: %d", arg3);
    if (inc)
	fprintf(stdout, " inc: %d", inc);
    if (shortopt)
	fprintf(stdout, " short: %d", shortopt);
    if (aVal != bVal)
	fprintf(stdout, " aVal: %d", aVal);
    if (aFlag != bFlag)
	fprintf(stdout, " aFlag: %d", aFlag);
    if (aInt != bInt)
	fprintf(stdout, " aInt: %d", aInt);
    if (aLong != bLong)
	fprintf(stdout, " aLong: %ld", aLong);
/*@-realcompare@*/
    if (aFloat != bFloat)
	fprintf(stdout, " aFloat: %g", (double)aFloat);
    if (aDouble != bDouble)
	fprintf(stdout, " aDouble: %g", aDouble);
/*@=realcompare@*/
    if (oStr != (char *)-1)
	fprintf(stdout, " oStr: %s", (oStr ? oStr : "(none)"));
    if (singleDash)
	fprintf(stdout, " -");

    rest = poptGetArgs(optCon);
    if (rest) {
	fprintf(stdout, " rest:");
	while (*rest) {
	    fprintf(stdout, " %s", *rest);
	    rest++;
	}
    }

    fprintf(stdout, "\n");

exit:
    optCon = poptFreeContext(optCon);
#if defined(HAVE_MCHECK_H) && defined(HAVE_MTRACE)
    /*@-moduncon -noeffectuncon@*/
    muntrace();   /* Trace malloc only if MALLOC_TRACE=mtrace-output-file. */
    /*@=moduncon =noeffectuncon@*/
#endif
    return ec;
}
Exemple #24
0
void MainLoop(int argc, char *argv[])
{
   int c;
   char *drivers = NULL;
   char *optArg;
   char strbuf[2048];
   char homedir[2048];
   const SDL_VideoInfo *inf;
   BOOL flag;
   SDL_Surface *s;

//   mtrace();
   if(AG_GetVariable(agConfig, "font.size", NULL) == NULL) { 
	AG_SetInt(agConfig, "font.size", UI_PT);
   }
   while ((c = AG_Getopt(argc, argv, "?fWd:w:h:T:t:c:T:F:S:o:O:l:s:i:", &optArg, NULL))
          != -1) {
              switch (c) {
              case 'd':
                      drivers = optArg;
                      break;
              case 'f':
                      /* Force full screen */
                      AG_SetBool(agConfig, "view.full-screen", 1);
                      break;
              case 'W':
                      /* Force Window */
                      AG_SetBool(agConfig, "view.full-screen", 0);
                      break;
              case 'T':
                      /* Set an alternate font directory */
                      AG_SetString(agConfig, "font-path", optArg);
                      break;
              case 'F':
                      /* Set an alternate font face */
                      AG_SetString(agConfig, "font.face", optArg);
                      break;
              case 'S':
                  /* Set an alternate font face */
                  AG_SetInt(agConfig, "font.size", atoi(optArg));
                  break;
              case 'o':
                  /* Set an alternate font face */
                  AG_SetString(agConfig, "osdfont.face", optArg);
                  break;
              case 'O':
                  /* Set an alternate font face */
                  AG_SetInt(agConfig, "osdfont.size", atoi(optArg));
                  break;
              case 'l':
                  /* Set an alternate font face */
                  AG_SetString(agConfig, "load-path", optArg);
                  break;
              case 's':
                  /* Set an alternate font face */
                  AG_SetString(agConfig, "save-path", optArg);
                  break;
              case 'i':
                  /* Set an alternate font face */
                  AG_SetString(agConfig, "save-path", optArg);
                  AG_SetString(agConfig, "load-path", optArg);
                  break;
              case 't':
                  /* Change the default font */
                  AG_TextParseFontSpec(optArg);
                  break;
          case '?':
          default:
                  printf("%s [-v] [-f|-W] [-d driver] [-r fps] [-t fontspec] "
                         "[-w width] [-h height] "
                	 "[-F font.face] [-S font.size]"
			 "[-o osd-font.face] [-O osd-font.size]"
			 "[-s SavePath] [-l LoadPath] "
                         "[-T font-path]\n\n"
			 "Usage:\n"
			 "-f : FullScreen\n-W:Window Mode\n",
                         agProgName);
                  exit(0);
          }
    }
   
    if(SDL_getenv("HOME") != NULL) {
	strcpy(homedir, SDL_getenv("HOME"));
    } else {
        strcpy(homedir, ".");
    }
    XM7_DebugLog(XM7_LOG_DEBUG, "HOME = %s", homedir);

#ifdef _WINDOWS
	AG_PrtString(agConfig, "font-path", "%s:%s/xm7:%s:.",
		homedir, homedir, FONTPATH);
#else
    flag = FALSE;
    if(AG_GetString(agConfig, "font-path", strbuf, 2047) != NULL) {
       if((strlen(strbuf) <= 0) || (strncmp(strbuf, "_agFontVera", 11) == 0)){
	  flag = TRUE;
	 }
    } else {
       flag = TRUE;
    }
    if(flag) AG_PrtString(agConfig, "font-path", "%s/.fonts:%s:%s/.xm7:%s:.", 
		homedir, homedir, homedir, FONTPATH);
    flag = FALSE;
   
    XM7_DebugLog(XM7_LOG_DEBUG, "font-path = %s", strbuf);
#endif /* _WINDOWS */
    flag = FALSE;
    if(AG_GetString(agConfig, "font.face", strbuf, 511) != NULL) {
       if((strlen(strbuf) <= 0) || (strncmp(strbuf, "_agFontVera", 11) == 0)){
	  flag = TRUE;
       }
    } else {
	flag = TRUE;
    }
    if(flag) AG_SetString(agConfig, "font.face", UI_FONT);
    flag = FALSE;
    XM7_DebugLog(XM7_LOG_DEBUG, "font.face = %s", strbuf);
   
    stopreq_flag = FALSE;
    run_flag = TRUE;
    // Debug
#ifdef _XM7_FB_DEBUG // Force FB.
drivers = "sdlfb:width=1280:height=880:depth=32";
#endif
	/*
	 * Agar のメインループに入る
	 */

    if(drivers == NULL)  {
#ifdef USE_OPENGL
       if(AG_InitGraphics(NULL) == -1){
                fprintf(stderr, "%s\n", AG_GetError());
                return;
        }
#else
       if(AG_InitGraphics("cocoa,sdlfb") == -1){
                fprintf(stderr, "%s\n", AG_GetError());
                return;
        }
#endif
    } else {
        if (AG_InitGraphics(drivers) == -1) {
                fprintf(stderr, "%s\n", AG_GetError());
                return;
        }
    }
    OnCreate((AG_Widget *)NULL);
//    AG_AtExitFunc(OnDestroy);
    XM7_DebugLog(XM7_LOG_DEBUG, "Widget creation OK.");
   
   XM7_DebugLog(XM7_LOG_INFO, "Emulate version:%d", fm7_ver);
   SDL_InitSubSystem(SDL_INIT_AUDIO | SDL_INIT_JOYSTICK);
   XM7_DebugLog(XM7_LOG_DEBUG, "Audio and JOYSTICK subsystem was initialised.");

   InitInstance();
   XM7_DebugLog(XM7_LOG_DEBUG, "InitInstance() OK.");
   if(agDriverSw && AG_UsingSDL(NULL)) {
      SDL_Init(SDL_INIT_VIDEO);
      XM7_DebugLog(XM7_LOG_INFO, "Start Single WM with SDL.");
      switch(fm7_ver) {
       case 1: // FM7/77
	 if(!(LoadGlobalIconPng(NULL, "tamori.png"))) {
	    LoadGlobalIconPng(NULL, "xm7.png");
	 }
	 break;
       case 2: // FM77AV
	 if(!(LoadGlobalIconPng(NULL, "fujitsu.png"))) {
	    LoadGlobalIconPng(NULL, "xm7.png");
	 }
	 break;
       case 3: // FM77AV20/40/EX/SX
	 if(!(LoadGlobalIconPng(NULL, "fujitsu2.png"))) {
	    LoadGlobalIconPng(NULL, "xm7.png");
	 }
	 break;
       default:
	 LoadGlobalIconPng(NULL, "xm7.png");
	 break;
      }
   } else { // WM function is managed by SDL, load and set icon for WM. 
      SDL_Init(SDL_INIT_VIDEO);
      XM7_DebugLog(XM7_LOG_INFO, "Start multi window mode.");
   }
       
   stopreq_flag = FALSE;
   run_flag = TRUE;
   AG_DrawInitsub();

   inf = SDL_GetVideoInfo();
   if(inf != NULL) {
      RootVideoWidth = inf->current_w;
      RootVideoHeight = inf->current_h;
   } else {
      RootVideoWidth = 640;
      RootVideoHeight = 400;
   }

   newResize = FALSE;
   nDrawTick1D = XM7_timeGetTime();
   nDrawTick1E = nDrawTick1D;

   ResizeWindow_Agar2(nDrawWidth, nDrawHeight);
   XM7_DebugLog(XM7_LOG_DEBUG, "Screen is %d x %d.", nDrawWidth, nDrawHeight);
    switch(nErrorCode) 
     {
      case 0:
	break;
      case 1:
	ErrorPopup(gettext("Error init VM.\nPlease check ROMS and system-memory.\n"));
	break;
      case 2:
	ErrorPopup(gettext("Error init Emulator.\nPlease check window system, display and more.\n"));
	break;
      default:
	ErrorPopup(gettext("Unknown error on setup.\nPlease email to author."));
	break;
     }
#if 0
   mtrace();
#endif
   if(DrawArea != NULL) {
      AG_RedrawOnTick(DrawArea, 1000 / nDrawFPS);
      XM7_DebugLog(XM7_LOG_INFO, "Direct draw mode.");
   } else if(GLDrawArea != NULL) {
      AG_RedrawOnTick(GLDrawArea, 1000 / nDrawFPS);
      XM7_DebugLog(XM7_LOG_INFO, "OpenGL mode.");
   }
   bEventRunFlag == TRUE;
   AGDrawTaskEvent(TRUE);
//   muntrace();
   XM7_DebugLog(XM7_LOG_INFO, "All End.");
}
Exemple #25
0
int main()
{
    /* $ export MALLOC_TRACE=malloc.log */
    mtrace();

    ini_t *conf = ini_load("test.ini");
    if (conf == NULL)
        error(1, errno, "ini_load fail");

    char *type;
    ini_read_str(conf, "main", "type", &type, "test");
    puts(type);
    free(type);

    char value[100] = { 0 };
    ini_read_strn(conf, "main", "len", value, sizeof(value), NULL);
    puts(value);

    int i;
    ini_read_int(conf, "int", "int", &i, 0);
    unsigned ui;
    ini_read_unsigned(conf, "int", "unsigned", &ui, 0);
    printf("int: %d, unsigned: %u\n", i, ui);

    int8_t  int8;
    ini_read_int8(conf, "int", "int8", &int8, 0);
    uint8_t uint8;
    ini_read_uint8(conf, "int", "uint8", &uint8, 0);
    printf("int8: %i, uint8: %u\n", int8, uint8);

    int16_t int16;
    ini_read_int16(conf, "int", "int16", &int16, 0);
    uint16_t uint16;
    ini_read_uint16(conf, "int", "uint16", &uint16, 0);
    printf("int16: %i, uint16: %u\n", int16, uint16);

    int32_t int32;
    ini_read_int32(conf, "int", "int32", &int32, 0);
    uint32_t uint32;
    ini_read_uint32(conf, "int", "uint32", &uint32, 0);
    printf("int32: %i, uint32: %u\n", int32, uint32);

    int64_t int64;
    ini_read_int64(conf, "int", "int64", &int64, 0);
    uint64_t uint64;
    ini_read_uint64(conf, "int", "uint64", &uint64, 0);
    printf("int64: %"PRIi64", uint64: %"PRIu64"\n", int64, uint64);

    float f;
    ini_read_float(conf, "float", "float", &f, 0);
    double d;
    ini_read_double(conf, "float", "double", &d, 0);
    printf("float: %f, double: %f\n", f, d);

    struct sockaddr_in addr;
    ini_read_ipv4_addr(conf, "addr", "ipv4", &addr, "127.0.0.1:0");
    printf("%s:%u\n", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));

    char *proc_name = NULL;
    ini_read_str(conf, "global", "proc_name", &proc_name, "test.ini");
    printf("proc_name: %s\n", proc_name);
    free(proc_name);

    char *phone_num = NULL;
    ini_read_str(conf, "damon", "phone num", &phone_num, "123456789");
    printf("phone num: %s\n", phone_num);
    free(phone_num);

    char *city = NULL;
    ini_read_str(conf, "global", "$%^#@!", &city, "shen zhen");
    puts(city);
    free(city);

    char *name = NULL;
    ini_read_str(conf, NULL, "名字", &name, "");
    puts(name);
    free(name);

    ini_free(conf);

    return 0;
}
Exemple #26
0
int
main(int argc, char *argv[])
{
    int fd_socket, read_socket;
    int listen_port;
    char client_ip[120];
    struct hostent *resolved_client;
    struct sockaddr_storage tentative_addr;
    struct sockaddr *cli_addr;
    int real_addr_size;
    fd_set readfs, masterfs;
    int retcod, status;
    int exit_program = 0;
    pid_t pid;
    char ainfo_port_string[16];
    struct addrinfo ai_req, *ai_ans, *cur_ans;
    int address_found;

#ifdef MTRACE_ON
    char mtrace_log[2048];
#endif

#ifdef MTRACE_ON
    sprintf(mtrace_log, "mtrace_%d.log", getpid());
    setenv("MALLOC_TRACE", mtrace_log, 1);
    mtrace();
#endif
    
    listen_port = 19999;
    if (argc > 2)
    {
       if (strncmp(argv[1],"-p", 2) == 0)
           listen_port = atoi(argv[2]);
    }

    openlog("blahpd", LOG_PID, LOG_DAEMON);
    syslog(LOG_DAEMON | LOG_INFO, "Starting blah server (%s)", RCSID_VERSION);
    
    printf("Starting BLAHP server...\n");
    printf("%s\n", RCSID_VERSION);

    ai_req.ai_flags = AI_PASSIVE;
    ai_req.ai_family = PF_UNSPEC;
    ai_req.ai_socktype = SOCK_STREAM;
    ai_req.ai_protocol = 0; /* Any stream protocol is OK */

    sprintf(ainfo_port_string,"%5d",listen_port);

    if (getaddrinfo(NULL, ainfo_port_string, &ai_req, &ai_ans) != 0)
    {
        fprintf(stderr, "Cannot get address of passive SOCK_STREAM socket.\n");
        exit(1);
    }

    address_found = 0;
    for (cur_ans = ai_ans; cur_ans != NULL; cur_ans = cur_ans->ai_next)
    {
        if ((fd_socket = socket(cur_ans->ai_family,
                                cur_ans->ai_socktype,
                              cur_ans->ai_protocol)) == -1)
        {
            continue; 
        }
        if (bind(fd_socket,cur_ans->ai_addr, cur_ans->ai_addrlen) == 0)
        {
            address_found = 1;
            break;
        }
        close(fd_socket);
    }
    freeaddrinfo(ai_ans);

    if (address_found == 0)
    {
        fprintf(stderr, "Cannot create or bind socket: %s\n", strerror(errno));
        exit(1);
    }

    if (listen(fd_socket,1) == -1)
    {
        fprintf(stderr, "Cannot listen from socket: %s\n", strerror(errno));
        exit(1);
    } else printf("Server up and listening on port %d...\n", listen_port);

    FD_ZERO(&masterfs);
    FD_SET(0, &masterfs);
    FD_SET(fd_socket, &masterfs);

    while (!exit_program)
    {
        printf("\nBLAHP Server > ");

        readfs = masterfs;

        fflush(stdout);
        if ((retcod = select(FD_SETSIZE, &readfs, (fd_set *) 0, (fd_set *) 0, (struct timeval *) 0)) < 0)
        {
            perror("Select error");
            close(fd_socket);
            exit(1);
        } 

        if (FD_ISSET(0, &readfs))
        {
            exit_program = processConsoleCommand();
        }

        if (FD_ISSET(fd_socket, &readfs))
        {
            real_addr_size = sizeof(tentative_addr);
            cli_addr = (struct sockaddr *)(&tentative_addr);
            if ((read_socket = accept(fd_socket, cli_addr, &real_addr_size)) == -1)
            {
                fprintf(stderr,"\nCannot accept connection: %s\n", strerror(errno));
                exit(1);
            }
            if ((getnameinfo(cli_addr, real_addr_size,
                             client_ip, sizeof(client_ip), NULL, 0, 0)) < 0)
            {
                client_ip[sizeof(client_ip)-1]='\000';
                strncpy(client_ip, "-unknown-", sizeof(client_ip) - 1);
            }

            printf("\nIncoming connection from %s\n", client_ip);
            while (waitpid(-1, &status, WNOHANG) > 0);
            pid = fork();
            if (pid < 0)
            {
                fprintf(stderr, "\nCannot fork connection manager: %s\n", strerror(errno));
                close(read_socket);
            }
            else if (pid >0)
            {
                printf("\nNew connection managed by child process %d\n", pid);
                close(read_socket);
            }
            else
            {
                close(fd_socket);
		syslog(LOG_DAEMON | LOG_INFO, "fork to serve connection from %s", client_ip);
                serveConnection(read_socket, client_ip);
            }
        }
    }

    printf("Server shutting down...\n");

    shutdown(fd_socket, SHUT_RDWR);
    close(fd_socket);
    printf("Socket closed\n");

    /* Shutdown of child processes */

    printf("Goodbye!\n");
    exit(0);
}
Exemple #27
0
int
main (int argc, char *argv[])
{
  int result = 0;

  /* For debugging.  */
  mtrace ();

  /* This is the place where the .mo files are placed.  */
  if (argc > 1)
    {
      bindtextdomain ("existing-domain", argv[1]);
      bindtextdomain ("existing-time-domain", argv[1]);
      bindtextdomain ("non-existing-domain", argv[1]);
    }

  /* The locale the catalog is created for is "existing-category".  Now
     set the various variables in question to this value and run the
     test.  */
  setenv ("LANGUAGE", "existing-locale", 1);
  setenv ("LC_ALL", "non-existing-locale", 1);
  setenv ("LC_MESSAGES", "non-existing-locale", 1);
  setenv ("LC_CTYPE", "non-existing-locale", 1);
  setenv ("LANG", "non-existing-locale", 1);
  check_setlocale (LC_CTYPE, "de_DE.UTF-8");
  check_setlocale (LC_MESSAGES, "de_DE.UTF-8");
  unsetenv ("OUTPUT_CHARSET");
  /* This is the name of the existing domain with a catalog for the
     LC_MESSAGES category.  */
  textdomain ("existing-domain");
  puts ("test `gettext' with LANGUAGE set");
  if (positive_gettext_test () != 0)
    {
      puts ("FAILED");
      result = 1;
    }
  /* This is the name of a non-existing domain with a catalog for the
     LC_MESSAGES category.  We leave this value set for the `dgettext'
     and `dcgettext' tests.  */
  textdomain ("non-existing-domain");
  puts ("test `gettext' with LANGUAGE set");
  if (negative_gettext_test () != 0)
    {
      puts ("FAILED");
      result = 1;
    }
  puts ("test `dgettext' with LANGUAGE set");
  if (positive_dgettext_test ("existing-domain") != 0)
    {
      puts ("FAILED");
      result = 1;
    }

  /* Now the same tests with LC_ALL deciding.  */
  unsetenv ("LANGUAGE");
  setenv ("LC_ALL", "existing-locale", 1);
  check_setlocale (LC_ALL, "");
  puts ("test `gettext' with LC_ALL set");
  /* This is the name of the existing domain with a catalog for the
     LC_MESSAGES category.  */
  textdomain ("existing-domain");
  if (positive_gettext_test () != 0)
    {
      puts ("FAILED");
      result = 1;
    }
  /* This is the name of a non-existing domain with a catalog for the
     LC_MESSAGES category.  We leave this value set for the `dgettext'
     and `dcgettext' tests.  */
  textdomain ("non-existing-domain");
  puts ("test `gettext' with LC_ALL deciding");
  if (negative_gettext_test () != 0)
    {
      puts ("FAILED");
      result = 1;
    }
  puts ("test `dgettext' with LC_ALL deciding");
  if (positive_dgettext_test ("existing-domain") != 0)
    {
      puts ("FAILED");
      result = 1;
    }

  /* Now the same tests with LC_MESSAGES deciding.  */
  unsetenv ("LC_ALL");
  setenv ("LC_MESSAGES", "existing-locale", 1);
  check_setlocale (LC_MESSAGES, "");
  setenv ("LC_TIME", "existing-locale", 1);
  check_setlocale (LC_TIME, "");
  setenv ("LC_NUMERIC", "non-existing-locale", 1);
  char *what = setlocale (LC_NUMERIC, "");
  if (what != NULL)
    {
      printf ("setlocale succeeded (%s), expected failure\n", what);
      result = 1;
    }

  puts ("test `gettext' with LC_MESSAGES set");
  /* This is the name of the existing domain with a catalog for the
     LC_MESSAGES category.  */
  textdomain ("existing-domain");
  if (positive_gettext_test () != 0)
    {
      puts ("FAILED");
      result = 1;
    }
  /* This is the name of a non-existing domain with a catalog for the
     LC_MESSAGES category.  We leave this value set for the `dgettext'
     and `dcgettext' tests.  */
  textdomain ("non-existing-domain");
  puts ("test `gettext' with LC_MESSAGES deciding");
  if (negative_gettext_test () != 0)
    {
      puts ("FAILED");
      result = 1;
    }
  puts ("test `dgettext' with LC_MESSAGES deciding");
  if (positive_dgettext_test ("existing-domain") != 0)
    {
      puts ("FAILED");
      result = 1;
    }
  puts ("test `dcgettext' with category == LC_MESSAGES");
  if (positive_dcgettext_test ("existing-domain", LC_MESSAGES) != 0)
    {
      puts ("FAILED");
      result = 1;
    }
  /* Try a different category.  For this we also switch the domain.  */
  puts ("test `dcgettext' with LANGUAGE == LC_TIME");
  if (positive_dcgettext_test ("existing-time-domain", LC_TIME) != 0)
    {
      puts ("FAILED");
      result = 1;
    }
  /* This time use a category for which there is no catalog.  */
  puts ("test `dcgettext' with LANGUAGE == LC_NUMERIC");
  if (negative_dcgettext_test ("existing-domain", LC_NUMERIC) != 0)
    {
      puts ("FAILED");
      result = 1;
    }

  /* Now the same tests with LANG deciding.  */
  unsetenv ("LC_MESSAGES");
  unsetenv ("LC_CTYPE");
  unsetenv ("LC_TIME");
  unsetenv ("LC_NUMERIC");
  setenv ("LANG", "existing-locale", 1);
  check_setlocale (LC_ALL, "");
  /* This is the name of the existing domain with a catalog for the
     LC_MESSAGES category.  */
  textdomain ("existing-domain");
  puts ("test `gettext' with LANG set");
  if (positive_gettext_test () != 0)
    {
      puts ("FAILED");
      result = 1;
    }
  /* This is the name of a non-existing domain with a catalog for the
     LC_MESSAGES category.  We leave this value set for the `dgettext'
     and `dcgettext' tests.  */
  textdomain ("non-existing-domain");
  puts ("test `gettext' with LANG set");
  if (negative_gettext_test () != 0)
    {
      puts ("FAILED");
      result = 1;
    }
  puts ("test `dgettext' with LANG set");
  if (positive_dgettext_test ("existing-domain") != 0)
    {
      puts ("FAILED");
      result = 1;
    }

  check_setlocale (LC_ALL, "C");

  return result;
}
Exemple #28
0
int
zmain (void)
{
  glob_t gl;
  int errval;
  int result = 0;
  const char *fmt;
  int flags;

  mtrace ();

  memset (&gl, '\0', sizeof (gl));

  gl.gl_closedir = my_closedir;
  gl.gl_readdir = my_readdir;
  gl.gl_opendir = my_opendir;
  gl.gl_lstat = my_stat;
  gl.gl_stat = my_stat;

#define test(a, b, c...) \
  fmt = a;								      \
  flags = b;								      \
  errval = glob (fmt, flags, NULL, &gl);				      \
  if (errval != 0)							      \
    {									      \
      printf ("glob (\"%s\", %s) failed: %s\n", fmt, flagstr (flags),	      \
	      errval >= 0 && errval < nglob_errstring			      \
	      ? glob_errstring[errval] : "???");			      \
      result = 1;							      \
    }									      \
  else									      \
    result |= test_result (fmt, flags, &gl, (const char *[]) { c, NULL })

  test ("*/*/*", GLOB_ALTDIRFUNC,
	"dir1lev1/dir2lev2/dir1lev3",
	"dir1lev1/dir2lev2/file1lev3",
	"dir1lev1/dir2lev2/file2lev3",
	"dir1lev1/dir3lev2/file3lev3",
	"dir1lev1/dir3lev2/file4lev3");

  test ("*/*/*", GLOB_ALTDIRFUNC | GLOB_PERIOD,
	"dir1lev1/dir1lev2/.",
	"dir1lev1/dir1lev2/..",
	"dir1lev1/dir2lev2/.",
	"dir1lev1/dir2lev2/..",
	"dir1lev1/dir2lev2/.foo",
	"dir1lev1/dir2lev2/dir1lev3",
	"dir1lev1/dir2lev2/file1lev3",
	"dir1lev1/dir2lev2/file2lev3",
	"dir1lev1/dir3lev2/.",
	"dir1lev1/dir3lev2/..",
	"dir1lev1/dir3lev2/file3lev3",
	"dir1lev1/dir3lev2/file4lev3",
	"dir2lev1/dir1lev2/.",
	"dir2lev1/dir1lev2/..",
	"dir2lev1/dir1lev2/.dir",
	"dir2lev1/dir1lev2/.foo");

  test ("*/*/.*", GLOB_ALTDIRFUNC,
	"dir1lev1/dir1lev2/.",
	"dir1lev1/dir1lev2/..",
	"dir1lev1/dir2lev2/.",
	"dir1lev1/dir2lev2/..",
	"dir1lev1/dir2lev2/.foo",
	"dir1lev1/dir3lev2/.",
	"dir1lev1/dir3lev2/..",
	"dir2lev1/dir1lev2/.",
	"dir2lev1/dir1lev2/..",
	"dir2lev1/dir1lev2/.dir",
	"dir2lev1/dir1lev2/.foo");

  test ("*1*/*2*/.*", GLOB_ALTDIRFUNC,
	"dir1lev1/dir1lev2/.",
	"dir1lev1/dir1lev2/..",
	"dir1lev1/dir2lev2/.",
	"dir1lev1/dir2lev2/..",
	"dir1lev1/dir2lev2/.foo",
	"dir1lev1/dir3lev2/.",
	"dir1lev1/dir3lev2/..",
	"dir2lev1/dir1lev2/.",
	"dir2lev1/dir1lev2/..",
	"dir2lev1/dir1lev2/.dir",
	"dir2lev1/dir1lev2/.foo");

  test ("*1*/*1*/.*", GLOB_ALTDIRFUNC,
	"dir1lev1/dir1lev2/.",
	"dir1lev1/dir1lev2/..",
	"dir2lev1/dir1lev2/.",
	"dir2lev1/dir1lev2/..",
	"dir2lev1/dir1lev2/.dir",
	"dir2lev1/dir1lev2/.foo");

  test ("\\/*", GLOB_ALTDIRFUNC,
	"/dir1lev1",
	"/dir2lev1",
	"/file1lev1",
	"/file2lev1");

  globfree (&gl);

  return result;
}
Exemple #29
0
int
main (int argc, char *argv[])
{
  int remaining;
  int err;

#ifndef NDEBUG
  /* Enable memory debugging.  */
  mtrace ();
#endif

  /* Sanity check.  We always want to use the LFS functionality.  */
  if (sizeof (off_t) != sizeof (off64_t))
    abort ();

  /* We use no threads here which can interfere with handling a stream.  */
  __fsetlocking (stdin, FSETLOCKING_BYCALLER);
  __fsetlocking (stdout, FSETLOCKING_BYCALLER);
  __fsetlocking (stderr, FSETLOCKING_BYCALLER);

  /* Set locale.  */
  setlocale (LC_ALL, "");

  /* Make sure the message catalog can be found.  */
  bindtextdomain (PACKAGE_TARNAME, LOCALEDIR);

  /* Initialize the message catalog.  */
  textdomain (PACKAGE_TARNAME);

  /* Before we start tell the ELF library which version we are using.  */
  elf_version (EV_CURRENT);

  /* The user can use the LD_LIBRARY_PATH environment variable to add
     additional lookup directories.  */
  ld_library_path1 = getenv ("LD_LIBRARY_PATH");

  /* Initialize the memory handling.  */
#define obstack_chunk_alloc xmalloc
#define obstack_chunk_free free
  obstack_init (&ld_state.smem);

  /* Recognize old-style parameters for compatibility.  */
  replace_args (argc, argv);

  /* One quick pass over the parameters which allows us to scan for options
     with global effect which influence the rest of the processing.  */
  argp_parse (&argp_1st, argc, argv, ARGP_IN_ORDER, &remaining, NULL);

  /* We need at least one input file.  */
  if (input_file_list == NULL)
    {
      error (0, 0, gettext ("At least one input file needed"));
      argp_help (&argp_1st, stderr, ARGP_HELP_SEE, "ld");
      exit (EXIT_FAILURE);
    }

  /* Determine which ELF backend to use.  */
  determine_output_format ();

  /* If no hash style was specific default to the oldand slow SysV
     method.  */
  if (unlikely (ld_state.hash_style == hash_style_none))
    ld_state.hash_style = hash_style_sysv;

  /* Prepare state.  */
  err = ld_prepare_state (emulation);
  if (err != 0)
    error (EXIT_FAILURE, 0, gettext ("error while preparing linking"));

  /* XXX Read the linker script now.  Since we later will have the linker
     script built in we don't go into trouble to make sure we handle GROUP
     statements in the script.  This simply must not happen.  */
  ldin = fopen (linker_script, "r");
  if (ldin == NULL)
    error (EXIT_FAILURE, errno, gettext ("cannot open linker script '%s'"),
	   linker_script);
  /* No need for locking.  */
  __fsetlocking (ldin, FSETLOCKING_BYCALLER);

  ld_state.srcfiles = NULL;
  ldlineno = 1;
  ld_scan_version_script = 0;
  ldin_fname = linker_script;
  if (ldparse () != 0)
    /* Something went wrong during parsing.  */
    exit (EXIT_FAILURE);
  fclose (ldin);

  /* We now might have a list of directories to look for libraries in
     named by the linker script.  Put them in a different list so that
     they are searched after all paths given by the user on the
     command line.  */
  ld_state.default_paths = ld_state.paths;
  ld_state.paths = ld_state.tailpaths = NULL;

  /* Get runpath/rpath information in usable form.  */
  gen_rxxpath_data ();

  /* Parse and process arguments for real.  */
  argp_parse (&argp_2nd, argc, argv, ARGP_IN_ORDER, &remaining, NULL);
  /* All options should have been processed by the argp parser.  */
  assert (remaining == argc);

  /* Process the last file.  */
  while (last_file != NULL)
    /* Try to open the file.  */
    error_loading |= FILE_PROCESS (-1, last_file, &ld_state, &last_file);

  /* Stop if there has been a problem while reading the input files.  */
  if (error_loading)
    exit (error_loading);

  /* See whether all opened -( were closed.  */
  if (group_level > 0)
    {
      error (0, 0, gettext ("-( without matching -)"));
      argp_help (&argp_1st, stderr, ARGP_HELP_SEE, "ld");
      exit (EXIT_FAILURE);
    }

  /* When we create a relocatable file we don't have to look for the
     DT_NEEDED DSOs and we also don't test for undefined symbols.  */
  if (ld_state.file_type != relocatable_file_type)
    {
      /* At this point we have loaded all the direct dependencies.  What
	 remains to be done is find the indirect dependencies.  These are
	 DSOs which are referenced by the DT_NEEDED entries in the DSOs
	 which are direct dependencies.  We have to transitively find and
	 load all these dependencies.  */
      load_needed ();

      /* At this point all object files and DSOs are read.  If there
	 are still undefined symbols left they might have to be
	 synthesized from the linker script.  */
      create_lscript_symbols ();

      /* Now that we have loaded all the object files we can determine
	 whether we have any non-weak unresolved references left.  If
	 there are any we stop.  If the user used the '-z nodefs' option
	 and we are creating a DSO don't perform the tests.  */
      if (FLAG_UNRESOLVED (&ld_state) != 0)
	exit (1);
    }

  /* Collect information about the relocations which will be carried
     forward into the output.  We have to do this here and now since
     we need to know which sections have to be created.  */
  if (ld_state.file_type != relocatable_file_type)
    {
      void *p ;
      struct scnhead *h;

      p = NULL;
      while ((h = ld_section_tab_iterate (&ld_state.section_tab, &p)) != NULL)
	if (h->type == SHT_REL || h->type == SHT_RELA)
	  {
	    struct scninfo *runp = h->last;
	    do
	      {
		/* If we are processing the relocations determine how
		   many will be in the output file.  Also determine
		   how many GOT entries are needed.  */
		COUNT_RELOCATIONS (&ld_state, runp);

		ld_state.relsize_total += runp->relsize;
	      }
	    while ((runp = runp->next) != h->last);
	  }
    }

  /* Not part of the gABI, but part of every psABI: the symbols for the
     GOT section.  Add the symbol if necessary.  */
  if (ld_state.need_got)
    create_special_section_symbol (&ld_state.got_symbol,
				   "_GLOBAL_OFFSET_TABLE_");
  /* Similarly for the _DYNAMIC symbol which points to the dynamic
     section.  */
  if (dynamically_linked_p ())
    create_special_section_symbol (&ld_state.dyn_symbol, "_DYNAMIC");

  /* We are ready to start working on the output file.  Not all
     information has been gather or created yet.  This will be done as
     we go.  Open the file now.  */
  if (OPEN_OUTFILE (&ld_state, EM_NONE, ELFCLASSNONE, ELFDATANONE) != 0)
    exit (1);

  /* Create the sections which are generated by the linker and are not
     present in the input file.  The output file must already have
     been opened since we need the ELF descriptor to deduce type
     sizes.  */
  GENERATE_SECTIONS (&ld_state);

  /* At this point we have read all the files and know all the
     sections which have to be linked into the application.  We do now
     create an array listing all the sections.  We will than pass this
     array to a system specific function which can reorder it at will.
     The functions can also merge sections if this is what is
     wanted.  */
  collect_sections ();

  /* Create the output sections now.  This may requires sorting them
     first.  */
  CREATE_SECTIONS (&ld_state);

  /* Create the output file data.  Appropriate code for the selected
     output file type is called.  */
  if (CREATE_OUTFILE (&ld_state) != 0)
    exit (1);

  /* Finalize the output file, write the data out.  */
  err |= FINALIZE (&ld_state);

  /* Return with an non-zero exit status also if any error message has
     been printed.  */
  return err | (error_message_count != 0);
}
Exemple #30
0
int 
main(int argc, const char ** argv) {

    poptContext optCon;   /* context for parsing command-line options */
    struct poptOption userOptionsTable[] = {
        { "first", 'f', POPT_ARG_STRING, &firstname, 0,
            "user's first name", "first" },
        { "last", 'l', POPT_ARG_STRING, &lastname, 0,
            "user's last name", "last" },
        { "username", 'u', POPT_ARG_STRING, &username, 0,
            "system user name", "user" },
        { "password", 'p', POPT_ARG_STRING, &password, 0,
            "system password name", "password" },
        { "addr1", '1', POPT_ARG_STRING, &addr1, 0,
            "line 1 of address", "addr1" },
        { "addr2", '2', POPT_ARG_STRING, &addr2, 0,
            "line 2 of address", "addr2" },
        { "city", 'c', POPT_ARG_STRING, &city, 0,
            "city", "city" },
        { "state", 's', POPT_ARG_STRING, &state, 0,
            "state or province", "state" },
        { "postal", 'P', POPT_ARG_STRING, &postal, 0,
            "postal or zip code", "postal" },
        { "zip", 'z', POPT_ARG_STRING, &postal, 0,
            "postal or zip code", "postal" },
        { "country", 'C', POPT_ARG_STRING, &country, 0,
            "two letter ISO country code", "country" },
        { "email", 'e', POPT_ARG_STRING, &email, 0,
            "user's email address", "email" },
        { "dayphone", 'd', POPT_ARG_STRING, &dayphone, 0,
            "day time phone number", "dayphone" },
        { "fax", 'F', POPT_ARG_STRING, &fax, 0,
            "fax number", "fax" },
        { NULL, 0, 0, NULL, 0, NULL, NULL }
    };
    struct poptOption transactOptionsTable[] = {
        { "keyfile", '\0', POPT_ARG_STRING, &PathnameOfKeyFile, 0,
            "transact offer key file (flat_O.kf)", "key-file" },
        { "offerfile", '\0', POPT_ARG_STRING, &PathnameOfOfferFile, 0,
            "offer template file (osl.ofr)", "offer-file" },
        { "storeid", '\0', POPT_ARG_INT, &txStoreId, 0,
            "store id", "store-id" },
        { "rcfile", '\0', POPT_ARG_STRING, &rcfile, 0,
            "default command line options (in popt format)", "rcfile" },
        { "txhost", '\0', POPT_ARG_STRING, &txHost, 0,
            "transact host", "transact-host" },
        { "txsslport", '\0', POPT_ARG_INT, &txSslPort, 0,
            "transact server ssl port ", "transact ssl port" },
        { "cnhost", '\0', POPT_ARG_STRING, &contentHost, 0,
            "content host", "content-host" },
        { "cnpath", '\0', POPT_ARG_STRING, &contentPath, 0,
            "content url path", "content-path" },
        { NULL, 0, 0, NULL, 0, NULL, NULL }
    };

    struct poptOption databaseOptionsTable[] = {
        { "dbpassword", '\0', POPT_ARG_STRING, &dbPassword, 0,
            "Database password", "DB password" },
        { "dbusername", '\0', POPT_ARG_STRING, &dbUserName, 0,
            "Database user name", "DB UserName" },
        { NULL, 0, 0, NULL, 0, NULL, NULL }
    };

    struct poptOption optionsTable[] = {
	{ NULL, '\0', POPT_ARG_INCLUDE_TABLE,  NULL, 0,
            "Transact Options (not all will apply)", NULL },
	{ NULL, '\0', POPT_ARG_INCLUDE_TABLE,  NULL, 0,
            "Transact Database Names", NULL },
	{ NULL, '\0', POPT_ARG_INCLUDE_TABLE,  NULL, 0,
            "User Fields", NULL },
        POPT_AUTOHELP
        { NULL, 0, 0, NULL, 0, NULL, NULL }
    };

    optionsTable[0].arg = transactOptionsTable;
    optionsTable[1].arg = databaseOptionsTable;
    optionsTable[2].arg = userOptionsTable;

#if HAVE_MCHECK_H && HAVE_MTRACE
    mtrace();   /* Trace malloc only if MALLOC_TRACE=mtrace-output-file. */
#endif

    optCon = poptGetContext("createuser", argc, argv, optionsTable, 0);
    poptReadConfigFile(optCon, rcfile );

    /* although there are no options to be parsed, check for --help */
    poptGetNextOpt(optCon);

    optCon = poptFreeContext(optCon);

    printf( "dbusername %s\tdbpassword %s\n"
            "txhost %s\ttxsslport %d\ttxstoreid %d\tpathofkeyfile %s\n"
	    "username %s\tpassword %s\tfirstname %s\tlastname %s\n"
	    "addr1 %s\taddr2 %s\tcity %s\tstate %s\tpostal %s\n"
	    "country %s\temail %s\tdayphone %s\tfax %s\n",
        dbUserName, dbPassword,
        txHost, txSslPort, txStoreId, PathnameOfKeyFile,
        username, password, firstname, lastname,
        addr1,addr2, city, state, postal,
        country, email, dayphone, fax);
    return 0;
}