示例#1
0
文件: pposix.c 项目: Chingliu/prosody
int lc_meminfo(lua_State* L)
{
	struct mallinfo info = mallinfo();
	lua_newtable(L);
	/* This is the total size of memory allocated with sbrk by malloc, in bytes. */
	lua_pushinteger(L, info.arena);
	lua_setfield(L, -2, "allocated");
	/* This is the total size of memory allocated with mmap, in bytes. */
	lua_pushinteger(L, info.hblkhd);
	lua_setfield(L, -2, "allocated_mmap");
	/* This is the total size of memory occupied by chunks handed out by malloc. */
	lua_pushinteger(L, info.uordblks);
	lua_setfield(L, -2, "used");
	/* This is the total size of memory occupied by free (not in use) chunks. */
	lua_pushinteger(L, info.fordblks);
	lua_setfield(L, -2, "unused");
	/* This is the size of the top-most releasable chunk that normally borders the
	   end of the heap (i.e., the high end of the virtual address space's data segment). */
	lua_pushinteger(L, info.keepcost);
	lua_setfield(L, -2, "returnable");
	return 1;
}
示例#2
0
void print_resource_track(const char *desc, struct resource_track *track)
{
#ifdef HAVE_GETRUSAGE
	struct rusage r;
#endif
#ifdef HAVE_MALLINFO
	struct mallinfo	malloc_info;
#endif
	struct timeval time_end;

	gettimeofday(&time_end, 0);

	if (desc)
		printf("%s: ", desc);

#ifdef HAVE_MALLINFO
#define kbytes(x)	(((x) + 1023) / 1024)
	
	malloc_info = mallinfo();
	printf(_("Memory used: %dk/%dk (%dk/%dk), "),
	       kbytes(malloc_info.arena), kbytes(malloc_info.hblkhd),
	       kbytes(malloc_info.uordblks), kbytes(malloc_info.fordblks));
#else
	printf(_("Memory used: %d, "),
	       (int) (((char *) sbrk(0)) - ((char *) track->brk_start)));
#endif	
#ifdef HAVE_GETRUSAGE
	getrusage(RUSAGE_SELF, &r);

	printf(_("time: %5.2f/%5.2f/%5.2f\n"),
	       timeval_subtract(&time_end, &track->time_start),
	       timeval_subtract(&r.ru_utime, &track->user_start),
	       timeval_subtract(&r.ru_stime, &track->system_start));
#else
	printf(_("elapsed time: %6.3f\n"),
	       timeval_subtract(&time_end, &track->time_start));
#endif
}
示例#3
0
static int
show_memory_mallinfo (struct vty *vty)
{
  struct mallinfo minfo = mallinfo();
  char buf[MTYPE_MEMSTR_LEN];
  
  vty_out (vty, "System allocator statistics:%s", VTY_NEWLINE);
  vty_out (vty, "  Total heap allocated:  %s%s",
           mtype_memstr (buf, MTYPE_MEMSTR_LEN, minfo.arena),
           VTY_NEWLINE);
  vty_out (vty, "  Holding block headers: %s%s",
           mtype_memstr (buf, MTYPE_MEMSTR_LEN, minfo.hblkhd),
           VTY_NEWLINE);
  vty_out (vty, "  Used small blocks:     %s%s",
           mtype_memstr (buf, MTYPE_MEMSTR_LEN, minfo.usmblks),
           VTY_NEWLINE);
  vty_out (vty, "  Used ordinary blocks:  %s%s",
           mtype_memstr (buf, MTYPE_MEMSTR_LEN, minfo.uordblks),
           VTY_NEWLINE);
  vty_out (vty, "  Free small blocks:     %s%s",
           mtype_memstr (buf, MTYPE_MEMSTR_LEN, minfo.fsmblks),
           VTY_NEWLINE);
  vty_out (vty, "  Free ordinary blocks:  %s%s",
           mtype_memstr (buf, MTYPE_MEMSTR_LEN, minfo.fordblks),
           VTY_NEWLINE);
  vty_out (vty, "  Ordinary blocks:       %ld%s",
           (unsigned long)minfo.ordblks,
           VTY_NEWLINE);
  vty_out (vty, "  Small blocks:          %ld%s",
           (unsigned long)minfo.smblks,
           VTY_NEWLINE);
  vty_out (vty, "  Holding blocks:        %ld%s",
           (unsigned long)minfo.hblks,
           VTY_NEWLINE);
  vty_out (vty, "(see system documentation for 'mallinfo' for meaning)%s",
           VTY_NEWLINE);
  return 1;
}
void TestMallocPrivate::init()
{
    /*
        When using glibc malloc, this function will be called before any heap allocation.
        When using other malloc and when running under valgrind, we might get called after
        some heap allocation.
    */
    struct mallinfo info = mallinfo();
    static TestMallocPrivate testmalloc;
    testmalloc.now_usable.store(info.uordblks);
    testmalloc.now_overhead.store(0); /* cannot get this figure, but should be close to 0. */
    TestMalloc::resetPeak();
    testmalloc.selftest();

    /* Turn off mmap so that all blocks have a fixed overhead. */
    mallopt(M_MMAP_MAX, 0);

#ifdef TEST_TESTMALLOC
    __after_morecore_hook = &TestMallocPrivate::afterMorecore;
    mallopt(M_TRIM_THRESHOLD, 0);
    mallopt(M_TOP_PAD, 0);
#endif
}
示例#5
0
int handle_meminfo_command(struct command_context_s *cmd_ctx, char *cmd, char **args, int argc)
{
	static int prev = 0;
	struct mallinfo info;

	if (argc != 0)
	{
		command_print(cmd_ctx, "meminfo");
		return ERROR_INVALID_ARGUMENTS;
	}

	info = mallinfo();

	if (prev > 0)
	{
		command_print(cmd_ctx, "Diff:            %d", prev - info.fordblks);
	}
	prev = info.fordblks;

	command_print(cmd_ctx, "Available ram:   %d", info.fordblks );

	return ERROR_OK;
}
示例#6
0
int mac_selinux_init(const char *prefix) {
        int r = 0;

#ifdef HAVE_SELINUX
        usec_t before_timestamp, after_timestamp;
        struct mallinfo before_mallinfo, after_mallinfo;

        if (!mac_selinux_use())
                return 0;

        if (label_hnd)
                return 0;

        before_mallinfo = mallinfo();
        before_timestamp = now(CLOCK_MONOTONIC);

        if (prefix) {
                struct selinux_opt options[] = {
                        { .type = SELABEL_OPT_SUBSET, .value = prefix },
                };

                label_hnd = selabel_open(SELABEL_CTX_FILE, options, ELEMENTSOF(options));
        } else
示例#7
0
文件: info.c 项目: jimmyskull/Wooki
void meminfo(void) {
    struct mallinfo info = mallinfo();

    out(_("%sMemory Info%s\n"), CC_BOLD, CC_RESTORE);
    out(_("\t%sTotal bytes allocated%s: %i bytes "),
        CC_BOLD, CC_RESTORE, info.arena);
    print_memsize(info.arena);
    out(_("\t%sChunks not being used%s: %i\n"),
        CC_BOLD, CC_RESTORE, info.ordblks);
    out(_("\t%sNumber of chunks allocated with mmap%s: %i\n"),
        CC_BOLD, CC_RESTORE, info.hblks);
    out(_("\t%sSize of chunks allocated with mmap%s: %i bytes"),
        CC_BOLD, CC_RESTORE, info.hblkhd);
    print_memsize(info.hblkhd);
    out(_("\t%sTotal allocated with malloc%s: %i bytes"),
        CC_BOLD, CC_RESTORE, info.uordblks);
    print_memsize(info.uordblks);
    out(_("\t%sTotal memory not in use%s: %i bytes"),
        CC_BOLD, CC_RESTORE, info.fordblks);
    print_memsize(info.fordblks);
    out(_("\t%sTop-most releasable chunk size%s: %i bytes\n"),
        CC_BOLD, CC_RESTORE, info.keepcost);
}
示例#8
0
static void print_mstats() {
#ifdef __APPLE__
    struct mstats ms = mstats();
    printf( "Malloc statistics:\n"
            "\tms.bytes_free=%d\n"
            "\tms.bytes_total=%d\n"
            "\tms.bytes_used=%d\n"""
            "\tms.chunks_used=%d\n"
            "\tms.chunks_free=%d\n",
            ms.bytes_free, ms.bytes_total, ms.bytes_used, ms.chunks_used, ms.chunks_free);
#else
        struct mallinfo mi = mallinfo();
        printf( "Malloc statistics:\n"
                "\tarena %d\n"
                "\tordblks %d\n"
                "\tsmblks %d\n"
                "\thblks %d\n"
                "\thblkhd %d\n"
                "\tusmblks %d\n"
                "\tfsmblks %d\n"
                "\tuordblks %d\n"
                "\tfordblks %d\n"
                "\tkeepcost %d\n",
                mi.arena,
                mi.ordblks,
                mi.smblks,
                mi.hblks,
                mi.hblkhd,
                mi.usmblks,
                mi.fsmblks,
                mi.uordblks,
                mi.fordblks,
                mi.keepcost
                );

#endif
}
示例#9
0
/*ad*
 * This function returns a filled-in structure with current
 * statistics on heap allocations.
 * The underlying structure and prototypes are in malloc.h
 * This is supported only in the GNU environment.
 *
 * @external
 * @include "appconf_api.h"
 * @category SystemSWServices:general_purpose
 * @since 7.4
 *
 * @param  pMS		pointer to structure to fill in
 * @return rc       0 for success, non-zero for failure
 *
 * @see @link SystemSWServices:general_purpose:NABspMallocStats
 *
*ad*/
int NABspGetHeapSnapshot(NABspMallocStats * pMS)
{
#ifdef	__GNUC__
	extern char end asm ("__end__");
	extern char  heap_limit[];
	extern unsigned long heap_adjustment;
	struct mallinfo Info;
	int rc = 0;

	Info = mallinfo();

	pMS->system = heap_limit - &end + heap_adjustment,
	pMS->arena = Info.arena;
   	pMS->ordblks = Info.ordblks;
   	pMS->hblks = Info.hblks;
	pMS->hblkhd = Info.hblkhd;
   	pMS->uordblks = Info.uordblks;
	pMS->fordblks = Info.fordblks;
   	pMS->keepcost = Info.keepcost;
#else
	int rc = 0;
#endif
	return rc;
}
示例#10
0
void stats(char *msg)
{
#if defined(HAVE_MALLINFO)
  struct mallinfo mallinfo_result;
  mallinfo_result = mallinfo();
#endif

  /* from /usr/include/malloc.h */
  printf("%s\n", msg);

#if defined(HAVE_MALLINFO)
  printf("%10d int arena;    /* non-mmapped space allocated from system */\n", mallinfo_result.arena);
  printf("%10d int ordblks;  /* number of free chunks */\n", mallinfo_result.ordblks);
  printf("%10d int smblks;   /* number of fastbin blocks */\n", mallinfo_result.smblks);
  printf("%10d int hblks;    /* number of mmapped regions */\n", mallinfo_result.hblks);
  printf("%10d int hblkhd;   /* space in mmapped regions */\n", mallinfo_result.hblkhd);
  printf("%10d int usmblks;  /* maximum total allocated space */\n", mallinfo_result.usmblks);
  printf("%10d int fsmblks;  /* space available in freed fastbin blocks */\n", mallinfo_result.fsmblks);
  printf("%10d int uordblks; /* total allocated space */\n", mallinfo_result.uordblks);
  printf("%10d int fordblks; /* total free space */\n", mallinfo_result.fordblks);
  printf("%10d int keepcost; /* top-most, releasable (via malloc_trim) space */\n", mallinfo_result.keepcost);
  printf("\n");
#endif
}
示例#11
0
static void benchmark_save(const char *name) {
    struct mallinfo info;
    int             i;

    i = find_benchmark(name);
    if (i == NOT_FOUND) {
        if (bm.count == MAX_BENCHMARKS) {
            error(_("Reached maximum of benchmarks\n"));
            return;
        }
        i = bm.count++;
        {
            struct benchmark_data    *nbm;

            nbm = TALLOC(struct benchmark_data);
            bm.list[i] = nbm;
            strcpy(bm.list[i]->name, name);
        }
    }
    info = mallinfo();
    bm.list[i]->clock = clock();
    bm.list[i]->allocated = info.uordblks;
    bm.list[i]->time = time(NULL);
}
示例#12
0
int main( int argc, char **argv )
{
    int err, iteration;
    struct mallinfo minfo
;
    CYG_TEST_INIT();

    // --------------------------------------------------------------

    CYG_TEST_INFO("mount /");    
    err = mount( CYGDAT_IO_FLASH_BLOCK_DEVICE_NAME_1, "/", "jffs2" );
    if( err < 0 ) SHOW_RESULT( mount, err );    
    
    chdir ("/");
    
    iteration=0;
    create_file(iteration);
    while (iteration < ITERATIONS) {
      if (!(iteration % 1000)) {
        minfo = mallinfo();
        diag_printf("<INFO> Iteration %07d fordblks = %7d\n", 
                    iteration, minfo.fordblks);
      }
      iteration++;
      create_file(iteration);
      check_file(iteration-1);
      delete_file(iteration-1);
      check_file(iteration);
    }
    
    CYG_TEST_INFO("umount /");
    err = umount( "/" );
    if( err < 0 ) SHOW_RESULT( umount, err );    
    
    CYG_TEST_PASS_FINISH("jffs2_3");
}
示例#13
0
/* ============================================================================
 *  Stats RPC Protocol
 */
static int __memusage (z_rpc_ctx_t *ctx,
                       struct memusage_request *req,
                       struct memusage_response *resp)
{
  struct stats_client *client = STATS_CLIENT(ctx->client);
#if defined(Z_SYS_HAS_MALLINFO)
  struct mallinfo mminfo = mallinfo();

  resp->arena    = mminfo.arena;        /* Non-mmapped space allocated (bytes) */
  memusage_response_set_arena(resp);
  resp->ordblks  = mminfo.ordblks;            /* Number of free chunks */
  memusage_response_set_ordblks(resp);
  resp->smblks   = mminfo.smblks;             /* Number of free fastbin blocks */
  memusage_response_set_smblks(resp);
  resp->hblks    = mminfo.hblks;              /* Number of mmapped regions */
  memusage_response_set_hblks(resp);
  resp->hblkhd   = mminfo.hblkhd;       /* Space allocated in mmapped regions (bytes) */
  memusage_response_set_hblkhd(resp);
  resp->usmblks  = mminfo.usmblks;      /* Maximum total allocated space (bytes) */
  memusage_response_set_usmblks(resp);
  resp->fsmblks  = mminfo.fsmblks;      /* Space in freed fastbin blocks (bytes) */
  memusage_response_set_fsmblks(resp);
  resp->uordblks = mminfo.uordblks;     /* Total allocated space (bytes) */
  memusage_response_set_uordblks(resp);
  resp->fordblks = mminfo.fordblks;     /* Total free space (bytes) */
  memusage_response_set_fordblks(resp);
  resp->keepcost = mminfo.keepcost;     /* Top-most, releasable space (bytes) */
  memusage_response_set_keepcost(resp);

  resp->sysused = z_system_memory_used();
  memusage_response_set_sysused(resp);
  resp->sysfree = z_system_memory_free();
  memusage_response_set_sysfree(resp);
#endif
  return(stats_rpc_server_push_response(ctx, &(client->msgbuf)));
}
static void
xmalloc_show_trace(void *p, int sign)
{
    int statMemoryAccounted();
    static size_t last_total = 0, last_accounted = 0, last_mallinfo = 0;
    size_t accounted = statMemoryAccounted();
    size_t mi = 0;
    size_t sz;
#if HAVE_MALLINFO

    struct mallinfo mp = mallinfo();
    mi = mp.uordblks + mp.usmblks + mp.hblkhd;
#endif

    sz = xmallocblksize(p) * sign;
    xmalloc_total += sz;
    xmalloc_count += sign > 0;

    if (xmalloc_trace) {
        fprintf(stderr, "%c%8p size=%5d/%d acc=%5d/%d mallinfo=%5d/%d %s:%d %s",
                sign > 0 ? '+' : '-', p,
                (int) xmalloc_total - last_total, (int) xmalloc_total,
                (int) accounted - last_accounted, (int) accounted,
                (int) mi - last_mallinfo, (int) mi,
                xmalloc_file, xmalloc_line, xmalloc_func);

        if (sign < 0)
            fprintf(stderr, " (%d %s:%d)\n", malloc_number(p), malloc_file_name(p), malloc_line_number(p));
        else
            fprintf(stderr, " %d\n", xmalloc_count);
    }

    last_total = xmalloc_total;
    last_accounted = accounted;
    last_mallinfo = mi;
}
示例#15
0
} END_TEST

