os/ossrv/glib/glib/gtestutils.c
author sl
Tue, 10 Jun 2014 14:32:02 +0200
changeset 1 260cb5ec6c19
permissions -rw-r--r--
Update contrib.
     1 /* GLib testing utilities
     2  * Copyright (C) 2007 Imendio AB
     3  * Authors: Tim Janik, Sven Herzberg
     4  * Portions copyright (c) 2009 Nokia Corporation.  All rights reserved.
     5  * This library is free software; you can redistribute it and/or
     6  * modify it under the terms of the GNU Lesser General Public
     7  * License as published by the Free Software Foundation; either
     8  * version 2 of the License, or (at your option) any later version.
     9  *
    10  * This library is distributed in the hope that it will be useful,
    11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    13  * Lesser General Public License for more details.
    14  *
    15  * You should have received a copy of the GNU Lesser General Public
    16  * License along with this library; if not, write to the
    17  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
    18  * Boston, MA 02111-1307, USA.
    19  */
    20 #include "config.h"
    21 #include "gtestutils.h"
    22 #include "galias.h"
    23 #include <sys/types.h>
    24 #ifdef G_OS_UNIX
    25 #include <sys/wait.h>
    26 #include <sys/time.h>
    27 #include <fcntl.h>
    28 #endif
    29 #include <string.h>
    30 #include <stdlib.h>
    31 #include <stdio.h>
    32 #ifdef HAVE_UNISTD_H
    33 #include <unistd.h>
    34 #endif
    35 #ifdef G_OS_WIN32
    36 #include <io.h>
    37 #endif
    38 #include <errno.h>
    39 #include <signal.h>
    40 #ifdef HAVE_SYS_SELECT_H
    41 #include <sys/select.h>
    42 #endif /* HAVE_SYS_SELECT_H */
    43 
    44 #ifdef __SYMBIAN32__
    45 #include "glib_wsd.h"
    46 #endif /* __SYMBIAN32__ */
    47 
    48 /* --- structures --- */
    49 struct GTestCase
    50 {
    51   gchar  *name;
    52   guint   fixture_size;
    53   void   (*fixture_setup)    (void*, gconstpointer);
    54   void   (*fixture_test)     (void*, gconstpointer);
    55   void   (*fixture_teardown) (void*, gconstpointer);
    56   gpointer test_data;
    57 };
    58 struct GTestSuite
    59 {
    60   gchar  *name;
    61   GSList *suites;
    62   GSList *cases;
    63 };
    64 typedef struct DestroyEntry DestroyEntry;
    65 struct DestroyEntry
    66 {
    67   DestroyEntry *next;
    68   GDestroyNotify destroy_func;
    69   gpointer       destroy_data;
    70 };
    71 
    72 /* --- prototypes --- */
    73 static void     test_run_seed                   (const gchar *rseed);
    74 static void     test_trap_clear                 (void);
    75 static guint8*  g_test_log_dump                 (GTestLogMsg *msg,
    76                                                  guint       *len);
    77 static void     gtest_default_log_handler       (const gchar    *log_domain,
    78                                                  GLogLevelFlags  log_level,
    79                                                  const gchar    *message,
    80                                                  gpointer        unused_data);
    81 
    82 
    83 /* --- variables --- */
    84 #if (EMULATOR)
    85 PLS(test_log_fd,gtestutils,int)
    86 PLS(test_mode_fatal,gtestutils,gboolean)
    87 PLS(g_test_run_once,gtestutils,gboolean)
    88 PLS(test_run_list,gtestutils,gboolean)
    89 PLS(test_run_seedstr,gtestutils,gchar*)
    90 PLS(test_run_rand,gtestutils,GRand*)
    91 PLS(test_run_name,gtestutils,gchar*)
    92 PLS(test_run_forks,gtestutils,guint)
    93 PLS(test_run_count,gtestutils,guint)
    94 PLS(test_skip_count,gtestutils,guint)
    95 PLS(test_user_timer,gtestutils,GTimer*)
    96 PLS(test_user_stamp,gtestutils,double)
    97 PLS(test_paths,gtestutils,GSList*)
    98 PLS(test_suite_root,gtestutils,GTestSuite*)
    99 PLS(test_trap_last_status,gtestutils,int)
   100 PLS(test_trap_last_pid,gtestutils,int)
   101 PLS(test_trap_last_stdout,gtestutils,char*)
   102 PLS(test_trap_last_stderr,gtestutils,char*)
   103 PLS(test_uri_base,gtestutils,char*)
   104 PLS(test_debug_log,gtestutils,gboolean)
   105 PLS(test_destroy_queue,gtestutils,DestroyEntry*)
   106 PLS(mutable_test_config_vars,gtestutils,GTestConfig)
   107 PLS(g_test_config_vars,gtestutils,const GTestConfig* const)
   108 
   109 #define test_log_fd (*FUNCTION_NAME(test_log_fd,gtestutils)())
   110 #define test_mode_fatal (*FUNCTION_NAME(test_mode_fatal,gtestutils)())
   111 #define g_test_run_once (*FUNCTION_NAME(g_test_run_once,gtestutils)())
   112 #define test_run_list (*FUNCTION_NAME(test_run_list,gtestutils)())
   113 #define test_run_seedstr (*FUNCTION_NAME(test_run_seedstr,gtestutils)())
   114 #define test_run_rand (*FUNCTION_NAME(test_run_rand,gtestutils)())
   115 #define test_run_name (*FUNCTION_NAME(test_run_name,gtestutils)())
   116 #define test_run_forks (*FUNCTION_NAME(test_run_forks,gtestutils)())
   117 #define test_run_count (*FUNCTION_NAME(test_run_count,gtestutils)())
   118 #define test_skip_count (*FUNCTION_NAME(test_skip_count,gtestutils)())
   119 #define test_user_timer (*FUNCTION_NAME(test_user_timer,gtestutils)())
   120 #define test_user_stamp (*FUNCTION_NAME(test_user_stamp,gtestutils)())
   121 #define test_paths (*FUNCTION_NAME(test_paths,gtestutils)())
   122 #define test_suite_root (*FUNCTION_NAME(test_suite_root,gtestutils)())
   123 #define test_trap_last_status (*FUNCTION_NAME(test_trap_last_status,gtestutils)())
   124 #define test_trap_last_pid (*FUNCTION_NAME(test_trap_last_pid,gtestutils)())
   125 #define test_trap_last_stdout (*FUNCTION_NAME(test_trap_last_stdout,gtestutils)())
   126 #define test_trap_last_stderr (*FUNCTION_NAME(test_trap_last_stderr,gtestutils)())
   127 #define test_uri_base (*FUNCTION_NAME(test_uri_base,gtestutils)())
   128 #define test_debug_log (*FUNCTION_NAME(test_debug_log,gtestutils)())
   129 #define test_destroy_queue (*FUNCTION_NAME(test_destroy_queue,gtestutils)())
   130 #define mutable_test_config_vars (*FUNCTION_NAME(mutable_test_config_vars,gtestutils)())
   131 #define g_test_config_vars (*FUNCTION_NAME(g_test_config_vars,gtestutils)())
   132 
   133 #else
   134 static int         test_log_fd = -1;
   135 static gboolean    test_mode_fatal = TRUE;
   136 static gboolean    g_test_run_once = TRUE;
   137 static gboolean    test_run_list = FALSE;
   138 static gchar      *test_run_seedstr = NULL;
   139 static GRand      *test_run_rand = NULL;
   140 static gchar      *test_run_name = "";
   141 static guint       test_run_forks = 0;
   142 static guint       test_run_count = 0;
   143 static guint       test_skip_count = 0;
   144 static GTimer     *test_user_timer = NULL;
   145 static double      test_user_stamp = 0;
   146 static GSList     *test_paths = NULL;
   147 static GTestSuite *test_suite_root = NULL;
   148 static int         test_trap_last_status = 0;
   149 static int         test_trap_last_pid = 0;
   150 static char       *test_trap_last_stdout = NULL;
   151 static char       *test_trap_last_stderr = NULL;
   152 static char       *test_uri_base = NULL;
   153 static gboolean    test_debug_log = FALSE;
   154 static DestroyEntry *test_destroy_queue = NULL;
   155 static GTestConfig mutable_test_config_vars = {
   156   FALSE,        /* test_initialized */
   157   TRUE,         /* test_quick */
   158   FALSE,        /* test_perf */
   159   FALSE,        /* test_verbose */
   160   FALSE,        /* test_quiet */
   161 };
   162 const GTestConfig * const g_test_config_vars = &mutable_test_config_vars ;
   163 
   164 #endif//EMULATOR
   165 #ifdef __SYMBIAN32__
   166 EXPORT_C const GTestConfig * const *_g_test_config_vars(void)
   167 	{
   168 	return &g_test_config_vars;
   169 	}
   170 #endif//__SYMBIAN32__
   171 /* --- functions --- */
   172 EXPORT_C const char*
   173 g_test_log_type_name (GTestLogType log_type)
   174 {
   175   switch (log_type)
   176     {
   177     case G_TEST_LOG_NONE:               return "none";
   178     case G_TEST_LOG_ERROR:              return "error";
   179     case G_TEST_LOG_START_BINARY:       return "binary";
   180     case G_TEST_LOG_LIST_CASE:          return "list";
   181     case G_TEST_LOG_SKIP_CASE:          return "skip";
   182     case G_TEST_LOG_START_CASE:         return "start";
   183     case G_TEST_LOG_STOP_CASE:          return "stop";
   184     case G_TEST_LOG_MIN_RESULT:         return "minperf";
   185     case G_TEST_LOG_MAX_RESULT:         return "maxperf";
   186     case G_TEST_LOG_MESSAGE:            return "message";
   187     }
   188   return "???";
   189 }
   190 
   191 static void
   192 g_test_log_send (guint         n_bytes,
   193                  const guint8 *buffer)
   194 {
   195   if (test_log_fd >= 0)
   196     {
   197       int r;
   198       do
   199         r = write (test_log_fd, buffer, n_bytes);
   200       while (r < 0 && errno == EINTR);
   201     }
   202   if (test_debug_log)
   203     {
   204       GTestLogBuffer *lbuffer = g_test_log_buffer_new ();
   205       GTestLogMsg *msg;
   206       guint ui;
   207       g_test_log_buffer_push (lbuffer, n_bytes, buffer);
   208       msg = g_test_log_buffer_pop (lbuffer);
   209       g_warn_if_fail (msg != NULL);
   210       g_warn_if_fail (lbuffer->data->len == 0);
   211       g_test_log_buffer_free (lbuffer);
   212       /* print message */
   213       g_printerr ("{*LOG(%s)", g_test_log_type_name (msg->log_type));
   214       for (ui = 0; ui < msg->n_strings; ui++)
   215         g_printerr (":{%s}", msg->strings[ui]);
   216       if (msg->n_nums)
   217         {
   218           g_printerr (":(");
   219           for (ui = 0; ui < msg->n_nums; ui++)
   220             g_printerr ("%s%.16Lg", ui ? ";" : "", msg->nums[ui]);
   221           g_printerr (")");
   222         }
   223       g_printerr (":LOG*}\n");
   224       g_test_log_msg_free (msg);
   225     }
   226 }
   227 
   228 static void
   229 g_test_log (GTestLogType lbit,
   230             const gchar *string1,
   231             const gchar *string2,
   232             guint        n_args,
   233             long double *largs)
   234 {
   235   gboolean fail = lbit == G_TEST_LOG_STOP_CASE && largs[0] != 0;
   236   GTestLogMsg msg;
   237   gchar *astrings[3] = { NULL, NULL, NULL };
   238   guint8 *dbuffer;
   239   guint32 dbufferlen;
   240 
   241   switch (lbit)
   242     {
   243     case G_TEST_LOG_START_BINARY:
   244       if (g_test_verbose())
   245         g_print ("GTest: random seed: %s\n", string2);
   246       break;
   247     case G_TEST_LOG_STOP_CASE:
   248       if (g_test_verbose())
   249         g_print ("GTest: result: %s\n", fail ? "FAIL" : "OK");
   250       else if (!g_test_quiet())
   251         g_print ("%s\n", fail ? "FAIL" : "OK");
   252       if (fail && test_mode_fatal)
   253         abort();
   254       break;
   255     case G_TEST_LOG_MIN_RESULT:
   256       if (g_test_verbose())
   257         g_print ("(MINPERF:%s)\n", string1);
   258       break;
   259     case G_TEST_LOG_MAX_RESULT:
   260       if (g_test_verbose())
   261         g_print ("(MAXPERF:%s)\n", string1);
   262       break;
   263     case G_TEST_LOG_MESSAGE:
   264       if (g_test_verbose())
   265         g_print ("(MSG: %s)\n", string1);
   266       break;
   267     default: ;
   268     }
   269 
   270   msg.log_type = lbit;
   271   msg.n_strings = (string1 != NULL) + (string1 && string2);
   272   msg.strings = astrings;
   273   astrings[0] = (gchar*) string1;
   274   astrings[1] = astrings[0] ? (gchar*) string2 : NULL;
   275   msg.n_nums = n_args;
   276   msg.nums = largs;
   277   dbuffer = g_test_log_dump (&msg, &dbufferlen);
   278   g_test_log_send (dbufferlen, dbuffer);
   279   g_free (dbuffer);
   280 
   281   switch (lbit)
   282     {
   283     case G_TEST_LOG_START_CASE:
   284       if (g_test_verbose())
   285         g_print ("GTest: run: %s\n", string1);
   286       else if (!g_test_quiet())
   287         g_print ("%s: ", string1);
   288       break;
   289     default: ;
   290     }
   291 }
   292 
   293 /* We intentionally parse the command line without GOptionContext
   294  * because otherwise you would never be able to test it.
   295  */
   296 static void
   297 parse_args (gint    *argc_p,
   298             gchar ***argv_p)
   299 {
   300   guint argc = *argc_p;
   301   gchar **argv = *argv_p;
   302   guint i, e;
   303   /* parse known args */
   304   for (i = 1; i < argc; i++)
   305     {
   306       if (strcmp (argv[i], "--g-fatal-warnings") == 0)
   307         {
   308           GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
   309           fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
   310           g_log_set_always_fatal (fatal_mask);
   311           argv[i] = NULL;
   312         }
   313       else if (strcmp (argv[i], "--keep-going") == 0 ||
   314                strcmp (argv[i], "-k") == 0)
   315         {
   316           test_mode_fatal = FALSE;
   317           argv[i] = NULL;
   318         }
   319       else if (strcmp (argv[i], "--debug-log") == 0)
   320         {
   321           test_debug_log = TRUE;
   322           argv[i] = NULL;
   323         }
   324       else if (strcmp ("--GTestLogFD", argv[i]) == 0 || strncmp ("--GTestLogFD=", argv[i], 13) == 0)
   325         {
   326           gchar *equal = argv[i] + 12;
   327           if (*equal == '=')
   328             test_log_fd = g_ascii_strtoull (equal + 1, NULL, 0);
   329           else if (i + 1 < argc)
   330             {
   331               argv[i++] = NULL;
   332               test_log_fd = g_ascii_strtoull (argv[i], NULL, 0);
   333             }
   334           argv[i] = NULL;
   335         }
   336       else if (strcmp ("--GTestSkipCount", argv[i]) == 0 || strncmp ("--GTestSkipCount=", argv[i], 17) == 0)
   337         {
   338           gchar *equal = argv[i] + 16;
   339           if (*equal == '=')
   340             test_skip_count = g_ascii_strtoull (equal + 1, NULL, 0);
   341           else if (i + 1 < argc)
   342             {
   343               argv[i++] = NULL;
   344               test_skip_count = g_ascii_strtoull (argv[i], NULL, 0);
   345             }
   346           argv[i] = NULL;
   347         }
   348       else if (strcmp ("-p", argv[i]) == 0 || strncmp ("-p=", argv[i], 3) == 0)
   349         {
   350           gchar *equal = argv[i] + 2;
   351           if (*equal == '=')
   352             test_paths = g_slist_prepend (test_paths, equal + 1);
   353           else if (i + 1 < argc)
   354             {
   355               argv[i++] = NULL;
   356               test_paths = g_slist_prepend (test_paths, argv[i]);
   357             }
   358           argv[i] = NULL;
   359         }
   360       else if (strcmp ("-m", argv[i]) == 0 || strncmp ("-m=", argv[i], 3) == 0)
   361         {
   362           gchar *equal = argv[i] + 2;
   363           const gchar *mode = "";
   364           if (*equal == '=')
   365             mode = equal + 1;
   366           else if (i + 1 < argc)
   367             {
   368               argv[i++] = NULL;
   369               mode = argv[i];
   370             }
   371           if (strcmp (mode, "perf") == 0)
   372             mutable_test_config_vars.test_perf = TRUE;
   373           else if (strcmp (mode, "slow") == 0)
   374             mutable_test_config_vars.test_quick = FALSE;
   375           else if (strcmp (mode, "thorough") == 0)
   376             mutable_test_config_vars.test_quick = FALSE;
   377           else if (strcmp (mode, "quick") == 0)
   378             {
   379               mutable_test_config_vars.test_quick = TRUE;
   380               mutable_test_config_vars.test_perf = FALSE;
   381             }
   382           else
   383             g_error ("unknown test mode: -m %s", mode);
   384           argv[i] = NULL;
   385         }
   386       else if (strcmp ("-q", argv[i]) == 0 || strcmp ("--quiet", argv[i]) == 0)
   387         {
   388           mutable_test_config_vars.test_quiet = TRUE;
   389           mutable_test_config_vars.test_verbose = FALSE;
   390           argv[i] = NULL;
   391         }
   392       else if (strcmp ("--verbose", argv[i]) == 0)
   393         {
   394           mutable_test_config_vars.test_quiet = FALSE;
   395           mutable_test_config_vars.test_verbose = TRUE;
   396           argv[i] = NULL;
   397         }
   398       else if (strcmp ("-l", argv[i]) == 0)
   399         {
   400           test_run_list = TRUE;
   401           argv[i] = NULL;
   402         }
   403       else if (strcmp ("--seed", argv[i]) == 0 || strncmp ("--seed=", argv[i], 7) == 0)
   404         {
   405           gchar *equal = argv[i] + 6;
   406           if (*equal == '=')
   407             test_run_seedstr = equal + 1;
   408           else if (i + 1 < argc)
   409             {
   410               argv[i++] = NULL;
   411               test_run_seedstr = argv[i];
   412             }
   413           argv[i] = NULL;
   414         }
   415       else if (strcmp ("-?", argv[i]) == 0 || strcmp ("--help", argv[i]) == 0)
   416         {
   417           printf ("Usage:\n"
   418                   "  %s [OPTION...]\n\n"
   419                   "Help Options:\n"
   420                   "  -?, --help                     Show help options\n"
   421                   "Test Options:\n"
   422                   "  -l                             List test cases available in a test executable\n"
   423                   "  -seed=RANDOMSEED               Provide a random seed to reproduce test\n"
   424                   "                                 runs using random numbers\n"
   425                   "  --verbose                      Run tests verbosely\n"
   426                   "  -q, --quiet                    Run tests quietly\n"
   427                   "  -p TESTPATH                    execute all tests matching TESTPATH\n"
   428                   "  -m {perf|slow|thorough|quick}  Execute tests according modes\n"
   429                   "  --debug-log                    debug test logging output\n"
   430                   "  -k, --keep-going               gtester-specific argument\n"
   431                   "  --GTestLogFD=N                 gtester-specific argument\n"
   432                   "  --GTestSkipCount=N             gtester-specific argument\n",
   433                   argv[0]);
   434           exit (0);
   435         }
   436     }
   437   /* collapse argv */
   438   e = 1;
   439   for (i = 1; i < argc; i++)
   440     if (argv[i])
   441       {
   442         argv[e++] = argv[i];
   443         if (i >= e)
   444           argv[i] = NULL;
   445       }
   446   *argc_p = e;
   447 }
   448 
   449 #if (EMULATOR)
   450 PLS_ARRAY(seedstr,g_test_init,char)
   451 #define seedstr (FUNCTION_NAME(seedstr,g_test_init)())
   452 #endif//EMULATOR
   453 
   454 /**
   455  * g_test_init:
   456  * @argc: Address of the @argc parameter of the main() function.
   457  *        Changed if any arguments were handled.
   458  * @argv: Address of the @argv parameter of main().
   459  *        Any parameters understood by g_test_init() stripped before return.
   460  * @Varargs: Reserved for future extension. Currently, you must pass %NULL.
   461  *
   462  * Initialize the GLib testing framework, e.g. by seeding the
   463  * test random number generator, the name for g_get_prgname()
   464  * and parsing test related command line args.
   465  * So far, the following arguments are understood:
   466  * <variablelist>
   467  *   <varlistentry>
   468  *     <term><option>-l</option></term>
   469  *     <listitem><para>
   470  *       list test cases available in a test executable.
   471  *     </para></listitem>
   472  *   </varlistentry>
   473  *   <varlistentry>
   474  *     <term><option>--seed=<replaceable>RANDOMSEED</replaceable></option></term>
   475  *     <listitem><para>
   476  *       provide a random seed to reproduce test runs using random numbers.
   477  *     </para></listitem>
   478  *     </varlistentry>
   479  *     <varlistentry>
   480  *       <term><option>--verbose</option></term>
   481  *       <listitem><para>run tests verbosely.</para></listitem>
   482  *     </varlistentry>
   483  *     <varlistentry>
   484  *       <term><option>-q</option>, <option>--quiet</option></term>
   485  *       <listitem><para>run tests quietly.</para></listitem>
   486  *     </varlistentry>
   487  *     <varlistentry>
   488  *       <term><option>-p <replaceable>TESTPATH</replaceable></option></term>
   489  *       <listitem><para>
   490  *         execute all tests matching <replaceable>TESTPATH</replaceable>.
   491  *       </para></listitem>
   492  *     </varlistentry>
   493  *     <varlistentry>
   494  *       <term><option>-m {perf|slow|thorough|quick}</option></term>
   495  *       <listitem><para>
   496  *         execute tests according to these test modes:
   497  *         <variablelist>
   498  *           <varlistentry>
   499  *             <term>perf</term>
   500  *             <listitem><para>
   501  *               performance tests, may take long and report results.
   502  *             </para></listitem>
   503  *           </varlistentry>
   504  *           <varlistentry>
   505  *             <term>slow, thorough</term>
   506  *             <listitem><para>
   507  *               slow and thorough tests, may take quite long and 
   508  *               maximize coverage.
   509  *             </para></listitem>
   510  *           </varlistentry>
   511  *           <varlistentry>
   512  *             <term>quick</term>
   513  *             <listitem><para>
   514  *               quick tests, should run really quickly and give good coverage.
   515  *             </para></listitem>
   516  *           </varlistentry>
   517  *         </variablelist>
   518  *       </para></listitem>
   519  *     </varlistentry>
   520  *     <varlistentry>
   521  *       <term><option>--debug-log</option></term>
   522  *       <listitem><para>debug test logging output.</para></listitem>
   523  *     </varlistentry>
   524  *     <varlistentry>
   525  *       <term><option>-k</option>, <option>--keep-going</option></term>
   526  *       <listitem><para>gtester-specific argument.</para></listitem>
   527  *     </varlistentry>
   528  *     <varlistentry>
   529  *       <term><option>--GTestLogFD <replaceable>N</replaceable></option></term>
   530  *       <listitem><para>gtester-specific argument.</para></listitem>
   531  *     </varlistentry>
   532  *     <varlistentry>
   533  *       <term><option>--GTestSkipCount <replaceable>N</replaceable></option></term>
   534  *       <listitem><para>gtester-specific argument.</para></listitem>
   535  *     </varlistentry>
   536  *  </variablelist>
   537  *
   538  * Since: 2.16
   539  */
   540 EXPORT_C void
   541 g_test_init (int    *argc,
   542              char ***argv,
   543              ...)
   544 {
   545 #if (!EMULATOR)
   546   static char seedstr[4 + 4 * 8 + 1];
   547 #endif//!EMULATOR  
   548   va_list args;
   549   gpointer vararg1;
   550   /* make warnings and criticals fatal for all test programs */
   551   GLogLevelFlags fatal_mask = (GLogLevelFlags) g_log_set_always_fatal ((GLogLevelFlags) G_LOG_FATAL_MASK);
   552   fatal_mask = (GLogLevelFlags) (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL);
   553   g_log_set_always_fatal (fatal_mask);
   554   /* check caller args */
   555   g_return_if_fail (argc != NULL);
   556   g_return_if_fail (argv != NULL);
   557   g_return_if_fail (g_test_config_vars->test_initialized == FALSE);
   558   mutable_test_config_vars.test_initialized = TRUE;
   559 
   560   va_start (args, argv);
   561   vararg1 = va_arg (args, gpointer); /* reserved for future extensions */
   562   va_end (args);
   563   g_return_if_fail (vararg1 == NULL);
   564 
   565   /* setup random seed string */
   566 #if (!EMULATOR)
   567   g_snprintf (seedstr, sizeof (seedstr), "R02S%08x%08x%08x%08x", g_random_int(), g_random_int(), g_random_int(), g_random_int());
   568 #else
   569   g_snprintf (seedstr, 37, "R02S%08x%08x%08x%08x", g_random_int(), g_random_int(), g_random_int(), g_random_int());
   570 #endif//EMULATOR
   571   test_run_seedstr = seedstr;
   572 
   573   /* parse args, sets up mode, changes seed, etc. */
   574   parse_args (argc, argv);
   575   if (!g_get_prgname())
   576     g_set_prgname ((*argv)[0]);
   577 
   578   /* verify GRand reliability, needed for reliable seeds */
   579   if (1)
   580     {
   581       GRand *rg = g_rand_new_with_seed (0xc8c49fb6);
   582       guint32 t1 = g_rand_int (rg), t2 = g_rand_int (rg), t3 = g_rand_int (rg), t4 = g_rand_int (rg);
   583       /* g_print ("GRand-current: 0x%x 0x%x 0x%x 0x%x\n", t1, t2, t3, t4); */
   584       if (t1 != 0xfab39f9b || t2 != 0xb948fb0e || t3 != 0x3d31be26 || t4 != 0x43a19d66)
   585         g_warning ("random numbers are not GRand-2.2 compatible, seeds may be broken (check $G_RANDOM_VERSION)");
   586       g_rand_free (rg);
   587     }
   588 
   589   /* check rand seed */
   590   test_run_seed (test_run_seedstr);
   591 
   592   /* report program start */
   593   g_log_set_default_handler (gtest_default_log_handler, NULL);
   594   g_test_log (G_TEST_LOG_START_BINARY, g_get_prgname(), test_run_seedstr, 0, NULL);
   595 }
   596 
   597 #if (EMULATOR)
   598 #undef seedstr
   599 #endif//EMULATOR
   600 
   601 static void
   602 test_run_seed (const gchar *rseed)
   603 {
   604   guint seed_failed = 0;
   605   if (test_run_rand)
   606     g_rand_free (test_run_rand);
   607   test_run_rand = NULL;
   608   while (strchr (" \t\v\r\n\f", *rseed))
   609     rseed++;
   610   if (strncmp (rseed, "R02S", 4) == 0)  /* seed for random generator 02 (GRand-2.2) */
   611     {
   612       const char *s = rseed + 4;
   613       if (strlen (s) >= 32)             /* require 4 * 8 chars */
   614         {
   615           guint32 seedarray[4];
   616           gchar *p, hexbuf[9] = { 0, };
   617           memcpy (hexbuf, s + 0, 8);
   618           seedarray[0] = g_ascii_strtoull (hexbuf, &p, 16);
   619           seed_failed += p != NULL && *p != 0;
   620           memcpy (hexbuf, s + 8, 8);
   621           seedarray[1] = g_ascii_strtoull (hexbuf, &p, 16);
   622           seed_failed += p != NULL && *p != 0;
   623           memcpy (hexbuf, s + 16, 8);
   624           seedarray[2] = g_ascii_strtoull (hexbuf, &p, 16);
   625           seed_failed += p != NULL && *p != 0;
   626           memcpy (hexbuf, s + 24, 8);
   627           seedarray[3] = g_ascii_strtoull (hexbuf, &p, 16);
   628           seed_failed += p != NULL && *p != 0;
   629           if (!seed_failed)
   630             {
   631               test_run_rand = g_rand_new_with_seed_array (seedarray, 4);
   632               return;
   633             }
   634         }
   635     }
   636   g_error ("Unknown or invalid random seed: %s", rseed);
   637 }
   638 
   639 /**
   640  * g_test_rand_int:
   641  *
   642  * Get a reproducible random integer number.
   643  *
   644  * The random numbers generated by the g_test_rand_*() family of functions
   645  * change with every new test program start, unless the --seed option is
   646  * given when starting test programs.
   647  *
   648  * For individual test cases however, the random number generator is
   649  * reseeded, to avoid dependencies between tests and to make --seed
   650  * effective for all test cases.
   651  *
   652  * Returns: a random number from the seeded random number generator.
   653  *
   654  * Since: 2.16
   655  */
   656 EXPORT_C gint32
   657 g_test_rand_int (void)
   658 {
   659   return g_rand_int (test_run_rand);
   660 }
   661 
   662 /**
   663  * g_test_rand_int_range:
   664  * @begin: the minimum value returned by this function
   665  * @end:   the smallest value not to be returned by this function
   666  *
   667  * Get a reproducible random integer number out of a specified range,
   668  * see g_test_rand_int() for details on test case random numbers.
   669  *
   670  * Returns: a number with @begin <= number < @end.
   671  * 
   672  * Since: 2.16
   673  */
   674 EXPORT_C gint32
   675 g_test_rand_int_range (gint32          begin,
   676                        gint32          end)
   677 {
   678   return g_rand_int_range (test_run_rand, begin, end);
   679 }
   680 
   681 /**
   682  * g_test_rand_double:
   683  *
   684  * Get a reproducible random floating point number,
   685  * see g_test_rand_int() for details on test case random numbers.
   686  *
   687  * Returns: a random number from the seeded random number generator.
   688  *
   689  * Since: 2.16
   690  */
   691 EXPORT_C double
   692 g_test_rand_double (void)
   693 {
   694   return g_rand_double (test_run_rand);
   695 }
   696 
   697 /**
   698  * g_test_rand_double_range:
   699  * @range_start: the minimum value returned by this function
   700  * @range_end: the minimum value not returned by this function
   701  *
   702  * Get a reproducible random floating pointer number out of a specified range,
   703  * see g_test_rand_int() for details on test case random numbers.
   704  *
   705  * Returns: a number with @range_start <= number < @range_end.
   706  *
   707  * Since: 2.16
   708  */
   709 EXPORT_C double
   710 g_test_rand_double_range (double          range_start,
   711                           double          range_end)
   712 {
   713   return g_rand_double_range (test_run_rand, range_start, range_end);
   714 }
   715 
   716 /**
   717  * g_test_timer_start:
   718  *
   719  * Start a timing test. Call g_test_timer_elapsed() when the task is supposed
   720  * to be done. Call this function again to restart the timer.
   721  *
   722  * Since: 2.16
   723  */
   724 EXPORT_C void
   725 g_test_timer_start (void)
   726 {
   727   if (!test_user_timer)
   728     test_user_timer = g_timer_new();
   729   test_user_stamp = 0;
   730   g_timer_start (test_user_timer);
   731 }
   732 
   733 /**
   734  * g_test_timer_elapsed:
   735  *
   736  * Get the time since the last start of the timer with g_test_timer_start().
   737  *
   738  * Returns: the time since the last start of the timer, as a double
   739  *
   740  * Since: 2.16
   741  */
   742 EXPORT_C double
   743 g_test_timer_elapsed (void)
   744 {
   745   test_user_stamp = test_user_timer ? g_timer_elapsed (test_user_timer, NULL) : 0;
   746   return test_user_stamp;
   747 }
   748 
   749 /**
   750  * g_test_timer_last:
   751  *
   752  * Report the last result of g_test_timer_elapsed().
   753  *
   754  * Returns: the last result of g_test_timer_elapsed(), as a double
   755  *
   756  * Since: 2.16
   757  */
   758 EXPORT_C double
   759 g_test_timer_last (void)
   760 {
   761   return test_user_stamp;
   762 }
   763 
   764 /**
   765  * g_test_minimized_result:
   766  * @minimized_quantity: the reported value
   767  * @format: the format string of the report message
   768  * @Varargs: arguments to pass to the printf() function
   769  *
   770  * Report the result of a performance or measurement test.
   771  * The test should generally strive to minimize the reported
   772  * quantities (smaller values are better than larger ones),
   773  * this and @minimized_quantity can determine sorting
   774  * order for test result reports.
   775  *
   776  * Since: 2.16
   777  */
   778 EXPORT_C void
   779 g_test_minimized_result (double          minimized_quantity,
   780                          const char     *format,
   781                          ...)
   782 {
   783   long double largs = minimized_quantity;
   784   gchar *buffer;
   785   va_list args;
   786   va_start (args, format);
   787   buffer = g_strdup_vprintf (format, args);
   788   va_end (args);
   789   g_test_log (G_TEST_LOG_MIN_RESULT, buffer, NULL, 1, &largs);
   790   g_free (buffer);
   791 }
   792 
   793 /**
   794  * g_test_maximized_result:
   795  * @maximized_quantity: the reported value
   796  * @format: the format string of the report message
   797  * @Varargs: arguments to pass to the printf() function
   798  *
   799  * Report the result of a performance or measurement test.
   800  * The test should generally strive to maximize the reported
   801  * quantities (larger values are better than smaller ones),
   802  * this and @maximized_quantity can determine sorting
   803  * order for test result reports.
   804  *
   805  * Since: 2.16
   806  */
   807 EXPORT_C void
   808 g_test_maximized_result (double          maximized_quantity,
   809                          const char     *format,
   810                          ...)
   811 {
   812   long double largs = maximized_quantity;
   813   gchar *buffer;
   814   va_list args;
   815   va_start (args, format);
   816   buffer = g_strdup_vprintf (format, args);
   817   va_end (args);
   818   g_test_log (G_TEST_LOG_MAX_RESULT, buffer, NULL, 1, &largs);
   819   g_free (buffer);
   820 }
   821 
   822 /**
   823  * g_test_message:
   824  * @format: the format string
   825  * @...:    printf-like arguments to @format
   826  *
   827  * Add a message to the test report.
   828  *
   829  * Since: 2.16
   830  */
   831 EXPORT_C void
   832 g_test_message (const char *format,
   833                 ...)
   834 {
   835   gchar *buffer;
   836   va_list args;
   837   va_start (args, format);
   838   buffer = g_strdup_vprintf (format, args);
   839   va_end (args);
   840   g_test_log (G_TEST_LOG_MESSAGE, buffer, NULL, 0, NULL);
   841   g_free (buffer);
   842 }
   843 
   844 /**
   845  * g_test_bug_base:
   846  * @uri_pattern: the base pattern for bug URIs
   847  *
   848  * Specify the base URI for bug reports.
   849  *
   850  * The base URI is used to construct bug report messages for
   851  * g_test_message() when g_test_bug() is called.
   852  * Calling this function outside of a test case sets the
   853  * default base URI for all test cases. Calling it from within
   854  * a test case changes the base URI for the scope of the test
   855  * case only.
   856  * Bug URIs are constructed by appending a bug specific URI
   857  * portion to @uri_pattern, or by replacing the special string
   858  * '%s' within @uri_pattern if that is present.
   859  *
   860  * Since: 2.16
   861  */
   862 EXPORT_C void
   863 g_test_bug_base (const char *uri_pattern)
   864 {
   865   g_free (test_uri_base);
   866   test_uri_base = g_strdup (uri_pattern);
   867 }
   868 
   869 /**
   870  * g_test_bug:
   871  * @bug_uri_snippet: Bug specific bug tracker URI portion.
   872  *
   873  * This function adds a message to test reports that
   874  * associates a bug URI with a test case.
   875  * Bug URIs are constructed from a base URI set with g_test_bug_base()
   876  * and @bug_uri_snippet.
   877  *
   878  * Since: 2.16
   879  */
   880 EXPORT_C void
   881 g_test_bug (const char *bug_uri_snippet)
   882 {
   883   char *c;
   884   g_return_if_fail (test_uri_base != NULL);
   885   g_return_if_fail (bug_uri_snippet != NULL);
   886   c = strstr (test_uri_base, "%s");
   887   if (c)
   888     {
   889       char *b = g_strndup (test_uri_base, c - test_uri_base);
   890       char *s = g_strconcat (b, bug_uri_snippet, c + 2, NULL);
   891       g_free (b);
   892       g_test_message ("Bug Reference: %s", s);
   893       g_free (s);
   894     }
   895   else
   896     g_test_message ("Bug Reference: %s%s", test_uri_base, bug_uri_snippet);
   897 }
   898 
   899 /**
   900  * g_test_get_root:
   901  *
   902  * Get the toplevel test suite for the test path API.
   903  *
   904  * Returns: the toplevel #GTestSuite
   905  *
   906  * Since: 2.16
   907  */
   908 EXPORT_C GTestSuite*
   909 g_test_get_root (void)
   910 {
   911   if (!test_suite_root)
   912     {
   913       test_suite_root = g_test_create_suite ("root");
   914       g_free (test_suite_root->name);
   915       test_suite_root->name = g_strdup ("");
   916     }
   917   return test_suite_root;
   918 }
   919 
   920 /**
   921  * g_test_run:
   922  *
   923  * Runs all tests under the toplevel suite which can be retrieved
   924  * with g_test_get_root(). Similar to g_test_run_suite(), the test
   925  * cases to be run are filtered according to
   926  * test path arguments (-p <replaceable>testpath</replaceable>) as 
   927  * parsed by g_test_init().
   928  * g_test_run_suite() or g_test_run() may only be called once
   929  * in a program.
   930  *
   931  * Returns: 0 on success
   932  *
   933  * Since: 2.16
   934  */
   935 EXPORT_C int
   936 g_test_run (void)
   937 {
   938   return g_test_run_suite (g_test_get_root());
   939 }
   940 
   941 /**
   942  * g_test_create_case:
   943  * @test_name:     the name for the test case
   944  * @data_size:     the size of the fixture data structure
   945  * @test_data:     test data argument for the test functions
   946  * @data_setup:    the function to set up the fixture data
   947  * @data_test:     the actual test function
   948  * @data_teardown: the function to teardown the fixture data
   949  *
   950  * Create a new #GTestCase, named @test_name, this API is fairly
   951  * low level, calling g_test_add() or g_test_add_func() is preferable.
   952  * When this test is executed, a fixture structure of size @data_size
   953  * will be allocated and filled with 0s. Then data_setup() is called
   954  * to initialize the fixture. After fixture setup, the actual test
   955  * function data_test() is called. Once the test run completed, the
   956  * fixture structure is torn down  by calling data_teardown() and
   957  * after that the memory is released.
   958  *
   959  * Splitting up a test run into fixture setup, test function and
   960  * fixture teardown is most usful if the same fixture is used for
   961  * multiple tests. In this cases, g_test_create_case() will be
   962  * called with the same fixture, but varying @test_name and
   963  * @data_test arguments.
   964  *
   965  * Returns: a newly allocated #GTestCase.
   966  *
   967  * Since: 2.16
   968  */
   969 EXPORT_C GTestCase*
   970 g_test_create_case (const char     *test_name,
   971                     gsize           data_size,
   972                     gconstpointer   test_data,
   973                     void          (*data_setup) (void),
   974                     void          (*data_test) (void),
   975                     void          (*data_teardown) (void))
   976 {
   977   GTestCase *tc;
   978   g_return_val_if_fail (test_name != NULL, NULL);
   979   g_return_val_if_fail (strchr (test_name, '/') == NULL, NULL);
   980   g_return_val_if_fail (test_name[0] != 0, NULL);
   981   g_return_val_if_fail (data_test != NULL, NULL);
   982   tc = g_slice_new0 (GTestCase);
   983   tc->name = g_strdup (test_name);
   984   tc->test_data = (gpointer) test_data;
   985   tc->fixture_size = data_size;
   986   tc->fixture_setup = (void*) data_setup;
   987   tc->fixture_test = (void*) data_test;
   988   tc->fixture_teardown = (void*) data_teardown;
   989   return tc;
   990 }
   991 
   992 EXPORT_C void
   993 g_test_add_vtable (const char     *testpath,
   994                    gsize           data_size,
   995                    gconstpointer   test_data,
   996                    void          (*data_setup)    (void),
   997                    void          (*fixture_test_func) (void),
   998                    void          (*data_teardown) (void))
   999 {
  1000   gchar **segments;
  1001   guint ui;
  1002   GTestSuite *suite;
  1003 
  1004   g_return_if_fail (testpath != NULL);
  1005   g_return_if_fail (testpath[0] == '/');
  1006   g_return_if_fail (fixture_test_func != NULL);
  1007 
  1008   suite = g_test_get_root();
  1009   segments = g_strsplit (testpath, "/", -1);
  1010   for (ui = 0; segments[ui] != NULL; ui++)
  1011     {
  1012       const char *seg = segments[ui];
  1013       gboolean islast = segments[ui + 1] == NULL;
  1014       if (islast && !seg[0])
  1015         g_error ("invalid test case path: %s", testpath);
  1016       else if (!seg[0])
  1017         continue;       /* initial or duplicate slash */
  1018       else if (!islast)
  1019         {
  1020           GTestSuite *csuite = g_test_create_suite (seg);
  1021           g_test_suite_add_suite (suite, csuite);
  1022           suite = csuite;
  1023         }
  1024       else /* islast */
  1025         {
  1026           GTestCase *tc = g_test_create_case (seg, data_size, test_data, data_setup, fixture_test_func, data_teardown);
  1027           g_test_suite_add (suite, tc);
  1028         }
  1029     }
  1030   g_strfreev (segments);
  1031 }
  1032 
  1033 /**
  1034  * g_test_add_func:
  1035  * @testpath:   Slash-separated test case path name for the test.
  1036  * @test_func:  The test function to invoke for this test.
  1037  *
  1038  * Create a new test case, similar to g_test_create_case(). However
  1039  * the test is assumed to use no fixture, and test suites are automatically
  1040  * created on the fly and added to the root fixture, based on the
  1041  * slash-separated portions of @testpath.
  1042  *
  1043  * Since: 2.16
  1044  */
  1045 EXPORT_C void
  1046 g_test_add_func (const char     *testpath,
  1047                  void          (*test_func) (void))
  1048 {
  1049   g_return_if_fail (testpath != NULL);
  1050   g_return_if_fail (testpath[0] == '/');
  1051   g_return_if_fail (test_func != NULL);
  1052   g_test_add_vtable (testpath, 0, NULL, NULL, test_func, NULL);
  1053 }
  1054 
  1055 /**
  1056  * g_test_add_data_func:
  1057  * @testpath:   Slash-separated test case path name for the test.
  1058  * @test_data:  Test data argument for the test function.
  1059  * @test_func:  The test function to invoke for this test.
  1060  *
  1061  * Create a new test case, similar to g_test_create_case(). However
  1062  * the test is assumed to use no fixture, and test suites are automatically
  1063  * created on the fly and added to the root fixture, based on the
  1064  * slash-separated portions of @testpath. The @test_data argument
  1065  * will be passed as first argument to @test_func.
  1066  *
  1067  * Since: 2.16
  1068  */
  1069 EXPORT_C void
  1070 g_test_add_data_func (const char     *testpath,
  1071                       gconstpointer   test_data,
  1072                       void          (*test_func) (gconstpointer))
  1073 {
  1074   g_return_if_fail (testpath != NULL);
  1075   g_return_if_fail (testpath[0] == '/');
  1076   g_return_if_fail (test_func != NULL);
  1077   g_test_add_vtable (testpath, 0, test_data, NULL, (void(*)(void)) test_func, NULL);
  1078 }
  1079 
  1080 /**
  1081  * g_test_create_suite:
  1082  * @suite_name: a name for the suite
  1083  *
  1084  * Create a new test suite with the name @suite_name.
  1085  *
  1086  * Returns: A newly allocated #GTestSuite instance.
  1087  *
  1088  * Since: 2.16
  1089  */
  1090 EXPORT_C GTestSuite*
  1091 g_test_create_suite (const char *suite_name)
  1092 {
  1093   GTestSuite *ts;
  1094   g_return_val_if_fail (suite_name != NULL, NULL);
  1095   g_return_val_if_fail (strchr (suite_name, '/') == NULL, NULL);
  1096   g_return_val_if_fail (suite_name[0] != 0, NULL);
  1097   ts = g_slice_new0 (GTestSuite);
  1098   ts->name = g_strdup (suite_name);
  1099   return ts;
  1100 }
  1101 
  1102 /**
  1103  * g_test_suite_add:
  1104  * @suite: a #GTestSuite
  1105  * @test_case: a #GTestCase
  1106  *
  1107  * Adds @test_case to @suite.
  1108  *
  1109  * Since: 2.16
  1110  */
  1111 EXPORT_C void
  1112 g_test_suite_add (GTestSuite     *suite,
  1113                   GTestCase      *test_case)
  1114 {
  1115   g_return_if_fail (suite != NULL);
  1116   g_return_if_fail (test_case != NULL);
  1117   suite->cases = g_slist_prepend (suite->cases, test_case);
  1118 }
  1119 
  1120 /**
  1121  * g_test_suite_add_suite:
  1122  * @suite:       a #GTestSuite
  1123  * @nestedsuite: another #GTestSuite
  1124  *
  1125  * Adds @nestedsuite to @suite.
  1126  *
  1127  * Since: 2.16
  1128  */
  1129 EXPORT_C void
  1130 g_test_suite_add_suite (GTestSuite     *suite,
  1131                         GTestSuite     *nestedsuite)
  1132 {
  1133   g_return_if_fail (suite != NULL);
  1134   g_return_if_fail (nestedsuite != NULL);
  1135   suite->suites = g_slist_prepend (suite->suites, nestedsuite);
  1136 }
  1137 
  1138 /**
  1139  * g_test_queue_free:
  1140  * @gfree_pointer: the pointer to be stored.
  1141  *
  1142  * Enqueue a pointer to be released with g_free() during the next
  1143  * teardown phase. This is equivalent to calling g_test_queue_destroy()
  1144  * with a destroy callback of g_free().
  1145  *
  1146  * Since: 2.16
  1147  */
  1148 EXPORT_C void
  1149 g_test_queue_free (gpointer gfree_pointer)
  1150 {
  1151   if (gfree_pointer)
  1152     g_test_queue_destroy (g_free, gfree_pointer);
  1153 }
  1154 
  1155 /**
  1156  * g_test_queue_destroy:
  1157  * @destroy_func:       Destroy callback for teardown phase.
  1158  * @destroy_data:       Destroy callback data.
  1159  *
  1160  * This function enqueus a callback @destroy_func() to be executed
  1161  * during the next test case teardown phase. This is most useful
  1162  * to auto destruct allocted test resources at the end of a test run.
  1163  * Resources are released in reverse queue order, that means enqueueing
  1164  * callback A before callback B will cause B() to be called before
  1165  * A() during teardown.
  1166  *
  1167  * Since: 2.16
  1168  */
  1169 EXPORT_C void
  1170 g_test_queue_destroy (GDestroyNotify destroy_func,
  1171                       gpointer       destroy_data)
  1172 {
  1173   DestroyEntry *dentry;
  1174   g_return_if_fail (destroy_func != NULL);
  1175   dentry = g_slice_new0 (DestroyEntry);
  1176   dentry->destroy_func = destroy_func;
  1177   dentry->destroy_data = destroy_data;
  1178   dentry->next = test_destroy_queue;
  1179   test_destroy_queue = dentry;
  1180 }
  1181 
  1182 static int
  1183 test_case_run (GTestCase *tc)
  1184 {
  1185   gchar *old_name = test_run_name, *old_base = g_strdup (test_uri_base);
  1186   test_run_name = g_strconcat (old_name, "/", tc->name, NULL);
  1187   if (++test_run_count <= test_skip_count)
  1188     g_test_log (G_TEST_LOG_SKIP_CASE, test_run_name, NULL, 0, NULL);
  1189   else if (test_run_list)
  1190     {
  1191       g_print ("%s\n", test_run_name);
  1192       g_test_log (G_TEST_LOG_LIST_CASE, test_run_name, NULL, 0, NULL);
  1193     }
  1194   else
  1195     {
  1196       GTimer *test_run_timer = g_timer_new();
  1197       long double largs[3];
  1198       void *fixture;
  1199       g_test_log (G_TEST_LOG_START_CASE, test_run_name, NULL, 0, NULL);
  1200       test_run_forks = 0;
  1201       g_timer_start (test_run_timer);
  1202       fixture = tc->fixture_size ? g_malloc0 (tc->fixture_size) : tc->test_data;
  1203       test_run_seed (test_run_seedstr);
  1204       if (tc->fixture_setup)
  1205         tc->fixture_setup (fixture, tc->test_data);
  1206       tc->fixture_test (fixture, tc->test_data);
  1207       test_trap_clear();
  1208       while (test_destroy_queue)
  1209         {
  1210           DestroyEntry *dentry = test_destroy_queue;
  1211           test_destroy_queue = dentry->next;
  1212           dentry->destroy_func (dentry->destroy_data);
  1213           g_slice_free (DestroyEntry, dentry);
  1214         }
  1215       if (tc->fixture_teardown)
  1216         tc->fixture_teardown (fixture, tc->test_data);
  1217       if (tc->fixture_size)
  1218         g_free (fixture);
  1219       g_timer_stop (test_run_timer);
  1220       largs[0] = 0; /* OK */
  1221       largs[1] = test_run_forks;
  1222       largs[2] = g_timer_elapsed (test_run_timer, NULL);
  1223       g_test_log (G_TEST_LOG_STOP_CASE, NULL, NULL, G_N_ELEMENTS (largs), largs);
  1224       g_timer_destroy (test_run_timer);
  1225     }
  1226   g_free (test_run_name);
  1227   test_run_name = old_name;
  1228   g_free (test_uri_base);
  1229   test_uri_base = old_base;
  1230   return 0;
  1231 }
  1232 
  1233 static int
  1234 g_test_run_suite_internal (GTestSuite *suite,
  1235                            const char *path)
  1236 {
  1237   guint n_bad = 0, n_good = 0, bad_suite = 0, l;
  1238   gchar *rest, *old_name = test_run_name;
  1239   GSList *slist, *reversed;
  1240   g_return_val_if_fail (suite != NULL, -1);
  1241   while (path[0] == '/')
  1242     path++;
  1243   l = strlen (path);
  1244   rest = strchr (path, '/');
  1245   l = rest ? MIN (l, rest - path) : l;
  1246   test_run_name = suite->name[0] == 0 ? g_strdup (test_run_name) : g_strconcat (old_name, "/", suite->name, NULL);
  1247   reversed = g_slist_reverse (g_slist_copy (suite->cases));
  1248   for (slist = reversed; slist; slist = slist->next)
  1249     {
  1250       GTestCase *tc = slist->data;
  1251       guint n = l ? strlen (tc->name) : 0;
  1252       if (l == n && strncmp (path, tc->name, n) == 0)
  1253         {
  1254           n_good++;
  1255           n_bad += test_case_run (tc) != 0;
  1256         }
  1257     }
  1258   g_slist_free (reversed);
  1259   reversed = g_slist_reverse (g_slist_copy (suite->suites));
  1260   for (slist = reversed; slist; slist = slist->next)
  1261     {
  1262       GTestSuite *ts = slist->data;
  1263       guint n = l ? strlen (ts->name) : 0;
  1264       if (l == n && strncmp (path, ts->name, n) == 0)
  1265         bad_suite += g_test_run_suite_internal (ts, rest ? rest : "") != 0;
  1266     }
  1267   g_slist_free (reversed);
  1268   g_free (test_run_name);
  1269   test_run_name = old_name;
  1270   return n_bad || bad_suite;
  1271 }
  1272 
  1273 /**
  1274  * g_test_run_suite:
  1275  * @suite: a #GTestSuite
  1276  *
  1277  * Execute the tests within @suite and all nested #GTestSuites.
  1278  * The test suites to be executed are filtered according to
  1279  * test path arguments (-p <replaceable>testpath</replaceable>) 
  1280  * as parsed by g_test_init().
  1281  * g_test_run_suite() or g_test_run() may only be called once
  1282  * in a program.
  1283  *
  1284  * Returns: 0 on success
  1285  *
  1286  * Since: 2.16
  1287  */
  1288 EXPORT_C int
  1289 g_test_run_suite (GTestSuite *suite)
  1290 {
  1291   guint n_bad = 0;
  1292   g_return_val_if_fail (g_test_config_vars->test_initialized, -1);
  1293   g_return_val_if_fail (g_test_run_once == TRUE, -1);
  1294   g_test_run_once = FALSE;
  1295   if (!test_paths)
  1296     test_paths = g_slist_prepend (test_paths, "");
  1297   while (test_paths)
  1298     {
  1299       const char *rest, *path = test_paths->data;
  1300       guint l, n = strlen (suite->name);
  1301       test_paths = g_slist_delete_link (test_paths, test_paths);
  1302       while (path[0] == '/')
  1303         path++;
  1304       if (!n) /* root suite, run unconditionally */
  1305         {
  1306           n_bad += 0 != g_test_run_suite_internal (suite, path);
  1307           continue;
  1308         }
  1309       /* regular suite, match path */
  1310       rest = strchr (path, '/');
  1311       l = strlen (path);
  1312       l = rest ? MIN (l, rest - path) : l;
  1313       if ((!l || l == n) && strncmp (path, suite->name, n) == 0)
  1314         n_bad += 0 != g_test_run_suite_internal (suite, rest ? rest : "");
  1315     }
  1316   return n_bad;
  1317 }
  1318 
  1319 static void
  1320 gtest_default_log_handler (const gchar    *log_domain,
  1321                            GLogLevelFlags  log_level,
  1322                            const gchar    *message,
  1323                            gpointer        unused_data)
  1324 {
  1325   const gchar *strv[16];
  1326   gchar *msg;
  1327   guint i = 0;
  1328   if (log_domain)
  1329     {
  1330       strv[i++] = log_domain;
  1331       strv[i++] = "-";
  1332     }
  1333   if (log_level & G_LOG_FLAG_FATAL)
  1334     strv[i++] = "FATAL-";
  1335   if (log_level & G_LOG_FLAG_RECURSION)
  1336     strv[i++] = "RECURSIVE-";
  1337   if (log_level & G_LOG_LEVEL_ERROR)
  1338     strv[i++] = "ERROR";
  1339   if (log_level & G_LOG_LEVEL_CRITICAL)
  1340     strv[i++] = "CRITICAL";
  1341   if (log_level & G_LOG_LEVEL_WARNING)
  1342     strv[i++] = "WARNING";
  1343   if (log_level & G_LOG_LEVEL_MESSAGE)
  1344     strv[i++] = "MESSAGE";
  1345   if (log_level & G_LOG_LEVEL_INFO)
  1346     strv[i++] = "INFO";
  1347   if (log_level & G_LOG_LEVEL_DEBUG)
  1348     strv[i++] = "DEBUG";
  1349   strv[i++] = ": ";
  1350   strv[i++] = message;
  1351   strv[i++] = NULL;
  1352   msg = g_strjoinv ("", (gchar**) strv);
  1353   g_test_log (G_TEST_LOG_ERROR, msg, NULL, 0, NULL);
  1354   g_log_default_handler (log_domain, log_level, message, unused_data);
  1355   g_free (msg);
  1356 }
  1357 
  1358 EXPORT_C void
  1359 g_assertion_message (const char     *domain,
  1360                      const char     *file,
  1361                      int             line,
  1362                      const char     *func,
  1363                      const char     *message)
  1364 {
  1365   char lstr[32];
  1366   char *s;
  1367   if (!message)
  1368     message = "code should not be reached";
  1369   g_snprintf (lstr, 32, "%d", line);
  1370   s = g_strconcat (domain ? domain : "", domain && domain[0] ? ":" : "",
  1371                    "ERROR:", file, ":", lstr, ":",
  1372                    func, func[0] ? ":" : "",
  1373                    " ", message, NULL);
  1374   g_printerr ("**\n%s\n", s);
  1375   g_test_log (G_TEST_LOG_ERROR, s, NULL, 0, NULL);
  1376   g_free (s);
  1377   abort();
  1378 }
  1379 
  1380 EXPORT_C void
  1381 g_assertion_message_expr (const char     *domain,
  1382                           const char     *file,
  1383                           int             line,
  1384                           const char     *func,
  1385                           const char     *expr)
  1386 {
  1387   char *s = g_strconcat ("assertion failed: (", expr, ")", NULL);
  1388   g_assertion_message (domain, file, line, func, s);
  1389   g_free (s);
  1390 }
  1391 
  1392 EXPORT_C void
  1393 g_assertion_message_cmpnum (const char     *domain,
  1394                             const char     *file,
  1395                             int             line,
  1396                             const char     *func,
  1397                             const char     *expr,
  1398                             long double     arg1,
  1399                             const char     *cmp,
  1400                             long double     arg2,
  1401                             char            numtype)
  1402 {
  1403   char *s = NULL;
  1404   switch (numtype)
  1405     {
  1406     case 'i':   s = g_strdup_printf ("assertion failed (%s): (%.0Lf %s %.0Lf)", expr, arg1, cmp, arg2); break;
  1407     case 'x':   s = g_strdup_printf ("assertion failed (%s): (0x%08" G_GINT64_MODIFIER "x %s 0x%08" G_GINT64_MODIFIER "x)", expr, (guint64) arg1, cmp, (guint64) arg2); break;
  1408     case 'f':   s = g_strdup_printf ("assertion failed (%s): (%.9Lg %s %.9Lg)", expr, arg1, cmp, arg2); break;
  1409       /* ideally use: floats=%.7g double=%.17g */
  1410     }
  1411   g_assertion_message (domain, file, line, func, s);
  1412   g_free (s);
  1413 }
  1414 
  1415 EXPORT_C void
  1416 g_assertion_message_cmpstr (const char     *domain,
  1417                             const char     *file,
  1418                             int             line,
  1419                             const char     *func,
  1420                             const char     *expr,
  1421                             const char     *arg1,
  1422                             const char     *cmp,
  1423                             const char     *arg2)
  1424 {
  1425   char *a1, *a2, *s, *t1 = NULL, *t2 = NULL;
  1426   a1 = arg1 ? g_strconcat ("\"", t1 = g_strescape (arg1, NULL), "\"", NULL) : g_strdup ("NULL");
  1427   a2 = arg2 ? g_strconcat ("\"", t2 = g_strescape (arg2, NULL), "\"", NULL) : g_strdup ("NULL");
  1428   g_free (t1);
  1429   g_free (t2);
  1430   s = g_strdup_printf ("assertion failed (%s): (%s %s %s)", expr, a1, cmp, a2);
  1431   g_free (a1);
  1432   g_free (a2);
  1433   g_assertion_message (domain, file, line, func, s);
  1434   g_free (s);
  1435 }
  1436 
  1437 EXPORT_C void
  1438 g_assertion_message_error (const char     *domain,
  1439 			   const char     *file,
  1440 			   int             line,
  1441 			   const char     *func,
  1442 			   const char     *expr,
  1443 			   GError         *error,
  1444 			   GQuark          error_domain,
  1445 			   int             error_code)
  1446 {
  1447   GString *gstring;
  1448 
  1449   /* This is used by both g_assert_error() and g_assert_no_error(), so there
  1450    * are three cases: expected an error but got the wrong error, expected
  1451    * an error but got no error, and expected no error but got an error.
  1452    */
  1453 
  1454   gstring = g_string_new ("assertion failed ");
  1455   if (error_domain)
  1456       g_string_append_printf (gstring, "(%s == (%s, %d)): ", expr,
  1457 			      g_quark_to_string (error_domain), error_code);
  1458   else
  1459     g_string_append_printf (gstring, "(%s == NULL): ", expr);
  1460 
  1461   if (error)
  1462       g_string_append_printf (gstring, "%s (%s, %d)", error->message,
  1463 			      g_quark_to_string (error->domain), error->code);
  1464   else
  1465     g_string_append_printf (gstring, "%s is NULL", expr);
  1466 
  1467   g_assertion_message (domain, file, line, func, gstring->str);
  1468   g_string_free (gstring, TRUE);
  1469 }
  1470 
  1471 /**
  1472  * g_strcmp0:
  1473  * @str1: a C string or %NULL
  1474  * @str2: another C string or %NULL
  1475  *
  1476  * Compares @str1 and @str2 like strcmp(). Handles %NULL 
  1477  * gracefully by sorting it before non-%NULL strings.
  1478  *
  1479  * Returns: -1, 0 or 1, if @str1 is <, == or > than @str2.
  1480  *
  1481  * Since: 2.16
  1482  */
  1483 EXPORT_C int
  1484 g_strcmp0 (const char     *str1,
  1485            const char     *str2)
  1486 {
  1487   if (!str1)
  1488     return -(str1 != str2);
  1489   if (!str2)
  1490     return str1 != str2;
  1491   return strcmp (str1, str2);
  1492 }
  1493 
  1494 #ifdef G_OS_UNIX
  1495 static int /* 0 on success */
  1496 kill_child (int  pid,
  1497             int *status,
  1498             int  patience)
  1499 {
  1500   int wr;
  1501   if (patience >= 3)    /* try graceful reap */
  1502     {
  1503       if (waitpid (pid, status, WNOHANG) > 0)
  1504         return 0;
  1505     }
  1506   if (patience >= 2)    /* try SIGHUP */
  1507     {
  1508       kill (pid, SIGHUP);
  1509       if (waitpid (pid, status, WNOHANG) > 0)
  1510         return 0;
  1511       g_usleep (20 * 1000); /* give it some scheduling/shutdown time */
  1512       if (waitpid (pid, status, WNOHANG) > 0)
  1513         return 0;
  1514       g_usleep (50 * 1000); /* give it some scheduling/shutdown time */
  1515       if (waitpid (pid, status, WNOHANG) > 0)
  1516         return 0;
  1517       g_usleep (100 * 1000); /* give it some scheduling/shutdown time */
  1518       if (waitpid (pid, status, WNOHANG) > 0)
  1519         return 0;
  1520     }
  1521   if (patience >= 1)    /* try SIGTERM */
  1522     {
  1523       kill (pid, SIGTERM);
  1524       if (waitpid (pid, status, WNOHANG) > 0)
  1525         return 0;
  1526       g_usleep (200 * 1000); /* give it some scheduling/shutdown time */
  1527       if (waitpid (pid, status, WNOHANG) > 0)
  1528         return 0;
  1529       g_usleep (400 * 1000); /* give it some scheduling/shutdown time */
  1530       if (waitpid (pid, status, WNOHANG) > 0)
  1531         return 0;
  1532     }
  1533   /* finish it off */
  1534   kill (pid, SIGKILL);
  1535   do
  1536     wr = waitpid (pid, status, 0);
  1537   while (wr < 0 && errno == EINTR);
  1538   return wr;
  1539 }
  1540 #endif
  1541 
  1542 static inline int
  1543 g_string_must_read (GString *gstring,
  1544                     int      fd)
  1545 {
  1546 #define STRING_BUFFER_SIZE     4096
  1547   char buf[STRING_BUFFER_SIZE];
  1548   gssize bytes;
  1549  again:
  1550   bytes = read (fd, buf, sizeof (buf));
  1551   if (bytes == 0)
  1552     return 0; /* EOF, calling this function assumes data is available */
  1553   else if (bytes > 0)
  1554     {
  1555       g_string_append_len (gstring, buf, bytes);
  1556       return 1;
  1557     }
  1558   else if (bytes < 0 && errno == EINTR)
  1559     goto again;
  1560   else /* bytes < 0 */
  1561     {
  1562       g_warning ("failed to read() from child process (%d): %s", test_trap_last_pid, g_strerror (errno));
  1563       return 1; /* ignore error after warning */
  1564     }
  1565 }
  1566 
  1567 static inline void
  1568 g_string_write_out (GString *gstring,
  1569                     int      outfd,
  1570                     int     *stringpos)
  1571 {
  1572   if (*stringpos < gstring->len)
  1573     {
  1574       int r;
  1575       do
  1576         r = write (outfd, gstring->str + *stringpos, gstring->len - *stringpos);
  1577       while (r < 0 && errno == EINTR);
  1578       *stringpos += MAX (r, 0);
  1579     }
  1580 }
  1581 
  1582 static void
  1583 test_trap_clear (void)
  1584 {
  1585   test_trap_last_status = 0;
  1586   test_trap_last_pid = 0;
  1587   g_free (test_trap_last_stdout);
  1588   test_trap_last_stdout = NULL;
  1589   g_free (test_trap_last_stderr);
  1590   test_trap_last_stderr = NULL;
  1591 }
  1592 
  1593 #ifdef G_OS_UNIX
  1594 
  1595 static int
  1596 sane_dup2 (int fd1,
  1597            int fd2)
  1598 {
  1599   int ret;
  1600   do
  1601     ret = dup2 (fd1, fd2);
  1602   while (ret < 0 && errno == EINTR);
  1603   return ret;
  1604 }
  1605 
  1606 static guint64
  1607 test_time_stamp (void)
  1608 {
  1609   GTimeVal tv;
  1610   guint64 stamp;
  1611   g_get_current_time (&tv);
  1612   stamp = tv.tv_sec;
  1613   stamp = stamp * 1000000 + tv.tv_usec;
  1614   return stamp;
  1615 }
  1616 
  1617 #endif
  1618 
  1619 /**
  1620  * g_test_trap_fork:
  1621  * @usec_timeout:    Timeout for the forked test in micro seconds.
  1622  * @test_trap_flags: Flags to modify forking behaviour.
  1623  *
  1624  * Fork the current test program to execute a test case that might
  1625  * not return or that might abort. The forked test case is aborted
  1626  * and considered failing if its run time exceeds @usec_timeout.
  1627  *
  1628  * The forking behavior can be configured with the #GTestTrapFlags flags.
  1629  *
  1630  * In the following example, the test code forks, the forked child
  1631  * process produces some sample output and exits successfully.
  1632  * The forking parent process then asserts successful child program
  1633  * termination and validates child program outputs.
  1634  *
  1635  * |[
  1636  *   static void
  1637  *   test_fork_patterns (void)
  1638  *   {
  1639  *     if (g_test_trap_fork (0, G_TEST_TRAP_SILENCE_STDOUT | G_TEST_TRAP_SILENCE_STDERR))
  1640  *       {
  1641  *         g_print ("some stdout text: somagic17\n");
  1642  *         g_printerr ("some stderr text: semagic43\n");
  1643  *         exit (0); /&ast; successful test run &ast;/
  1644  *       }
  1645  *     g_test_trap_assert_passed();
  1646  *     g_test_trap_assert_stdout ("*somagic17*");
  1647  *     g_test_trap_assert_stderr ("*semagic43*");
  1648  *   }
  1649  * ]|
  1650  *
  1651  * This function is implemented only on Unix platforms.
  1652  *
  1653  * Returns: %TRUE for the forked child and %FALSE for the executing parent process.
  1654  *
  1655  * Since: 2.16
  1656  */
  1657 EXPORT_C gboolean
  1658 g_test_trap_fork (guint64        usec_timeout,
  1659                   GTestTrapFlags test_trap_flags)
  1660 {
  1661 #ifdef G_OS_UNIX
  1662   gboolean pass_on_forked_log = FALSE;
  1663   int stdout_pipe[2] = { -1, -1 };
  1664   int stderr_pipe[2] = { -1, -1 };
  1665   int stdtst_pipe[2] = { -1, -1 };
  1666   test_trap_clear();
  1667   if (pipe (stdout_pipe) < 0 || pipe (stderr_pipe) < 0 || pipe (stdtst_pipe) < 0)
  1668     g_error ("failed to create pipes to fork test program: %s", g_strerror (errno));
  1669 #if defined (__SYMBIAN32__) && defined(SYMBIAN_OE_POSIX_SIGNALS)
  1670   signal (SIGCHLD, SIG_DFL);
  1671 #endif //defined (__SYMBIAN32__) && defined(SYMBIAN_OE_POSIX_SIGNALS)
  1672 #ifndef __SYMBIAN32__
  1673   test_trap_last_pid = fork ();//replace with popen3()
  1674 #endif//__SYMBIAN32__  
  1675   if (test_trap_last_pid < 0)
  1676     g_error ("failed to fork test program: %s", g_strerror (errno));
  1677   if (test_trap_last_pid == 0)  /* child */
  1678     {
  1679       int fd0 = -1;
  1680       close (stdout_pipe[0]);
  1681       close (stderr_pipe[0]);
  1682       close (stdtst_pipe[0]);
  1683       if (!(test_trap_flags & G_TEST_TRAP_INHERIT_STDIN))
  1684         fd0 = open ("/dev/null", O_RDONLY);
  1685       if (sane_dup2 (stdout_pipe[1], 1) < 0 || sane_dup2 (stderr_pipe[1], 2) < 0 || (fd0 >= 0 && sane_dup2 (fd0, 0) < 0))
  1686         g_error ("failed to dup2() in forked test program: %s", g_strerror (errno));
  1687       if (fd0 >= 3)
  1688         close (fd0);
  1689       if (stdout_pipe[1] >= 3)
  1690         close (stdout_pipe[1]);
  1691       if (stderr_pipe[1] >= 3)
  1692         close (stderr_pipe[1]);
  1693       test_log_fd = stdtst_pipe[1];
  1694       return TRUE;
  1695     }
  1696   else                          /* parent */
  1697     {
  1698       GString *sout = g_string_new (NULL);
  1699       GString *serr = g_string_new (NULL);
  1700       guint64 sstamp;
  1701       int soutpos = 0, serrpos = 0, wr, need_wait = TRUE;
  1702       test_run_forks++;
  1703       close (stdout_pipe[1]);
  1704       close (stderr_pipe[1]);
  1705       close (stdtst_pipe[1]);
  1706       sstamp = test_time_stamp();
  1707       /* read data until we get EOF on all pipes */
  1708       while (stdout_pipe[0] >= 0 || stderr_pipe[0] >= 0 || stdtst_pipe[0] > 0)
  1709         {
  1710           fd_set fds;
  1711           struct timeval tv;
  1712           int ret;
  1713           FD_ZERO (&fds);
  1714           if (stdout_pipe[0] >= 0)
  1715             FD_SET (stdout_pipe[0], &fds);
  1716           if (stderr_pipe[0] >= 0)
  1717             FD_SET (stderr_pipe[0], &fds);
  1718           if (stdtst_pipe[0] >= 0)
  1719             FD_SET (stdtst_pipe[0], &fds);
  1720           tv.tv_sec = 0;
  1721           tv.tv_usec = MIN (usec_timeout ? usec_timeout : 1000000, 100 * 1000); /* sleep at most 0.5 seconds to catch clock skews, etc. */
  1722           ret = select (MAX (MAX (stdout_pipe[0], stderr_pipe[0]), stdtst_pipe[0]) + 1, &fds, NULL, NULL, &tv);
  1723           if (ret < 0 && errno != EINTR)
  1724             {
  1725               g_warning ("Unexpected error in select() while reading from child process (%d): %s", test_trap_last_pid, g_strerror (errno));
  1726               break;
  1727             }
  1728           if (stdout_pipe[0] >= 0 && FD_ISSET (stdout_pipe[0], &fds) &&
  1729               g_string_must_read (sout, stdout_pipe[0]) == 0)
  1730             {
  1731               close (stdout_pipe[0]);
  1732               stdout_pipe[0] = -1;
  1733             }
  1734           if (stderr_pipe[0] >= 0 && FD_ISSET (stderr_pipe[0], &fds) &&
  1735               g_string_must_read (serr, stderr_pipe[0]) == 0)
  1736             {
  1737               close (stderr_pipe[0]);
  1738               stderr_pipe[0] = -1;
  1739             }
  1740           if (stdtst_pipe[0] >= 0 && FD_ISSET (stdtst_pipe[0], &fds))
  1741             {
  1742               guint8 buffer[4096];
  1743               gint l, r = read (stdtst_pipe[0], buffer, sizeof (buffer));
  1744               if (r > 0 && test_log_fd > 0)
  1745                 do
  1746                   l = write (pass_on_forked_log ? test_log_fd : -1, buffer, r);
  1747                 while (l < 0 && errno == EINTR);
  1748               if (r == 0 || (r < 0 && errno != EINTR && errno != EAGAIN))
  1749                 {
  1750                   close (stdtst_pipe[0]);
  1751                   stdtst_pipe[0] = -1;
  1752                 }
  1753             }
  1754           if (!(test_trap_flags & G_TEST_TRAP_SILENCE_STDOUT))
  1755             g_string_write_out (sout, 1, &soutpos);
  1756           if (!(test_trap_flags & G_TEST_TRAP_SILENCE_STDERR))
  1757             g_string_write_out (serr, 2, &serrpos);
  1758           if (usec_timeout)
  1759             {
  1760               guint64 nstamp = test_time_stamp();
  1761               int status = 0;
  1762               sstamp = MIN (sstamp, nstamp); /* guard against backwards clock skews */
  1763               if (usec_timeout < nstamp - sstamp)
  1764                 {
  1765                   /* timeout reached, need to abort the child now */
  1766                   kill_child (test_trap_last_pid, &status, 3);
  1767                   test_trap_last_status = 1024; /* timeout */
  1768                   if (0 && WIFSIGNALED (status))
  1769                     g_printerr ("%s: child timed out and received: %s\n", G_STRFUNC, g_strsignal (WTERMSIG (status)));
  1770                   need_wait = FALSE;
  1771                   break;
  1772                 }
  1773             }
  1774         }
  1775       close (stdout_pipe[0]);
  1776       close (stderr_pipe[0]);
  1777       close (stdtst_pipe[0]);
  1778       if (need_wait)
  1779         {
  1780           int status = 0;
  1781           do
  1782             wr = waitpid (test_trap_last_pid, &status, 0);
  1783           while (wr < 0 && errno == EINTR);
  1784           if (WIFEXITED (status)) /* normal exit */
  1785             test_trap_last_status = WEXITSTATUS (status); /* 0..255 */
  1786           else if (WIFSIGNALED (status))
  1787             test_trap_last_status = (WTERMSIG (status) << 12); /* signalled */
  1788           else /* WCOREDUMP (status) */
  1789             test_trap_last_status = 512; /* coredump */
  1790         }
  1791       test_trap_last_stdout = g_string_free (sout, FALSE);
  1792       test_trap_last_stderr = g_string_free (serr, FALSE);
  1793       return FALSE;
  1794     }
  1795 #else
  1796   g_message ("Not implemented: g_test_trap_fork");
  1797 
  1798   return FALSE;
  1799 #endif
  1800 }
  1801 
  1802 /**
  1803  * g_test_trap_has_passed:
  1804  *
  1805  * Check the result of the last g_test_trap_fork() call.
  1806  *
  1807  * Returns: %TRUE if the last forked child terminated successfully.
  1808  *
  1809  * Since: 2.16
  1810  */
  1811 EXPORT_C gboolean
  1812 g_test_trap_has_passed (void)
  1813 {
  1814   return test_trap_last_status == 0; /* exit_status == 0 && !signal && !coredump */
  1815 }
  1816 
  1817 /**
  1818  * g_test_trap_reached_timeout:
  1819  *
  1820  * Check the result of the last g_test_trap_fork() call.
  1821  *
  1822  * Returns: %TRUE if the last forked child got killed due to a fork timeout.
  1823  *
  1824  * Since: 2.16
  1825  */
  1826 EXPORT_C gboolean
  1827 g_test_trap_reached_timeout (void)
  1828 {
  1829   return 0 != (test_trap_last_status & 1024); /* timeout flag */
  1830 }
  1831 
  1832 EXPORT_C void
  1833 g_test_trap_assertions (const char     *domain,
  1834                         const char     *file,
  1835                         int             line,
  1836                         const char     *func,
  1837                         guint64         assertion_flags, /* 0-pass, 1-fail, 2-outpattern, 4-errpattern */
  1838                         const char     *pattern)
  1839 {
  1840 #ifdef G_OS_UNIX
  1841   gboolean must_pass = assertion_flags == 0;
  1842   gboolean must_fail = assertion_flags == 1;
  1843   gboolean match_result = 0 == (assertion_flags & 1);
  1844   const char *stdout_pattern = (assertion_flags & 2) ? pattern : NULL;
  1845   const char *stderr_pattern = (assertion_flags & 4) ? pattern : NULL;
  1846   const char *match_error = match_result ? "failed to match" : "contains invalid match";
  1847   if (test_trap_last_pid == 0)
  1848     g_error ("child process failed to exit after g_test_trap_fork() and before g_test_trap_assert*()");
  1849   if (must_pass && !g_test_trap_has_passed())
  1850     {
  1851       char *msg = g_strdup_printf ("child process (%d) of test trap failed unexpectedly", test_trap_last_pid);
  1852       g_assertion_message (domain, file, line, func, msg);
  1853       g_free (msg);
  1854     }
  1855   if (must_fail && g_test_trap_has_passed())
  1856     {
  1857       char *msg = g_strdup_printf ("child process (%d) did not fail as expected", test_trap_last_pid);
  1858       g_assertion_message (domain, file, line, func, msg);
  1859       g_free (msg);
  1860     }
  1861   if (stdout_pattern && match_result == !g_pattern_match_simple (stdout_pattern, test_trap_last_stdout))
  1862     {
  1863       char *msg = g_strdup_printf ("stdout of child process (%d) %s: %s", test_trap_last_pid, match_error, stdout_pattern);
  1864       g_assertion_message (domain, file, line, func, msg);
  1865       g_free (msg);
  1866     }
  1867   if (stderr_pattern && match_result == !g_pattern_match_simple (stderr_pattern, test_trap_last_stderr))
  1868     {
  1869       char *msg = g_strdup_printf ("stderr of child process (%d) %s: %s", test_trap_last_pid, match_error, stderr_pattern);
  1870       g_assertion_message (domain, file, line, func, msg);
  1871       g_free (msg);
  1872     }
  1873 #endif
  1874 }
  1875 
  1876 static void
  1877 gstring_overwrite_int (GString *gstring,
  1878                        guint    pos,
  1879                        guint32  vuint)
  1880 {
  1881   vuint = g_htonl (vuint);
  1882   g_string_overwrite_len (gstring, pos, (const gchar*) &vuint, 4);
  1883 }
  1884 
  1885 static void
  1886 gstring_append_int (GString *gstring,
  1887                     guint32  vuint)
  1888 {
  1889   vuint = g_htonl (vuint);
  1890   g_string_append_len (gstring, (const gchar*) &vuint, 4);
  1891 }
  1892 
  1893 static void
  1894 gstring_append_double (GString *gstring,
  1895                        double   vdouble)
  1896 {
  1897   union { double vdouble; guint64 vuint64; } u;
  1898   u.vdouble = vdouble;
  1899   u.vuint64 = GUINT64_TO_BE (u.vuint64);
  1900   g_string_append_len (gstring, (const gchar*) &u.vuint64, 8);
  1901 }
  1902 
  1903 static guint8*
  1904 g_test_log_dump (GTestLogMsg *msg,
  1905                  guint       *len)
  1906 {
  1907   GString *gstring = g_string_sized_new (1024);
  1908   guint ui;
  1909   gstring_append_int (gstring, 0);              /* message length */
  1910   gstring_append_int (gstring, msg->log_type);
  1911   gstring_append_int (gstring, msg->n_strings);
  1912   gstring_append_int (gstring, msg->n_nums);
  1913   gstring_append_int (gstring, 0);      /* reserved */
  1914   for (ui = 0; ui < msg->n_strings; ui++)
  1915     {
  1916       guint l = strlen (msg->strings[ui]);
  1917       gstring_append_int (gstring, l);
  1918       g_string_append_len (gstring, msg->strings[ui], l);
  1919     }
  1920   for (ui = 0; ui < msg->n_nums; ui++)
  1921     gstring_append_double (gstring, msg->nums[ui]);
  1922   *len = gstring->len;
  1923   gstring_overwrite_int (gstring, 0, *len);     /* message length */
  1924   return (guint8*) g_string_free (gstring, FALSE);
  1925 }
  1926 
  1927 static inline long double
  1928 net_double (const gchar **ipointer)
  1929 {
  1930   union { guint64 vuint64; double vdouble; } u;
  1931   guint64 aligned_int64;
  1932   memcpy (&aligned_int64, *ipointer, 8);
  1933   *ipointer += 8;
  1934   u.vuint64 = GUINT64_FROM_BE (aligned_int64);
  1935   return u.vdouble;
  1936 }
  1937 
  1938 static inline guint32
  1939 net_int (const gchar **ipointer)
  1940 {
  1941   guint32 aligned_int;
  1942   memcpy (&aligned_int, *ipointer, 4);
  1943   *ipointer += 4;
  1944   return g_ntohl (aligned_int);
  1945 }
  1946 
  1947 static gboolean
  1948 g_test_log_extract (GTestLogBuffer *tbuffer)
  1949 {
  1950   const gchar *p = tbuffer->data->str;
  1951   GTestLogMsg msg;
  1952   guint mlength;
  1953   if (tbuffer->data->len < 4 * 5)
  1954     return FALSE;
  1955   mlength = net_int (&p);
  1956   if (tbuffer->data->len < mlength)
  1957     return FALSE;
  1958   msg.log_type = net_int (&p);
  1959   msg.n_strings = net_int (&p);
  1960   msg.n_nums = net_int (&p);
  1961   if (net_int (&p) == 0)
  1962     {
  1963       guint ui;
  1964       msg.strings = g_new0 (gchar*, msg.n_strings + 1);
  1965       msg.nums = g_new0 (long double, msg.n_nums);
  1966       for (ui = 0; ui < msg.n_strings; ui++)
  1967         {
  1968           guint sl = net_int (&p);
  1969           msg.strings[ui] = g_strndup (p, sl);
  1970           p += sl;
  1971         }
  1972       for (ui = 0; ui < msg.n_nums; ui++)
  1973         msg.nums[ui] = net_double (&p);
  1974       if (p <= tbuffer->data->str + mlength)
  1975         {
  1976           g_string_erase (tbuffer->data, 0, mlength);
  1977           tbuffer->msgs = g_slist_prepend (tbuffer->msgs, g_memdup (&msg, sizeof (msg)));
  1978           return TRUE;
  1979         }
  1980     }
  1981   g_free (msg.nums);
  1982   g_strfreev (msg.strings);
  1983   g_error ("corrupt log stream from test program");
  1984   return FALSE;
  1985 }
  1986 
  1987 /**
  1988  * g_test_log_buffer_new:
  1989  *
  1990  * Internal function for gtester to decode test log messages, no ABI guarantees provided.
  1991  */
  1992 EXPORT_C GTestLogBuffer*
  1993 g_test_log_buffer_new (void)
  1994 {
  1995   GTestLogBuffer *tb = g_new0 (GTestLogBuffer, 1);
  1996   tb->data = g_string_sized_new (1024);
  1997   return tb;
  1998 }
  1999 
  2000 /**
  2001  * g_test_log_buffer_free
  2002  *
  2003  * Internal function for gtester to free test log messages, no ABI guarantees provided.
  2004  */
  2005 EXPORT_C void
  2006 g_test_log_buffer_free (GTestLogBuffer *tbuffer)
  2007 {
  2008   g_return_if_fail (tbuffer != NULL);
  2009   while (tbuffer->msgs)
  2010     g_test_log_msg_free (g_test_log_buffer_pop (tbuffer));
  2011   g_string_free (tbuffer->data, TRUE);
  2012   g_free (tbuffer);
  2013 }
  2014 
  2015 /**
  2016  * g_test_log_buffer_push
  2017  *
  2018  * Internal function for gtester to decode test log messages, no ABI guarantees provided.
  2019  */
  2020 EXPORT_C void
  2021 g_test_log_buffer_push (GTestLogBuffer *tbuffer,
  2022                         guint           n_bytes,
  2023                         const guint8   *bytes)
  2024 {
  2025   g_return_if_fail (tbuffer != NULL);
  2026   if (n_bytes)
  2027     {
  2028       gboolean more_messages;
  2029       g_return_if_fail (bytes != NULL);
  2030       g_string_append_len (tbuffer->data, (const gchar*) bytes, n_bytes);
  2031       do
  2032         more_messages = g_test_log_extract (tbuffer);
  2033       while (more_messages);
  2034     }
  2035 }
  2036 
  2037 /**
  2038  * g_test_log_buffer_pop:
  2039  *
  2040  * Internal function for gtester to retrieve test log messages, no ABI guarantees provided.
  2041  */
  2042 EXPORT_C GTestLogMsg*
  2043 g_test_log_buffer_pop (GTestLogBuffer *tbuffer)
  2044 {
  2045   GTestLogMsg *msg = NULL;
  2046   g_return_val_if_fail (tbuffer != NULL, NULL);
  2047   if (tbuffer->msgs)
  2048     {
  2049       GSList *slist = g_slist_last (tbuffer->msgs);
  2050       msg = slist->data;
  2051       tbuffer->msgs = g_slist_delete_link (tbuffer->msgs, slist);
  2052     }
  2053   return msg;
  2054 }
  2055 
  2056 /**
  2057  * g_test_log_msg_free:
  2058  *
  2059  * Internal function for gtester to free test log messages, no ABI guarantees provided.
  2060  */
  2061 EXPORT_C void
  2062 g_test_log_msg_free (GTestLogMsg *tmsg)
  2063 {
  2064   g_return_if_fail (tmsg != NULL);
  2065   g_strfreev (tmsg->strings);
  2066   g_free (tmsg->nums);
  2067   g_free (tmsg);
  2068 }
  2069 
  2070 /* --- macros docs START --- */
  2071 /**
  2072  * g_test_add:
  2073  * @testpath:  The test path for a new test case.
  2074  * @Fixture:   The type of a fixture data structure.
  2075  * @tdata:     Data argument for the test functions.
  2076  * @fsetup:    The function to set up the fixture data.
  2077  * @ftest:     The actual test function.
  2078  * @fteardown: The function to tear down the fixture data.
  2079  *
  2080  * Hook up a new test case at @testpath, similar to g_test_add_func().
  2081  * A fixture data structure with setup and teardown function may be provided
  2082  * though, similar to g_test_create_case().
  2083  * g_test_add() is implemented as a macro, so that the fsetup(), ftest() and
  2084  * fteardown() callbacks can expect a @Fixture pointer as first argument in
  2085  * a type safe manner.
  2086  *
  2087  * Since: 2.16
  2088  **/
  2089 /* --- macros docs END --- */
  2090 
  2091 #define __G_TEST_UTILS_C__
  2092 #include "galiasdef.c"