START_TEST (test_init) {
	struct event_loop el;
	int start_mem = mallinfo().uordblks;

	event_loop_init(&el);
	ck_assert_int_eq(start_mem, mallinfo().uordblks);

	event_loop_destroy(&el);
	ck_assert_int_eq(start_mem, mallinfo().uordblks);
	
	// Ensure calling init after calling new doesn't mess the destructor
	event_loop eln = event_loop_new();
	int new_mem = mallinfo().uordblks;
	ck_assert_int_ne(start_mem, new_mem);

	event_loop_init(eln);
	ck_assert_int_eq(new_mem, mallinfo().uordblks);

	event_loop_destroy(eln);
	ck_assert_int_eq(start_mem, mallinfo().uordblks);
} END_TEST
示例#16
0
int					/* O - Exit status */
main(int  argc,				/* I - Number of command-line args */
     char *argv[])			/* I - Command-line arguments */
{
  int			i;		/* Looping var */
  char			*opt;		/* Option character */
  int			fg;		/* Run in the foreground */
  int			fds;		/* Number of ready descriptors */
  cupsd_client_t	*con;		/* Current client */
  cupsd_job_t		*job;		/* Current job */
  cupsd_listener_t	*lis;		/* Current listener */
  time_t		current_time,	/* Current time */
			activity,	/* Client activity timer */
			senddoc_time,	/* Send-Document time */
			expire_time,	/* Subscription expire time */
			report_time,	/* Malloc/client/job report time */
			event_time;	/* Last event notification time */
  long			timeout;	/* Timeout for cupsdDoSelect() */
  struct rlimit		limit;		/* Runtime limit */
#if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
  struct sigaction	action;		/* Actions for POSIX signals */
#endif /* HAVE_SIGACTION && !HAVE_SIGSET */
#ifdef __sgi
  cups_file_t		*fp;		/* Fake lpsched lock file */
  struct stat		statbuf;	/* Needed for checking lpsched FIFO */
#endif /* __sgi */
  int			run_as_child = 0;
					/* Needed for background fork/exec */
#ifdef __APPLE__
  int			use_sysman = !getuid();
					/* Use system management functions? */
#else
  time_t		netif_time = 0;	/* Time since last network update */
#endif /* __APPLE__ */
#if HAVE_LAUNCHD
  int			launchd_idle_exit;
					/* Idle exit on select timeout? */
#endif	/* HAVE_LAUNCHD */


#ifdef HAVE_GETEUID
 /*
  * Check for setuid invocation, which we do not support!
  */

  if (getuid() != geteuid())
  {
    fputs("cupsd: Cannot run as a setuid program\n", stderr);
    return (1);
  }
#endif /* HAVE_GETEUID */

 /*
  * Check for command-line arguments...
  */

  fg = 0;

#ifdef HAVE_LAUNCHD
  if (getenv("CUPSD_LAUNCHD"))
  {
    Launchd = 1;
    fg      = 1;
  }
#endif /* HAVE_LAUNCHD */

  for (i = 1; i < argc; i ++)
    if (argv[i][0] == '-')
      for (opt = argv[i] + 1; *opt != '\0'; opt ++)
        switch (*opt)
	{
	  case 'C' : /* Run as child with config file */
              run_as_child = 1;
	      fg           = -1;

	  case 'c' : /* Configuration file */
	      i ++;
	      if (i >= argc)
	      {
	        _cupsLangPuts(stderr, _("cupsd: Expected config filename "
		                        "after \"-c\" option."));
	        usage(1);
	      }

              if (argv[i][0] == '/')
	      {
	       /*
	        * Absolute directory...
		*/

		cupsdSetString(&ConfigurationFile, argv[i]);
              }
	      else
	      {
	       /*
	        * Relative directory...
		*/

                char *current;		/* Current directory */


	       /*
	        * Allocate a buffer for the current working directory to
		* reduce run-time stack usage; this approximates the
		* behavior of some implementations of getcwd() when they
		* are passed a NULL pointer.
	        */

                if ((current = malloc(1024)) == NULL)
		{
		  _cupsLangPuts(stderr,
		                _("cupsd: Unable to get current directory."));
                  return (1);
		}

		if (!getcwd(current, 1024))
		{
		  _cupsLangPuts(stderr,
		                _("cupsd: Unable to get current directory."));
                  free(current);
		  return (1);
		}

		cupsdSetStringf(&ConfigurationFile, "%s/%s", current, argv[i]);
		free(current);
              }
	      break;

          case 'f' : /* Run in foreground... */
	      fg = 1;
	      break;

          case 'F' : /* Run in foreground, but disconnect from terminal... */
	      fg = -1;
	      break;

          case 'h' : /* Show usage/help */
	      usage(0);
	      break;

          case 'l' : /* Started by launchd... */
#ifdef HAVE_LAUNCHD
	      Launchd = 1;
	      fg      = 1;
#else
	      _cupsLangPuts(stderr, _("cupsd: launchd(8) support not compiled "
	                              "in, running in normal mode."));
              fg = 0;
#endif /* HAVE_LAUNCHD */
	      break;

          case 'p' : /* Stop immediately for profiling */
              fputs("cupsd: -p (startup profiling) is for internal testing "
                    "use only!\n", stderr);
	      stop_scheduler = 1;
	      fg             = 1;
	      break;

          case 'P' : /* Disable security profiles */
              fputs("cupsd: -P (disable security profiles) is for internal "
                    "testing use only!\n", stderr);
	      UseProfiles = 0;
	      break;

#ifdef __APPLE__
          case 'S' : /* Disable system management functions */
              fputs("cupsd: -S (disable system management) for internal "
                    "testing use only!\n", stderr);
	      use_sysman = 0;
	      break;
#endif /* __APPLE__ */

          case 't' : /* Test the cupsd.conf file... */
	      TestConfigFile = 1;
	      fg             = 1;
	      break;

	  default : /* Unknown option */
              _cupsLangPrintf(stderr, _("cupsd: Unknown option \"%c\" - "
	                                "aborting."), *opt);
	      usage(1);
	      break;
	}
    else
    {
      _cupsLangPrintf(stderr, _("cupsd: Unknown argument \"%s\" - aborting."),
                      argv[i]);
      usage(1);
    }

  if (!ConfigurationFile)
    cupsdSetString(&ConfigurationFile, CUPS_SERVERROOT "/cupsd.conf");

 /*
  * If the user hasn't specified "-f", run in the background...
  */

  if (!fg)
  {
   /*
    * Setup signal handlers for the parent...
    */

#ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
    sigset(SIGUSR1, parent_handler);
    sigset(SIGCHLD, parent_handler);

    sigset(SIGHUP, SIG_IGN);
#elif defined(HAVE_SIGACTION)
    memset(&action, 0, sizeof(action));
    sigemptyset(&action.sa_mask);
    sigaddset(&action.sa_mask, SIGUSR1);
    action.sa_handler = parent_handler;
    sigaction(SIGUSR1, &action, NULL);
    sigaction(SIGCHLD, &action, NULL);

    sigemptyset(&action.sa_mask);
    action.sa_handler = SIG_IGN;
    sigaction(SIGHUP, &action, NULL);
#else
    signal(SIGUSR1, parent_handler);
    signal(SIGCLD, parent_handler);

    signal(SIGHUP, SIG_IGN);
#endif /* HAVE_SIGSET */

    if (fork() > 0)
    {
     /*
      * OK, wait for the child to startup and send us SIGUSR1 or to crash
      * and the OS send us SIGCHLD...  We also need to ignore SIGHUP which
      * might be sent by the init script to restart the scheduler...
      */

      for (; parent_signal == 0;)
        sleep(1);

      if (parent_signal == SIGUSR1)
        return (0);

      if (wait(&i) < 0)
      {
        perror("cupsd");
	return (1);
      }
      else if (WIFEXITED(i))
      {
        fprintf(stderr, "cupsd: Child exited with status %d\n",
	        WEXITSTATUS(i));
	return (2);
      }
      else
      {
        fprintf(stderr, "cupsd: Child exited on signal %d\n", WTERMSIG(i));
	return (3);
      }
    }

#ifdef __OpenBSD__
   /*
    * Call _thread_sys_closefrom() so the child process doesn't reset the
    * parent's file descriptors to be blocking.  This is a workaround for a
    * limitation of userland libpthread on OpenBSD.
    */

    _thread_sys_closefrom(0);
#endif /* __OpenBSD__ */

   /*
    * Since CoreFoundation and DBUS both create fork-unsafe data on execution of
    * a program, and since this kind of really unfriendly behavior seems to be
    * more common these days in system libraries, we need to re-execute the
    * background cupsd with the "-C" option to avoid problems.  Unfortunately,
    * we also have to assume that argv[0] contains the name of the cupsd
    * executable - there is no portable way to get the real pathname...
    */

    execlp(argv[0], argv[0], "-C", ConfigurationFile, (char *)0);
    exit(errno);
  }

  if (fg < 1)
  {
   /*
    * Make sure we aren't tying up any filesystems...
    */

    chdir("/");

#ifndef DEBUG
   /*
    * Disable core dumps...
    */

    getrlimit(RLIMIT_CORE, &limit);
    limit.rlim_cur = 0;
    setrlimit(RLIMIT_CORE, &limit);

   /*
    * Disconnect from the controlling terminal...
    */

    setsid();

   /*
    * Close all open files...
    */

    getrlimit(RLIMIT_NOFILE, &limit);

    for (i = 0; i < limit.rlim_cur && i < 1024; i ++)
      close(i);

   /*
    * Redirect stdin/out/err to /dev/null...
    */

    if ((i = open("/dev/null", O_RDONLY)) != 0)
    {
      dup2(i, 0);
      close(i);
    }

    if ((i = open("/dev/null", O_WRONLY)) != 1)
    {
      dup2(i, 1);
      close(i);
    }

    if ((i = open("/dev/null", O_WRONLY)) != 2)
    {
      dup2(i, 2);
      close(i);
    }
#endif /* DEBUG */
  }

 /*
  * Set the timezone info...
  */

  tzset();

#ifdef LC_TIME
  setlocale(LC_TIME, "");
#endif /* LC_TIME */

 /*
  * Set the maximum number of files...
  */

  getrlimit(RLIMIT_NOFILE, &limit);

#if !defined(HAVE_POLL) && !defined(HAVE_EPOLL) && !defined(HAVE_KQUEUE)
  if (limit.rlim_max > FD_SETSIZE)
    MaxFDs = FD_SETSIZE;
  else
#endif /* !HAVE_POLL && !HAVE_EPOLL && !HAVE_KQUEUE */
#ifdef RLIM_INFINITY
  if (limit.rlim_max == RLIM_INFINITY)
    MaxFDs = 16384;
  else
#endif /* RLIM_INFINITY */
    MaxFDs = limit.rlim_max;

  limit.rlim_cur = MaxFDs;

  setrlimit(RLIMIT_NOFILE, &limit);

  cupsdStartSelect();

 /*
  * Read configuration...
  */

  if (!cupsdReadConfiguration())
  {
    if (TestConfigFile)
      printf("%s contains errors\n", ConfigurationFile);
    else
      syslog(LOG_LPR, "Unable to read configuration file \'%s\' - exiting!",
	     ConfigurationFile);
    return (1);
  }
  else if (TestConfigFile)
  {
    printf("%s is OK\n", ConfigurationFile);
    return (0);
  }

 /*
  * Clean out old temp files and printer cache data.
  */

  if (!strncmp(TempDir, RequestRoot, strlen(RequestRoot)))
    cupsdCleanFiles(TempDir, NULL);

  cupsdCleanFiles(CacheDir, "*.ipp");

#if HAVE_LAUNCHD
  if (Launchd)
  {
   /*
    * If we were started by launchd get the listen sockets file descriptors...
    */

    launchd_checkin();
    launchd_checkout();
  }
#endif /* HAVE_LAUNCHD */

 /*
  * Startup the server...
  */

  httpInitialize();

  cupsdStartServer();

 /*
  * Catch hangup and child signals and ignore broken pipes...
  */

#ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
  sigset(SIGCHLD, sigchld_handler);
  sigset(SIGHUP, sighup_handler);
  sigset(SIGPIPE, SIG_IGN);
  sigset(SIGTERM, sigterm_handler);
#elif defined(HAVE_SIGACTION)
  memset(&action, 0, sizeof(action));

  sigemptyset(&action.sa_mask);
  sigaddset(&action.sa_mask, SIGTERM);
  sigaddset(&action.sa_mask, SIGCHLD);
  action.sa_handler = sigchld_handler;
  sigaction(SIGCHLD, &action, NULL);

  sigemptyset(&action.sa_mask);
  sigaddset(&action.sa_mask, SIGHUP);
  action.sa_handler = sighup_handler;
  sigaction(SIGHUP, &action, NULL);

  sigemptyset(&action.sa_mask);
  action.sa_handler = SIG_IGN;
  sigaction(SIGPIPE, &action, NULL);

  sigemptyset(&action.sa_mask);
  sigaddset(&action.sa_mask, SIGTERM);
  sigaddset(&action.sa_mask, SIGCHLD);
  action.sa_handler = sigterm_handler;
  sigaction(SIGTERM, &action, NULL);
#else
  signal(SIGCLD, sigchld_handler);	/* No, SIGCLD isn't a typo... */
  signal(SIGHUP, sighup_handler);
  signal(SIGPIPE, SIG_IGN);
  signal(SIGTERM, sigterm_handler);
#endif /* HAVE_SIGSET */

#ifdef __sgi
 /*
  * Try to create a fake lpsched lock file if one is not already there.
  * Some Adobe applications need it under IRIX in order to enable
  * printing...
  */

  if ((fp = cupsFileOpen("/var/spool/lp/SCHEDLOCK", "w")) == NULL)
  {
    syslog(LOG_LPR, "Unable to create fake lpsched lock file "
                    "\"/var/spool/lp/SCHEDLOCK\"\' - %s!",
           strerror(errno));
  }
  else
  {
    fchmod(cupsFileNumber(fp), 0644);
    fchown(cupsFileNumber(fp), User, Group);

    cupsFileClose(fp);
  }
#endif /* __sgi */

 /*
  * Initialize authentication certificates...
  */

  cupsdInitCerts();

 /*
  * If we are running in the background, signal the parent process that
  * we are up and running...
  */

  if (!fg || run_as_child)
  {
   /*
    * Send a signal to the parent process, but only if the parent is
    * not PID 1 (init).  This avoids accidentally shutting down the
    * system on OpenBSD if you CTRL-C the server before it is up...
    */

    i = getppid();	/* Save parent PID to avoid race condition */

    if (i != 1)
      kill(i, SIGUSR1);
  }

#ifdef __APPLE__
 /*
  * Start power management framework...
  */

  if (use_sysman)
    cupsdStartSystemMonitor();
#endif /* __APPLE__ */

 /*
  * Send server-started event...
  */

#ifdef HAVE_LAUNCHD
  if (Launchd)
    cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED, NULL, NULL,
                  "Scheduler started via launchd.");
  else
#endif /* HAVE_LAUNCHD */
  if (fg)
    cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED, NULL, NULL,
                  "Scheduler started in foreground.");
  else
    cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED, NULL, NULL,
                  "Scheduler started in background.");

 /*
  * Start any pending print jobs...
  */

  cupsdCheckJobs();

 /*
  * Loop forever...
  */

  current_time  = time(NULL);
  event_time    = current_time;
  expire_time   = current_time;
  fds           = 1;
  report_time   = 0;
  senddoc_time  = current_time;

  while (!stop_scheduler)
  {
   /*
    * Check if there are dead children to handle...
    */

    if (dead_children)
      process_children();

   /*
    * Check if we need to load the server configuration file...
    */

    if (NeedReload)
    {
     /*
      * Close any idle clients...
      */

      if (cupsArrayCount(Clients) > 0)
      {
	for (con = (cupsd_client_t *)cupsArrayFirst(Clients);
	     con;
	     con = (cupsd_client_t *)cupsArrayNext(Clients))
	  if (con->http.state == HTTP_WAITING)
	    cupsdCloseClient(con);
	  else
	    con->http.keep_alive = HTTP_KEEPALIVE_OFF;

        cupsdPauseListening();
      }

     /*
      * Restart if all clients are closed and all jobs finished, or
      * if the reload timeout has elapsed...
      */

      if ((cupsArrayCount(Clients) == 0 &&
           (cupsArrayCount(PrintingJobs) == 0 || NeedReload != RELOAD_ALL)) ||
          (time(NULL) - ReloadTime) >= ReloadTimeout)
      {
       /*
	* Shutdown the server...
	*/

        DoingShutdown = 1;

	cupsdStopServer();

       /*
	* Read configuration...
	*/

        if (!cupsdReadConfiguration())
        {
          syslog(LOG_LPR, "Unable to read configuration file \'%s\' - exiting!",
		 ConfigurationFile);
          break;
	}

#if HAVE_LAUNCHD
	if (Launchd)
	{
	 /*
	  * If we were started by launchd, get the listen socket file
	  * descriptors...
	  */

	  launchd_checkin();
	  launchd_checkout();
	}
#endif /* HAVE_LAUNCHD */

       /*
        * Startup the server...
        */

        DoingShutdown = 0;

        cupsdStartServer();

       /*
        * Send a server-restarted event...
	*/

        cupsdAddEvent(CUPSD_EVENT_SERVER_RESTARTED, NULL, NULL,
                      "Scheduler restarted.");
      }
    }

   /*
    * Check for available input or ready output.  If cupsdDoSelect()
    * returns 0 or -1, something bad happened and we should exit
    * immediately.
    *
    * Note that we at least have one listening socket open at all
    * times.
    */

    if ((timeout = select_timeout(fds)) > 1 && LastEvent)
      timeout = 1;

#if HAVE_LAUNCHD
   /*
    * If no other work is scheduled and we're being controlled by
    * launchd then timeout after 'LaunchdTimeout' seconds of
    * inactivity...
    */

    if (timeout == 86400 && Launchd && LaunchdTimeout &&
        !cupsArrayCount(ActiveJobs) &&
	(!Browsing || !BrowseLocalProtocols || !cupsArrayCount(Printers)))
    {
      timeout		= LaunchdTimeout;
      launchd_idle_exit = 1;
    }
    else
      launchd_idle_exit = 0;
#endif	/* HAVE_LAUNCHD */

    if ((fds = cupsdDoSelect(timeout)) < 0)
    {
     /*
      * Got an error from select!
      */

#ifdef HAVE_DNSSD
      cupsd_printer_t	*p;		/* Current printer */
#endif /* HAVE_DNSSD */


      if (errno == EINTR)		/* Just interrupted by a signal */
        continue;

     /*
      * Log all sorts of debug info to help track down the problem.
      */

      cupsdLogMessage(CUPSD_LOG_EMERG, "cupsdDoSelect() failed - %s!",
                      strerror(errno));

      for (i = 0, con = (cupsd_client_t *)cupsArrayFirst(Clients);
	   con;
	   i ++, con = (cupsd_client_t *)cupsArrayNext(Clients))
        cupsdLogMessage(CUPSD_LOG_EMERG,
	                "Clients[%d] = %d, file = %d, state = %d",
	                i, con->http.fd, con->file, con->http.state);

      for (i = 0, lis = (cupsd_listener_t *)cupsArrayFirst(Listeners);
           lis;
	   i ++, lis = (cupsd_listener_t *)cupsArrayNext(Listeners))
        cupsdLogMessage(CUPSD_LOG_EMERG, "Listeners[%d] = %d", i, lis->fd);

      cupsdLogMessage(CUPSD_LOG_EMERG, "CGIPipes[0] = %d", CGIPipes[0]);

#ifdef __APPLE__
      cupsdLogMessage(CUPSD_LOG_EMERG, "SysEventPipes[0] = %d",
                      SysEventPipes[0]);
#endif /* __APPLE__ */

      for (job = (cupsd_job_t *)cupsArrayFirst(ActiveJobs);
	   job;
	   job = (cupsd_job_t *)cupsArrayNext(ActiveJobs))
        cupsdLogMessage(CUPSD_LOG_EMERG, "Jobs[%d] = %d < [%d %d] > [%d %d]",
	        	job->id,
			job->status_buffer ? job->status_buffer->fd : -1,
			job->print_pipes[0], job->print_pipes[1],
			job->back_pipes[0], job->back_pipes[1]);

#ifdef HAVE_DNSSD
      for (p = (cupsd_printer_t *)cupsArrayFirst(Printers);
	   p;
	   p = (cupsd_printer_t *)cupsArrayNext(Printers))
        cupsdLogMessage(CUPSD_LOG_EMERG, "printer[%s] reg_name=\"%s\"", p->name,
	                p->reg_name ? p->reg_name : "(null)");
#endif /* HAVE_DNSSD */

      break;
    }

    current_time = time(NULL);

   /*
    * Write dirty config/state files...
    */

    if (DirtyCleanTime && current_time >= DirtyCleanTime)
      cupsdCleanDirty();

#ifdef __APPLE__
   /*
    * If we are going to sleep and still have pending jobs, stop them after
    * a period of time...
    */

    if (SleepJobs > 0 && current_time >= SleepJobs &&
        cupsArrayCount(PrintingJobs) > 0)
    {
      SleepJobs = 0;
      cupsdStopAllJobs(CUPSD_JOB_DEFAULT, 5);
    }
#endif /* __APPLE__ */

#ifndef __APPLE__
   /*
    * Update the network interfaces once a minute...
    */

    if ((current_time - netif_time) >= 60)
    {
      netif_time  = current_time;
      NetIFUpdate = 1;
    }
#endif /* !__APPLE__ */

#if HAVE_LAUNCHD
   /*
    * If no other work was scheduled and we're being controlled by launchd
    * then timeout after 'LaunchdTimeout' seconds of inactivity...
    */

    if (!fds && launchd_idle_exit)
    {
      cupsdLogMessage(CUPSD_LOG_INFO,
                      "Printer sharing is off and there are no jobs pending, "
		      "will restart on demand.");
      stop_scheduler = 1;
      break;
    }
#endif /* HAVE_LAUNCHD */

   /*
    * Resume listening for new connections as needed...
    */

    if (ListeningPaused && ListeningPaused <= current_time &&
        cupsArrayCount(Clients) < MaxClients)
      cupsdResumeListening();

   /*
    * Expire subscriptions and unload completed jobs as needed...
    */

    if (current_time > expire_time)
    {
      if (cupsArrayCount(Subscriptions) > 0)
        cupsdExpireSubscriptions(NULL, NULL);

      cupsdUnloadCompletedJobs();

      expire_time = current_time;
    }

#ifndef HAVE_AUTHORIZATION_H
   /*
    * Update the root certificate once every 5 minutes if we have client
    * connections...
    */

    if ((current_time - RootCertTime) >= RootCertDuration && RootCertDuration &&
        !RunUser && cupsArrayCount(Clients))
    {
     /*
      * Update the root certificate...
      */

      cupsdDeleteCert(0);
      cupsdAddCert(0, "root", NULL);
    }
#endif /* !HAVE_AUTHORIZATION_H */

   /*
    * Check for new data on the client sockets...
    */

    for (con = (cupsd_client_t *)cupsArrayFirst(Clients);
	 con;
	 con = (cupsd_client_t *)cupsArrayNext(Clients))
    {
     /*
      * Process pending data in the input buffer...
      */

      if (con->http.used)
      {
        cupsdReadClient(con);
	continue;
      }

     /*
      * Check the activity and close old clients...
      */

      activity = current_time - Timeout;
      if (con->http.activity < activity && !con->pipe_pid)
      {
        cupsdLogMessage(CUPSD_LOG_DEBUG,
	                "Closing client %d after %d seconds of inactivity...",
	                con->http.fd, Timeout);

        cupsdCloseClient(con);
        continue;
      }
    }

   /*
    * Update any pending multi-file documents...
    */

    if ((current_time - senddoc_time) >= 10)
    {
      cupsdCheckJobs();
      senddoc_time = current_time;
    }

   /*
    * Clean job history...
    */

    if (JobHistoryUpdate && current_time >= JobHistoryUpdate)
      cupsdCleanJobs();

   /*
    * Log statistics at most once a minute when in debug mode...
    */

    if ((current_time - report_time) >= 60 && LogLevel >= CUPSD_LOG_DEBUG)
    {
      size_t		string_count,	/* String count */
			alloc_bytes,	/* Allocated string bytes */
			total_bytes;	/* Total string bytes */
#ifdef HAVE_MALLINFO
      struct mallinfo	mem;		/* Malloc information */


      mem = mallinfo();
      cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: malloc-arena=%lu", mem.arena);
      cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: malloc-used=%lu",
                      mem.usmblks + mem.uordblks);
      cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: malloc-free=%lu",
		      mem.fsmblks + mem.fordblks);
#endif /* HAVE_MALLINFO */

      cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: clients=%d",
                      cupsArrayCount(Clients));
      cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: jobs=%d",
                      cupsArrayCount(Jobs));
      cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: jobs-active=%d",
                      cupsArrayCount(ActiveJobs));
      cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: printers=%d",
                      cupsArrayCount(Printers));

      string_count = _cupsStrStatistics(&alloc_bytes, &total_bytes);
      cupsdLogMessage(CUPSD_LOG_DEBUG,
                      "Report: stringpool-string-count=" CUPS_LLFMT,
		      CUPS_LLCAST string_count);
      cupsdLogMessage(CUPSD_LOG_DEBUG,
                      "Report: stringpool-alloc-bytes=" CUPS_LLFMT,
		      CUPS_LLCAST alloc_bytes);
      cupsdLogMessage(CUPSD_LOG_DEBUG,
                      "Report: stringpool-total-bytes=" CUPS_LLFMT,
		      CUPS_LLCAST total_bytes);

      report_time = current_time;
    }

   /*
    * Handle OS-specific event notification for any events that have
    * accumulated.  Don't send these more than once a second...
    */

    if (LastEvent && (current_time - event_time) >= 1)
    {
#ifdef HAVE_NOTIFY_POST
      if (LastEvent & (CUPSD_EVENT_PRINTER_ADDED |
                       CUPSD_EVENT_PRINTER_DELETED |
                       CUPSD_EVENT_PRINTER_MODIFIED))
      {
        cupsdLogMessage(CUPSD_LOG_DEBUG2,
	                "notify_post(\"com.apple.printerListChange\")");
	notify_post("com.apple.printerListChange");
      }

      if (LastEvent & CUPSD_EVENT_PRINTER_STATE_CHANGED)
      {
        cupsdLogMessage(CUPSD_LOG_DEBUG2,
	                "notify_post(\"com.apple.printerHistoryChange\")");
	notify_post("com.apple.printerHistoryChange");
      }

      if (LastEvent & (CUPSD_EVENT_JOB_STATE_CHANGED |
                       CUPSD_EVENT_JOB_CONFIG_CHANGED |
                       CUPSD_EVENT_JOB_PROGRESS))
      {
        cupsdLogMessage(CUPSD_LOG_DEBUG2,
	                "notify_post(\"com.apple.jobChange\")");
	notify_post("com.apple.jobChange");
      }
#endif /* HAVE_NOTIFY_POST */

     /*
      * Reset the accumulated events...
      */

      LastEvent  = CUPSD_EVENT_NONE;
      event_time = current_time;
    }
  }

 /*
  * Log a message based on what happened...
  */

  if (stop_scheduler)
  {
    cupsdLogMessage(CUPSD_LOG_INFO, "Scheduler shutting down normally.");
    cupsdAddEvent(CUPSD_EVENT_SERVER_STOPPED, NULL, NULL,
                  "Scheduler shutting down normally.");
  }
  else
  {
    cupsdLogMessage(CUPSD_LOG_ERROR,
                    "Scheduler shutting down due to program error.");
    cupsdAddEvent(CUPSD_EVENT_SERVER_STOPPED, NULL, NULL,
                  "Scheduler shutting down due to program error.");
  }

 /*
  * Close all network clients...
  */

  DoingShutdown = 1;

  cupsdStopServer();

#ifdef HAVE_LAUNCHD
 /*
  * Update the launchd KeepAlive file as needed...
  */

  if (Launchd)
    launchd_checkout();
#endif /* HAVE_LAUNCHD */

 /*
  * Stop all jobs...
  */

  cupsdFreeAllJobs();

#ifdef __APPLE__
 /*
  * Stop monitoring system event monitoring...
  */

  if (use_sysman)
    cupsdStopSystemMonitor();
#endif /* __APPLE__ */

#ifdef HAVE_GSSAPI
 /*
  * Free the scheduler's Kerberos context...
  */

#  ifdef __APPLE__
 /*
  * If the weak-linked GSSAPI/Kerberos library is not present, don't try
  * to use it...
  */

  if (krb5_init_context != NULL)
#  endif /* __APPLE__ */
  if (KerberosContext)
    krb5_free_context(KerberosContext);
#endif /* HAVE_GSSAPI */

#ifdef __sgi
 /*
  * Remove the fake IRIX lpsched lock file, but only if the existing
  * file is not a FIFO which indicates that the real IRIX lpsched is
  * running...
  */

  if (!stat("/var/spool/lp/FIFO", &statbuf))
    if (!S_ISFIFO(statbuf.st_mode))
      unlink("/var/spool/lp/SCHEDLOCK");
#endif /* __sgi */

  cupsdStopSelect();

  return (!stop_scheduler);
}
示例#17
0
void dm_leak_check_start(struct unit_test_state *uts)
{
	uts->start = mallinfo();
	if (!uts->start.uordblks)
		puts("Warning: Please add '#define DEBUG' to the top of common/dlmalloc.c\n");
}
示例#18
0
int
user_start(int argc, char *argv[])
{
	/* run C++ ctors before we go any further */
	up_cxxinitialize();

	/* reset all to zero */
	memset(&system_state, 0, sizeof(system_state));

	/* configure the high-resolution time/callout interface */
	hrt_init();

	/* calculate our fw CRC so FMU can decide if we need to update */
	calculate_fw_crc();

	/*
	 * Poll at 1ms intervals for received bytes that have not triggered
	 * a DMA event.
	 */
#ifdef CONFIG_ARCH_DMA
	hrt_call_every(&serial_dma_call, 1000, 1000, (hrt_callout)stm32_serial_dma_poll, NULL);
#endif

	/* print some startup info */
	lowsyslog("\nPX4IO: starting\n");

	/* default all the LEDs to off while we start */
	LED_AMBER(false);
	LED_BLUE(false);
	LED_SAFETY(false);
#ifdef GPIO_LED4
	LED_RING(false);
#endif

	/* turn on servo power (if supported) */
#ifdef POWER_SERVO
	POWER_SERVO(true);
#endif

	/* turn off S.Bus out (if supported) */
#ifdef ENABLE_SBUS_OUT
	ENABLE_SBUS_OUT(false);
#endif

	/* start the safety switch handler */
	safety_init();

	/* configure the first 8 PWM outputs (i.e. all of them) */
	up_pwm_servo_init(0xff);

	/* initialise the control inputs */
	controls_init();

	/* set up the ADC */
	adc_init();

	/* start the FMU interface */
	interface_init();

	/* add a performance counter for mixing */
	perf_counter_t mixer_perf = perf_alloc(PC_ELAPSED, "mix");

	/* add a performance counter for controls */
	perf_counter_t controls_perf = perf_alloc(PC_ELAPSED, "controls");

	/* and one for measuring the loop rate */
	perf_counter_t loop_perf = perf_alloc(PC_INTERVAL, "loop");

	struct mallinfo minfo = mallinfo();
	lowsyslog("MEM: free %u, largest %u\n", minfo.mxordblk, minfo.fordblks);

	/* initialize PWM limit lib */
	pwm_limit_init(&pwm_limit);

	/*
	 *    P O L I C E    L I G H T S
	 *
	 * Not enough memory, lock down.
	 *
	 * We might need to allocate mixers later, and this will
	 * ensure that a developer doing a change will notice
	 * that he just burned the remaining RAM with static
	 * allocations. We don't want him to be able to
	 * get past that point. This needs to be clearly
	 * documented in the dev guide.
	 *
	 */
	if (minfo.mxordblk < 600) {

		lowsyslog("ERR: not enough MEM");
		bool phase = false;

		while (true) {

			if (phase) {
				LED_AMBER(true);
				LED_BLUE(false);

			} else {
				LED_AMBER(false);
				LED_BLUE(true);
			}

			up_udelay(250000);

			phase = !phase;
		}
	}

	/* Start the failsafe led init */
	failsafe_led_init();

	/*
	 * Run everything in a tight loop.
	 */

	uint64_t last_debug_time = 0;
	uint64_t last_heartbeat_time = 0;

	for (;;) {

		/* track the rate at which the loop is running */
		perf_count(loop_perf);

		/* kick the mixer */
		perf_begin(mixer_perf);
		mixer_tick();
		perf_end(mixer_perf);

		/* kick the control inputs */
		perf_begin(controls_perf);
		controls_tick();
		perf_end(controls_perf);

		if ((hrt_absolute_time() - last_heartbeat_time) > 250 * 1000) {
			last_heartbeat_time = hrt_absolute_time();
			heartbeat_blink();
		}

		ring_blink();

		check_reboot();

		/* check for debug activity (default: none) */
		show_debug_messages();

		/* post debug state at ~1Hz - this is via an auxiliary serial port
		 * DEFAULTS TO OFF!
		 */
		if (hrt_absolute_time() - last_debug_time > (1000 * 1000)) {

			isr_debug(1, "d:%u s=0x%x a=0x%x f=0x%x m=%u",
				  (unsigned)r_page_setup[PX4IO_P_SETUP_SET_DEBUG],
				  (unsigned)r_status_flags,
				  (unsigned)r_setup_arming,
				  (unsigned)r_setup_features,
				  (unsigned)mallinfo().mxordblk);
			last_debug_time = hrt_absolute_time();
		}
	}
}
示例#19
0
文件: enigma.cpp 项目: st7TEAM/e2a
void dump_malloc_stats(void)
{
	struct mallinfo mi = mallinfo();
	eDebug("MALLOC: %d total", mi.uordblks);
}
示例#20
0
int
registers_get(uint8_t page, uint8_t offset, uint16_t **values, unsigned *num_values)
{
#define SELECT_PAGE(_page_name)							\
	do {									\
		*values = (uint16_t *)&_page_name[0];				\
		*num_values = sizeof(_page_name) / sizeof(_page_name[0]);	\
	} while(0)

	switch (page) {

	/*
	 * Handle pages that are updated dynamically at read time.
	 */
	case PX4IO_PAGE_STATUS:
		/* PX4IO_P_STATUS_FREEMEM */
		{
			struct mallinfo minfo = mallinfo();
			r_page_status[PX4IO_P_STATUS_FREEMEM] = minfo.fordblks;
		}

		/* XXX PX4IO_P_STATUS_CPULOAD */

		/* PX4IO_P_STATUS_FLAGS maintained externally */

		/* PX4IO_P_STATUS_ALARMS maintained externally */

#ifdef ADC_VBATT
		/* PX4IO_P_STATUS_VBATT */
		{
			/*
			 * Coefficients here derived by measurement of the 5-16V
			 * range on one unit, validated on sample points of another unit
			 *
			 * Data in Tools/tests-host/data folder.
			 *
			 * measured slope = 0.004585267878277 (int: 4585)
			 * nominal theoretic slope: 0.00459340659 (int: 4593)
			 * intercept = 0.016646394188076 (int: 16646)
			 * nominal theoretic intercept: 0.00 (int: 0)
			 *
			 */
			unsigned counts = adc_measure(ADC_VBATT);
			if (counts != 0xffff) {
				unsigned mV = (166460 + (counts * 45934)) / 10000;
				unsigned corrected = (mV * r_page_setup[PX4IO_P_SETUP_VBATT_SCALE]) / 10000;

				r_page_status[PX4IO_P_STATUS_VBATT] = corrected;
			}
		}
#endif
#ifdef ADC_IBATT
		/* PX4IO_P_STATUS_IBATT */
		{
			/*
			  note that we have no idea what sort of
			  current sensor is attached, so we just
			  return the raw 12 bit ADC value and let the
			  FMU sort it out, with user selectable
			  configuration for their sensor
			 */
			unsigned counts = adc_measure(ADC_IBATT);
			if (counts != 0xffff) {
				r_page_status[PX4IO_P_STATUS_IBATT] = counts;
			}
		}
#endif
#ifdef ADC_VSERVO
		/* PX4IO_P_STATUS_VSERVO */
		{
			unsigned counts = adc_measure(ADC_VSERVO);
			if (counts != 0xffff) {
				// use 3:1 scaling on 3.3V ADC input
				unsigned mV = counts * 9900 / 4096;
				r_page_status[PX4IO_P_STATUS_VSERVO] = mV;
			}
		}
#endif
#ifdef ADC_RSSI
		/* PX4IO_P_STATUS_VRSSI */
		{
			unsigned counts = adc_measure(ADC_RSSI);
			if (counts != 0xffff) {
				// use 1:1 scaling on 3.3V ADC input
				unsigned mV = counts * 3300 / 4096;
				r_page_status[PX4IO_P_STATUS_VRSSI] = mV;
			}
		}
#endif
		/* XXX PX4IO_P_STATUS_PRSSI */

		SELECT_PAGE(r_page_status);
		break;

	case PX4IO_PAGE_RAW_ADC_INPUT:
		memset(r_page_scratch, 0, sizeof(r_page_scratch));
#ifdef ADC_VBATT
		r_page_scratch[0] = adc_measure(ADC_VBATT);
#endif
#ifdef ADC_IBATT
		r_page_scratch[1] = adc_measure(ADC_IBATT);
#endif

#ifdef ADC_VSERVO
		r_page_scratch[0] = adc_measure(ADC_VSERVO);
#endif
#ifdef ADC_RSSI
		r_page_scratch[1] = adc_measure(ADC_RSSI);
#endif
		SELECT_PAGE(r_page_scratch);
		break;

	case PX4IO_PAGE_PWM_INFO:
		memset(r_page_scratch, 0, sizeof(r_page_scratch));
		for (unsigned i = 0; i < PX4IO_SERVO_COUNT; i++)
			r_page_scratch[PX4IO_RATE_MAP_BASE + i] = up_pwm_servo_get_rate_group(i);

		SELECT_PAGE(r_page_scratch);
		break;

	/*
	 * Pages that are just a straight read of the register state.
	 */

	/* status pages */
	case PX4IO_PAGE_CONFIG:
		SELECT_PAGE(r_page_config);
		break;
	case PX4IO_PAGE_ACTUATORS:
		SELECT_PAGE(r_page_actuators);
		break;
	case PX4IO_PAGE_SERVOS:
		SELECT_PAGE(r_page_servos);
		break;
	case PX4IO_PAGE_RAW_RC_INPUT:
		SELECT_PAGE(r_page_raw_rc_input);
		break;
	case PX4IO_PAGE_RC_INPUT:
		SELECT_PAGE(r_page_rc_input);
		break;

	/* readback of input pages */
	case PX4IO_PAGE_SETUP:
		SELECT_PAGE(r_page_setup);
		break;
	case PX4IO_PAGE_CONTROLS:
		SELECT_PAGE(r_page_controls);
		break;
	case PX4IO_PAGE_RC_CONFIG:
		SELECT_PAGE(r_page_rc_input_config);
		break;
	case PX4IO_PAGE_DIRECT_PWM:
		SELECT_PAGE(r_page_servos);
		break;
	case PX4IO_PAGE_FAILSAFE_PWM:
		SELECT_PAGE(r_page_servo_failsafe);
		break;
	case PX4IO_PAGE_CONTROL_MIN_PWM:
		SELECT_PAGE(r_page_servo_control_min);
		break;
	case PX4IO_PAGE_CONTROL_MAX_PWM:
		SELECT_PAGE(r_page_servo_control_max);
		break;
	case PX4IO_PAGE_DISARMED_PWM:
		SELECT_PAGE(r_page_servo_disarmed);
		break;

	default:
		return -1;
	}

#undef SELECT_PAGE
#undef COPY_PAGE

last_page = page;
last_offset = offset;

	/* if the offset is at or beyond the end of the page, we have no data */
	if (offset >= *num_values)
		return -1;

	/* correct the data pointer and count for the offset */
	*values += offset;
	*num_values -= offset;

	return 0;
}
示例#21
0
文件: sax.c 项目: actility/ong
void info() {
	struct mallinfo info = mallinfo();
	printf ("### mallinfo : total allocated space:  %d bytes\n", info.uordblks);
}
示例#22
0
文件: driver.c 项目: sos22/dwc
int
main(int argc, char *argv[])
{
	int fd;
	struct stat statbuf;
	off_t size;
	unsigned nr_workers;
	int workers_left_alive;
	struct pollfd *polls;
	struct worker *workers;
	unsigned x;
	int idx;
	int *poll_slots_to_workers;
	int offline;
	int prepopulate;
	int poll_slots_in_use;
	struct mallinfo mi;

	init_malloc(false);
	gettimeofday(&start, NULL);

	if (argc == 1)
		errx(1, "arguments are either --offline and a list of files, or a list of ip port1 port2 triples");

	prepopulate = 0;
	if (!strcmp(argv[1], "--prepopulate")) {
		prepopulate = 1;
		argv++;
		argc--;
	}

	offline = 0;
	if (!strcmp(argv[1], "--offline"))
		offline = 1;

	if (!offline) {
		if ((argc - 2) % 3)
			errx(1, "non-integer number of workers?");

		fd = open(argv[1], O_RDONLY);
		if (fd < 0)
			err(1, "open(%s)", argv[1]);
		if (fstat(fd, &statbuf) < 0)
			err(1, "stat(%s)", argv[1]);
		size = statbuf.st_size;
		nr_workers = (argc - 2) / 3;
	} else {
		fd = -1;
		size = 0;
		nr_workers = argc - 2;
	}

	workers = calloc(nr_workers, sizeof(workers[0]));
	polls = calloc(nr_workers, sizeof(polls[0]));
	poll_slots_to_workers = calloc(nr_workers, sizeof(polls[0]));
	for (x = 0; x < nr_workers; x++) {
		if (offline) {
			workers[x].to_worker_fd = -1;
			workers[x].from_worker_fd = open(argv[x + 2], O_RDONLY | O_NONBLOCK);
			if (workers[x].from_worker_fd < 0)
				err(1, "opening %s", argv[x + 2]);
			polls[x].fd = workers[x].from_worker_fd;
			polls[x].events = POLLIN;
		} else {
			connect_to_worker(argv[x * 3 + 2],
					  argv[x * 3 + 3],
					  argv[x * 3 + 4],
					  &workers[x].to_worker_fd,
					  &workers[x].from_worker_fd);

			polls[x].fd = workers[x].to_worker_fd;
			polls[x].events = POLLOUT;

			workers[x].send_offset = x * (size / nr_workers);
			if (x != 0)
				workers[x-1].end_of_chunk = workers[x].send_offset;
		}
		workers[x].finished_hash_entries = -1;
		poll_slots_to_workers[x] = x;
	}
	workers[nr_workers - 1].end_of_chunk = size;

	workers_left_alive = nr_workers;
	poll_slots_in_use = nr_workers;
	DBG("Start main loop\n");
	while (workers_left_alive != 0) {
		int r = poll(polls, poll_slots_in_use, -1);
		if (r < 0)
			err(1, "poll()");
		for (x = 0; x < poll_slots_in_use && r; x++) {
			if (!polls[x].revents)
				continue;
			r--;
			idx = poll_slots_to_workers[x];

			assert(!(polls[x].revents & POLLNVAL));
			if (polls[x].revents & POLLERR)
				errx(1, "error on worker %d", idx);
			if (polls[x].revents & POLLHUP) {
				if (workers[idx].to_worker_fd < 0) {
					polls[x].revents = POLLIN;
					warnx("worker %d hung up on us, but that's okay", idx);
				} else {
					errx(1, "worker %d hung up on us when it really shouldn't have done", idx);
				}
			}

			if (polls[x].revents & POLLOUT) {
				ssize_t s;
				assert(!offline);
				assert(workers[idx].send_offset < workers[idx].end_of_chunk);
				s = sendfile(workers[idx].to_worker_fd,
					     fd,
					     &workers[idx].send_offset,
					     workers[idx].end_of_chunk - workers[idx].send_offset);
				if (s == 0)
					errx(1, "worker hung up on us");
				if (s < 0)
					err(1, "sending to worker");
				assert(workers[idx].send_offset <= workers[idx].end_of_chunk);
				if (workers[idx].send_offset == workers[idx].end_of_chunk) {
					DBG("Finished sending input to worker %d\n",
					       idx);
					if (prepopulate) {
						memmove(poll_slots_to_workers + x,
							poll_slots_to_workers + x + 1,
							(poll_slots_in_use - x - 1) * sizeof(int));
						memmove(polls + x,
							polls + x + 1,
							(poll_slots_in_use - x - 1) * sizeof(polls[0]));
						poll_slots_in_use--;
						if (poll_slots_in_use == 0) {
							/* Okay, we've
							   done the
							   prepopulate
							   phase.
							   Switch
							   modes. */
							DBG("Finished prepopulate phase\n");
							for (idx = 0; idx < nr_workers; idx++) {
								polls[idx].events = POLLIN;
								polls[idx].revents = 0;
								polls[idx].fd = workers[idx].from_worker_fd;
								poll_slots_to_workers[idx] = idx;
								close(workers[idx].to_worker_fd);
								workers[idx].to_worker_fd = -1;
							}
							DBG("All workers go\n");
							poll_slots_in_use = nr_workers;
						}
					} else {
						close(workers[idx].to_worker_fd);
						workers[idx].to_worker_fd = -1;
						polls[x].events = POLLIN;
						polls[x].revents = 0;
						polls[x].fd = workers[idx].from_worker_fd;
					}
				}
			} else if (polls[x].revents & POLLIN) {
				do_rx(workers + idx,
				      idx == 0,
				      idx == nr_workers - 1,
				      idx);
			}
		}

		for (x = 0; x < poll_slots_in_use; x++) {
			idx = poll_slots_to_workers[x];
			if (workers[idx].finished) {
				DBG("expunge worker %d\n", idx);
				memmove(poll_slots_to_workers + x,
					poll_slots_to_workers + x + 1,
					(poll_slots_in_use - x - 1) * sizeof(int));
				memmove(polls + x,
					polls + x + 1,
					(poll_slots_in_use - x - 1) * sizeof(polls[0]));
				poll_slots_in_use--;
				workers_left_alive--;
				x--;
			}
		}

		mi = mallinfo();
		if (mi.uordblks > TARGET_MAX_HEAP_SIZE)
			compact_heap(workers, nr_workers, polls);

	}

	DBG("All done\n");

	for (idx = last_gced_hash_slot + 1; idx < NR_HASH_TABLE_SLOTS; idx++) {
		struct word *w;
		for (w = hash_table[idx]; w; w = w->next) {
			printf("%16d %.*s\n",
			       w->counter,
			       w->len,
			       w->word);
		}
	}
	printf("Boundary screw ups:\n");
	for (idx = 0; idx <= last_gced_hash_slot; idx++) {
		struct word *w;
		for (w = hash_table[idx]; w; w = w->next) {
			printf("%16d %.*s\n",
			       w->counter,
			       w->len,
			       w->word);
		}
	}
	DBG("Finished producing output\n");

	return 0;
}
示例#23
0
int main(int argc, char **argv)
{
  timer    *t1=NULL,*t2=NULL;
  Image    *img=NULL,*grad=NULL;
  ImageForest *fst=NULL;
  CImage   *cimg=NULL;
  Set      *Obj=NULL,*Bkg=NULL;
  char     outfile[100];
  char     *file_noext;
  /*--------------------------------------------------------*/

  void *trash = malloc(1);
  struct mallinfo info;
  int MemDinInicial, MemDinFinal;
  free(trash);
  info = mallinfo();
  MemDinInicial = info.uordblks;

  /*--------------------------------------------------------*/

  if (argc!=4){
    fprintf(stderr,"Usage: diffwatershed <image.pgm> <gradient.pgm> <seeds.txt>\n");
    fprintf(stderr,"image.pgm: image to overlay the watershed lines on it\n");
    fprintf(stderr,"gradient.pgm: gradient image to compute the watershed segmentation\n");
    fprintf(stderr,"seeds.txt: seed pixels\n");
    exit(-1);
  }

  img   = ReadImage(argv[1]);
  grad  = ReadImage(argv[2]);
  ReadSeeds(argv[3],&Obj,&Bkg);
  fst   = CreateImageForest(img);

  file_noext = strtok(argv[1],".");

  // Add object and background seeds

  t1 = Tic();
  DiffWatershed(grad,fst,Obj,Bkg,NULL); 
  t2 = Toc();
  fprintf(stdout,"Adding object and background seeds in %f ms\n",CTime(t1,t2));
  cimg = DrawLabeledRegions(img,fst->label);
  sprintf(outfile,"%s_result-a.ppm",file_noext);
  WriteCImage(cimg,outfile);
  DestroyCImage(&cimg);
  
  // Remove background trees 

  t1 = Tic();
  DiffWatershed(grad,fst,NULL,NULL,Bkg);
  t2 = Toc();
  fprintf(stdout,"Removing background trees in %f ms\n",CTime(t1,t2));
  cimg = DrawLabeledRegions(img,fst->label);
  sprintf(outfile,"%s_result-b.ppm",file_noext);
  WriteCImage(cimg,outfile);
  DestroyCImage(&cimg);

  // Adding background trees back to the forest  

  t1 = Tic();
  DiffWatershed(grad,fst,NULL,Bkg,NULL);
  t2 = Toc();
  fprintf(stdout,"Adding the removed background trees in %f ms\n",CTime(t1,t2));
  cimg = DrawLabeledRegions(img,fst->label);
  sprintf(outfile,"%s_result-c.ppm",file_noext);
  WriteCImage(cimg,outfile);
  DestroyCImage(&cimg);


  DestroyImageForest(&fst);
  DestroyImage(&img);
  DestroyImage(&grad);
  DestroySet(&Obj);
  DestroySet(&Bkg);


  /* ---------------------------------------------------------- */

  info = mallinfo();
  MemDinFinal = info.uordblks;
  if (MemDinInicial!=MemDinFinal)
    printf("\n\nDinamic memory was not completely deallocated (%d, %d)\n",
	   MemDinInicial,MemDinFinal);

  return(0);
}
示例#24
0
struct mallinfo gv_mallinfo(void)
{
  return mallinfo();
}
int smart_main(int argc, char *argv[])
{
  FAR struct mtd_dev_s *mtd;
  unsigned int i;
  int ret;

  /* Seed the random number generated */

  srand(0x93846);

  /* Create and initialize a RAM MTD device instance */

#ifdef CONFIG_EXAMPLES_SMART_ARCHINIT
  mtd = smart_archinitialize();
#else
  mtd = rammtd_initialize(g_simflash, EXAMPLES_SMART_BUFSIZE);
#endif
  if (!mtd)
    {
      message("ERROR: Failed to create RAM MTD instance\n");
      msgflush();
      exit(1);
    }

  /* Initialize to provide SMART on an MTD interface */

  MTD_IOCTL(mtd, MTDIOC_BULKERASE, 0);
  ret = smart_initialize(1, mtd);
  if (ret < 0)
    {
      message("ERROR: SMART initialization failed: %d\n", -ret);
      msgflush();
      exit(2);
    }

  /* Creaet a SMARTFS filesystem */

  ret = mksmartfs("/dev/smart1");

  /* Mount the file system */

  ret = mount("/dev/smart1", CONFIG_EXAMPLES_SMART_MOUNTPT, "smartfs", 0, NULL);
  if (ret < 0)
    {
      message("ERROR: Failed to mount the SMART volume: %d\n", errno);
      msgflush();
      exit(3);
    }

  /* Set up memory monitoring */

#ifdef CONFIG_CAN_PASS_STRUCTS
  g_mmbefore = mallinfo();
  g_mmprevious = g_mmbefore;
#else
  (void)mallinfo(&g_mmbefore);
  memcpy(&g_mmprevious, &g_mmbefore, sizeof(struct mallinfo));
#endif

  /* Loop a few times ... file the file system with some random, files,
   * delete some files randomly, fill the file system with more random file,
   * delete, etc.  This beats the FLASH very hard!
   */

#if CONFIG_EXAMPLES_SMART_NLOOPS == 0
  for (i = 0; ; i++)
#else
  for (i = 1; i <= CONFIG_EXAMPLES_SMART_NLOOPS; i++)
#endif
    {
      /* Write a files to the SMART file system until either (1) all of the
       * open file structures are utilized or until (2) SMART reports an error
       * (hopefully that the file system is full)
       */

      message("\n=== FILLING %d =============================\n", i);
      ret = smart_fillfs();
      message("Filled file system\n");
      message("  Number of files: %d\n", g_nfiles);
      message("  Number deleted:  %d\n", g_ndeleted);

      /* Directory listing */

      smart_directory();

      /* Verify all files written to FLASH */

      ret = smart_verifyfs();
      if (ret < 0)
        {
          message("ERROR: Failed to verify files\n");
          message("  Number of files: %d\n", g_nfiles);
          message("  Number deleted:  %d\n", g_ndeleted);
        }
      else
        {
#if CONFIG_EXAMPLES_SMART_VERBOSE != 0
          message("Verified!\n");
          message("  Number of files: %d\n", g_nfiles);
          message("  Number deleted:  %d\n", g_ndeleted);
#endif
        }

      /* Delete some files */

      message("\n=== DELETING %d ============================\n", i);
      ret = smart_delfiles();
      if (ret < 0)
        {
          message("ERROR: Failed to delete files\n");
          message("  Number of files: %d\n", g_nfiles);
          message("  Number deleted:  %d\n", g_ndeleted);
        }
      else
        {
          message("Deleted some files\n");
          message("  Number of files: %d\n", g_nfiles);
          message("  Number deleted:  %d\n", g_ndeleted);
        }

      /* Directory listing */

      smart_directory();

      /* Verify all files written to FLASH */

      ret = smart_verifyfs();
      if (ret < 0)
        {
          message("ERROR: Failed to verify files\n");
          message("  Number of files: %d\n", g_nfiles);
          message("  Number deleted:  %d\n", g_ndeleted);
        }
      else
        {
#if CONFIG_EXAMPLES_SMART_VERBOSE != 0
          message("Verified!\n");
          message("  Number of files: %d\n", g_nfiles);
          message("  Number deleted:  %d\n", g_ndeleted);
#endif
        }

      /* Show memory usage */

      smart_loopmemusage();
      msgflush();
    }

  /* Delete all files then show memory usage again */

  smart_delallfiles();
  smart_endmemusage();
  msgflush();
  return 0;
}
示例#26
0
文件: memlock.c 项目: cardamon/lvm2
static void _allocate_memory(void)
{
#ifndef VALGRIND_POOL
	void *stack_mem;
	struct rlimit limit;
	int i, area = 0, missing = _size_malloc_tmp, max_areas = 32, hblks;
	char *areas[max_areas];

	/* Check if we could preallocate requested stack */
	if ((getrlimit (RLIMIT_STACK, &limit) == 0) &&
	    ((_size_stack * 2) < limit.rlim_cur) &&
	    ((stack_mem = alloca(_size_stack))))
		_touch_memory(stack_mem, _size_stack);
	/* FIXME else warn user setting got ignored */

        /*
         *  When a brk() fails due to fragmented address space (which sometimes
         *  happens when we try to grab 8M or so), glibc will make a new
         *  arena. In this arena, the rules for using “direct” mmap are relaxed,
         *  circumventing the MAX_MMAPs and MMAP_THRESHOLD settings. We can,
         *  however, detect when this happens with mallinfo() and try to co-opt
         *  malloc into using MMAP as a MORECORE substitute instead of returning
         *  MMAP'd memory directly. Since MMAP-as-MORECORE does not munmap the
         *  memory on free(), this is good enough for our purposes.
         */
	while (missing > 0) {
		struct mallinfo inf = mallinfo();
		hblks = inf.hblks;

		if ((areas[area] = malloc(_size_malloc_tmp)))
			_touch_memory(areas[area], _size_malloc_tmp);

		inf = mallinfo();

		if (hblks < inf.hblks) {
			/* malloc cheated and used mmap, even though we told it
			   not to; we try with twice as many areas, each half
			   the size, to circumvent the faulty logic in glibc */
			free(areas[area]);
			_size_malloc_tmp /= 2;
		} else {
			++ area;
			missing -= _size_malloc_tmp;
		}

		if (area == max_areas && missing > 0) {
			/* Too bad. Warn the user and proceed, as things are
			 * most likely going to work out anyway. */
			log_warn("WARNING: Failed to reserve memory, %d bytes missing.", missing);
			break;
		}
	}

	if ((_malloc_mem = malloc(_size_malloc)))
		_touch_memory(_malloc_mem, _size_malloc);

	/* free up the reserves so subsequent malloc's can use that memory */
	for (i = 0; i < area; ++i)
		free(areas[i]);
#endif
}
示例#27
0
int bc_tester_run_tests(const char *suite_name, const char *test_name) {
	int i;

	/* initialize the CUnit test registry */
	if (CUE_SUCCESS != CU_initialize_registry())
		return CU_get_error();

	for (i = 0; i < nb_test_suites; i++) {
		bc_tester_run_suite(test_suite[i]);
	}
#ifdef HAVE_CU_GET_SUITE
	CU_set_suite_start_handler(suite_start_message_handler);
	CU_set_suite_complete_handler(suite_complete_message_handler);
	CU_set_test_start_handler(test_start_message_handler);
	CU_set_test_complete_handler(test_complete_message_handler);
#endif
	CU_set_all_test_complete_handler(all_complete_message_handler);
	CU_set_suite_init_failure_handler(suite_init_failure_message_handler);
	CU_set_suite_cleanup_failure_handler(suite_cleanup_failure_message_handler);

	if( xml_enabled != 0 ){
		CU_automated_run_tests();
	} else {

#ifndef HAVE_CU_GET_SUITE
		if( suite_name ){
			bc_tester_printf(bc_printf_verbosity_info, "Tester compiled without CU_get_suite() function, running all tests instead of suite '%s'", suite_name);
		}
#else
		if (suite_name){
			CU_pSuite suite;
			suite=CU_get_suite(suite_name);
			if (!suite) {
				bc_tester_printf(bc_printf_verbosity_error, "Could not find suite '%s'. Available suites are:", suite_name);
				bc_tester_list_suites();
				return -1;
			} else if (test_name) {
				CU_pTest test=CU_get_test_by_name(test_name, suite);
				if (!test) {
					bc_tester_printf(bc_printf_verbosity_error, "Could not find test '%s' in suite '%s'. Available tests are:", test_name, suite_name);
					// do not use suite_name here, since this method is case sensitive
					bc_tester_list_tests(suite->pName);
					return -2;
				} else {
					CU_ErrorCode err= CU_run_test(suite, test);
					if (err != CUE_SUCCESS) bc_tester_printf(bc_printf_verbosity_error, "CU_basic_run_test error %d", err);
				}
			} else {
				CU_run_suite(suite);
			}
		}
		else
#endif
		{
#ifdef HAVE_CU_CURSES
			if (curses) {
			/* Run tests using the CUnit curses interface */
				CU_curses_run_tests();
			}
			else
#endif
			{
				/* Run all tests using the CUnit Basic interface */
				CU_run_all_tests();
			}
		}
	}
#ifdef __linux
	bc_tester_printf(bc_printf_verbosity_info, "Still %i kilobytes allocated when all tests are finished.",
					 mallinfo().uordblks / 1024);
#endif

	return CU_get_number_of_tests_failed()!=0;

}
示例#28
0
int 
main(int argc, char *argv[])
{
   unsigned int i;
   bitfield *b1, *b2;

#ifdef MALLINFO
   struct mallinfo meminfo;
#endif

   long clk_tck = 0;
   const char * header_format = "%5s %8s %8s %8s %8s %8s %8s %8s %8s %8s %8s\n";
   const char * data_format   = "%5d %8.3f %8.3f %8.3f %8.3f %8.3f %8.3f %8.3f"
                                " %8.3f %8.3f %8d\n";

   /* evaluate commandline args */
   if (argc > 1) {
      test_bf_loops = atoi(argv[1]);
   }

   /* create array to hold bitfields, to be used per test loop */
   b1 = (bitfield *)malloc(test_bf_loops * sizeof (bitfield));
   b2 = (bitfield *)malloc(test_bf_loops * sizeof (bitfield));
   printf("performing %d loops per action\n", test_bf_loops);

   /* test nullpointer actions */
   printf("\ntesting nullpointer actions\n");
   test_nullpointer_actions();

   printf("\ntesting bit operations\n");
   test_bitops();

   /* test performance */
   clk_tck = sysconf(_SC_CLK_TCK); /* JG: TODO: sge_sysconf? */
   printf("\ntesting performance of all actions\n");
   printf(header_format, "size", "create", "free",
          "copy", "bwcopy",
          "set", "get",
          "clear", "reset", "changed", "mem");

   for (i = 0; i <= test_bf_max_size; i += 10) {
      struct tms tms_buffer;
      clock_t now, start;
      double prof_create = 0.0;
      double prof_free = 0.0;
      double prof_copy = 0.0;
      double prof_bwcopy = 0.0;
      double prof_set = 0.0;
      double prof_get = 0.0;
      double prof_clear = 0.0;
      double prof_reset = 0.0;
      double prof_changed = 0.0;

      unsigned int loops, index;

      srand(time(0));

      /* creation of bitfields */
      start = times(&tms_buffer);
      for (loops = 0; loops < test_bf_loops; loops++) {
         sge_bitfield_init(&b1[loops], i);
         sge_bitfield_init(&b2[loops], i);
      }
      now = times(&tms_buffer);
      prof_create = (now - start) * 1.0 / clk_tck;

      /* copy */
      start = times(&tms_buffer);
      for (loops = 0; loops < test_bf_loops; loops++) {
         sge_bitfield_copy(&b1[loops], &b2[loops]);
      }
      now = times(&tms_buffer);
      prof_copy = (now - start) * 1.0 / clk_tck;

      /* bitwise copy */
      start = times(&tms_buffer);
      for (loops = 0; loops < test_bf_loops; loops++) {
         sge_bitfield_bitwise_copy(&b2[loops], &b2[loops]);
      }
      now = times(&tms_buffer);
      prof_bwcopy = (now - start) * 1.0 / clk_tck;

      /* set/get/clear */
      index = rand() % (i + 1) - 1;
      start = times(&tms_buffer);
      for (loops = 0; loops < test_bf_loops; loops++) {
         sge_bitfield_set(&b1[loops], index);
      }
      now = times(&tms_buffer);
      prof_set = (now - start) * 1.0 / clk_tck;

      index = rand() % (i + 1) - 1;
      start = times(&tms_buffer);
      for (loops = 0; loops < test_bf_loops; loops++) {
         sge_bitfield_get(&b1[loops], index);
      }
      now = times(&tms_buffer);
      prof_get = (now - start) * 1.0 / clk_tck;

      index = rand() % (i + 1) - 1;
      start = times(&tms_buffer);
      for (loops = 0; loops < test_bf_loops; loops++) {
         sge_bitfield_clear(&b1[loops], index);
      }
      now = times(&tms_buffer);
      prof_clear = (now - start) * 1.0 / clk_tck;

      /* reset */
      start = times(&tms_buffer);
      for (loops = 0; loops < test_bf_loops; loops++) {
         sge_bitfield_reset(&b1[loops]);
      }
      now = times(&tms_buffer);
      prof_reset = (now - start) * 1.0 / clk_tck;

      /* changed */
      start = times(&tms_buffer);
      for (loops = 0; loops < test_bf_loops; loops++) {
         sge_bitfield_changed(&b1[loops]);
      }
      now = times(&tms_buffer);
      prof_changed = (now - start) * 1.0 / clk_tck;

      /* evaluate memory usage */
#ifdef MALLINFO
      meminfo = mallinfo();
#endif

      /* freeing of bitfields */
      start = times(&tms_buffer);
      for (loops = 0; loops < test_bf_loops; loops++) {
         sge_bitfield_free_data(&b1[loops]);
         sge_bitfield_free_data(&b2[loops]);
      }
      now = times(&tms_buffer);
      prof_free = (now - start) * 1.0 / clk_tck;

      printf(data_format, i, prof_create, prof_free,
             prof_copy, prof_bwcopy,
             prof_set, prof_get, prof_clear,
             prof_reset, prof_changed,
#ifdef MALLINFO
             (meminfo.usmblks + meminfo.uordblks) / 1024
#else
             0
#endif
            );
   }

   /* free memory used for bitfields */
   free(b1);
   free(b2);
   return EXIT_SUCCESS;
}
示例#29
0
int
main( int argc, char *argv[] )
{
    char *str1, *str2, *str3;
    int j;
    int poolmax;

    CYG_TEST_INIT();

    CYG_TEST_INFO("Starting stress tests from testcase " __FILE__ " for C "
                  "library malloc(), calloc() and free() functions");

    poolmax = mallinfo().maxfree;
    
    if ( poolmax <= 0 ) {
        CYG_TEST_FAIL_FINISH( "Can't determine allocation size to use" );
    }

    if ( poolmax < 300 )
    {
        CYG_TEST_FAIL_FINISH("This testcase cannot safely be used with a "
                             "memory pool for malloc less than 300 bytes");
    } // if


    for ( j=1; j < NUM_ITERATIONS; j++)
    {
//        if ((j % 100) == 0)
//            CYG_TEST_STILL_ALIVE( j, "Multiple mallocs and frees continuing" );

        
        str1 = (char *)safe_malloc(50);
        fill_with_data( str1, 50 );
        str2 = (char *)safe_calloc(11);
        fill_with_data( str2, 11 );
        str3 = (char *)safe_malloc(32);
        fill_with_data( str3, 32 );

        free(str2);
        free(str1);

        str2 = (char *)safe_calloc(11);
        fill_with_data( str2, 11 );
        free(str2);

        str1 = (char *)safe_calloc(50);
        fill_with_data( str1, 50 );
        free(str3);

        str3 = (char *)safe_malloc(32);
        fill_with_data( str3, 32 );
        free(str1);

        str2 = (char *)safe_calloc(11);
        fill_with_data( str2, 11 );
        str1 = (char *)safe_malloc(50);
        fill_with_data( str1, 50 );

        free(str3);
        free(str1);
        free(str2);

        if (problem != 0)
            break;
    } // for

    // Did it completely successfully?
    if (j==NUM_ITERATIONS)
        CYG_TEST_PASS("Stress test completed successfully");

    CYG_TEST_FINISH("Finished stress tests from testcase " __FILE__ " for C "
                    "library malloc(), calloc() and free() functions");

    return 0;
} // main()
示例#30
0
文件: driver.c 项目: sos22/dwc
static void
compact_heap(struct worker *worker, int nr_workers, struct pollfd *polls)
{
	int x;
	int earliest_finished_slot;
	struct mallinfo mi;
	int throttle_worker_slot;
	bool some_worker_unready;

	DBG("Start hash table GC\n");

	/* Make sure that every worker has its prefix and suffix
	 * string before doing anything */
	some_worker_unready = false;
	for (x = 0; x < nr_workers; x++) {
		if (!worker[x].prefix_string || !worker[x].suffix_string) {
			DBG("Worker %d hasn't completed its boundary strings", x);
			some_worker_unready = true;
		}
	}

	if (some_worker_unready) {
		/* Okay, we're not ready for hash compaction.
		   Throttle every worker which has prefix and
		   suffix. */
		for (x = 0; x < nr_workers; x++) {
			if (worker[x].prefix_string && worker[x].suffix_string) {
				if (polls[x].events & POLLIN)
					DBG("Throttle %d for pre-compaction\n", x);
				polls[x].events &= ~POLLIN;
			}
		}
		return;
	}

	earliest_finished_slot = NR_HASH_TABLE_SLOTS;
	for (x = 0; x < nr_workers; x++) {
		if (worker[x].finished_hash_entries < earliest_finished_slot)
			earliest_finished_slot = worker[x].finished_hash_entries;
	}
	DBG("Discarding slots up to %d\n", earliest_finished_slot);
	for (x = 0; x <= earliest_finished_slot; x++) {
		struct word *w, *n;
		for (w = hash_table[x]; w; w = n) {
			n = w->next;
			printf("%16d %.*s\n",
			       w->counter,
			       w->len,
			       w->word);
			free(w);
		}
		hash_table[x] = NULL;
	}
	last_gced_hash_slot = earliest_finished_slot;
	mi = mallinfo();
	DBG("Done hash table GC; %d bytes still in use in heap\n", mi.uordblks);

	if (mi.uordblks >= THROTTLE_HEAP_SIZE) {
		throttle_worker_slot = earliest_finished_slot + 10000;
		DBG("Going to throttle mode; barrier is %d\n", throttle_worker_slot);
	} else {
		throttle_worker_slot = NR_HASH_TABLE_SLOTS;
		DBG("Throttle disabled\n");
	}

	for (x = 0; x < nr_workers; x++) {
		if (worker[x].finished_hash_entries >= throttle_worker_slot) {
			if (polls[x].events & POLLIN)
				DBG("Worker %d throttles at %d\n", x,
				    worker[x].finished_hash_entries);
			polls[x].events &= ~POLLIN;
		} else if (worker[x].to_worker_fd == -1) {
			if (!(polls[x].events & POLLIN))
				DBG("worker %d unthrottled at %d\n", x,
				    worker[x].finished_hash_entries);
			polls[x].events |= POLLIN;
		} else {
			DBG("worker %d isn't ready to receive results yet\n", x);
		}
	}
}