Esempio n. 1
0
static VALUE dictinfo_size(VALUE self) {
    return INT2FIX(get_info(self)->size);
}
Esempio n. 2
0
static void xmpp_iq_join_channel_cb(const char *msg,
                                    enum xmpp_msg_type type,
                                    void *args)
{
    /* Answer
      <iq from='masterserver@warface/pve_12' to='xxxxxx@warface/GameClient' type='result'>
       <query xmlns='urn:cryonline:k01'>
        <data query_name='join_channel' compressedData='...' originalSize='13480'/>
       </query>
      </iq>
     */

    struct cb_args *a = (struct cb_args *) args;
    char *data = wf_get_query_content(msg);

    if (type & XMPP_TYPE_ERROR)
    {
        fprintf(stderr, "Failed to join channel\nReason: ");

        int code = get_info_int(msg, "code='", "'", NULL);
        int custom_code = get_info_int(msg, "custom_code='", "'", NULL);

        switch (code)
        {
            case 1006:
                fprintf(stderr, "QoS limit reached\n");
                break;
            case 503:
                fprintf(stderr, "Invalid channel (%s)\n", a->channel);
                break;
            case 8:
                switch (custom_code)
                {
                    case 0:
                        fprintf(stderr, "Invalid token (%s) or userid (%s)\n",
                                session.active_token,
                                session.online_id);
                        break;
                    case 1:
                        fprintf(stderr, "Invalid profile_id (%s)\n",
                                session.profile_id);
                        break;
                    case 2:
                        fprintf(stderr, "Game version mismatch (%s)\n",
                                game_version_get());
                        break;
                    case 3:
                        fprintf(stderr, "Banned\n");
                        break;
                    case 5:
                        fprintf(stderr, "Rank restricted\n");
                        break;
                    default:
                        fprintf(stderr, "Unknown code (%d)\n", custom_code);
                        break;
                }
                break;
            default:
                fprintf(stderr, "Unknown\n");
                break;
        }
    }
    else
    {
        /* Leave previous room if any */
        xmpp_iq_gameroom_leave();

        if (data != NULL)
        {
            session.experience = get_info_int(data, "experience='", "'", "EXPERIENCE");

            if (a->channel != NULL)
            {
                free(session.channel);
                session.channel = strdup(a->channel);
            }


            char *m = data;

            while ((m = strstr(m, "<notif")))
            {
                char *notif = get_info(m, "<notif", "</notif>", NULL);

                xmpp_iq_confirm_notification(notif);
                free(notif);
                ++m;
            }
        }

        /* Ask for today's missions list */
        mission_list_update(NULL, NULL);

        /* Inform to k01 our status */
        xmpp_iq_player_status(STATUS_ONLINE | STATUS_LOBBY);

        if (a->cb)
            a->cb(a->args);
    }

    free(data);
    free(a->channel);
    free(a);
}
Esempio n. 3
0
NativeObj* get_from_NativePtr(JNIEnv* env, jobject obj) {
  auto info = get_info(env, __LINE__);
  int64_t addrA = env->GetLongField(obj, info->addrA_id_);
  return reinterpret_cast<NativeObj*>(addrA);
}
Esempio n. 4
0
SANE_Status
sane_init (SANE_Int * version_code, SANE_Auth_Callback __sane_unused__ authorize)
{

  char f[] = "sane_init";
  char dev_name[PATH_MAX], *p;
  size_t len;
  FILE *fp;
  int baud;

  DBG_INIT ();

  if (version_code)
    *version_code = SANE_VERSION_CODE (SANE_CURRENT_MAJOR, V_MINOR, 0);

  fp = sanei_config_open (DC210_CONFIG_FILE);

  /* defaults */
  Camera.baud = DEFAULT_BAUD_RATE;
  Camera.tty_name = DEFAULT_TTY;

  if (!fp)
    {
      /* default to /dev/whatever instead of insisting on config file */
      DBG (1, "%s:  missing config file '%s'\n", f, DC210_CONFIG_FILE);
    }
  else
    {
      while (sanei_config_read (dev_name, sizeof (dev_name), fp))
	{
	  dev_name[sizeof (dev_name) - 1] = '\0';
	  DBG (20, "%s:  config- %s\n", f, dev_name);

	  if (dev_name[0] == '#')
	    continue;		/* ignore line comments */
	  len = strlen (dev_name);
	  if (!len)
	    continue;		/* ignore empty lines */
	  if (strncmp (dev_name, "port=", 5) == 0)
	    {
	      p = strchr (dev_name, '/');
	      if (p)
		Camera.tty_name = strdup (p);
	      DBG (20, "Config file port=%s\n", Camera.tty_name);
	    }
	  else if (strncmp (dev_name, "baud=", 5) == 0)
	    {
	      baud = atoi (&dev_name[5]);
	      switch (baud)
		{
		case 9600:
		  Camera.baud = B9600;
		  break;
		case 19200:
		  Camera.baud = B19200;
		  break;
		case 38400:
		  Camera.baud = B38400;
		  break;
#ifdef B57600
		case 57600:
		  Camera.baud = B57600;
		  break;
#endif
#ifdef B115200
		case 115200:
		  Camera.baud = B115200;
		  break;
#endif
		}
	      DBG (20, "Config file baud=%d\n", Camera.baud);
	    }
	  else if (strcmp (dev_name, "dumpinquiry") == 0)
	    {
	      dumpinquiry = SANE_TRUE;
	    }
	  else if (strncmp (dev_name, "cmdrespause=", 12) == 0)
	    {
	      cmdrespause = atoi (&dev_name[12]);
	      DBG (20, "Config file cmdrespause=%lu\n", cmdrespause);
	    }
	  else if (strncmp (dev_name, "breakpause=", 11) == 0)
	    {
	      breakpause = atoi (&dev_name[11]);
	      DBG (20, "Config file breakpause=%lu\n", breakpause);
	    }
	}
      fclose (fp);
    }

  if (init_dc210 (&Camera) == -1)
    return SANE_STATUS_INVAL;

  if (get_info (&Camera) == -1)
    {
      DBG (2, "error: could not get info\n");
      close_dc210 (Camera.fd);
      return SANE_STATUS_INVAL;
    }
  if (Camera.pic_taken == 0)
    {
      sod[DC210_OPT_IMAGE_NUMBER].cap |= SANE_CAP_INACTIVE;
      image_range.min = 0;
      image_range.max = 0;
    }
  else
    {
      sod[DC210_OPT_IMAGE_NUMBER].cap &= ~SANE_CAP_INACTIVE;
      image_range.min = 1;
      image_range.max = Camera.pic_taken;
    }


  /* load the current images array */
  Camera.Pictures = get_pictures_info ();

  if (Camera.pic_taken == 0)
    {
      Camera.current_picture_number = 0;
      parms.bytes_per_line = 0;
      parms.pixels_per_line = 0;
      parms.lines = 0;
    }
  else
    {
      Camera.current_picture_number = 1;
      if (Camera.Pictures[Camera.current_picture_number - 1].low_res)
	{
	  parms.bytes_per_line = 640 * 3;
	  parms.pixels_per_line = 640;
	  parms.lines = 480;
	}
      else
	{
	  parms.bytes_per_line = 1152 * 3;
	  parms.pixels_per_line = 1152;
	  parms.lines = 864;
	}
    }

  if (dumpinquiry)
    {
      DBG (0, "\nCamera information:\n~~~~~~~~~~~~~~~~~\n\n");
      DBG (0, "Model...........: DC%x\n", Camera.model);
      DBG (0, "Firmware version: %d.%d\n", Camera.ver_major,
	   Camera.ver_minor);
      DBG (0, "Pictures........: %d/%d\n", Camera.pic_taken,
	   Camera.pic_taken + Camera.pic_left);
      DBG (0, "Resolution......: %s\n",
	   Camera.flags.low_res ? "low" : "high");
      DBG (0, "Battery state...: %s\n",
	   Camera.flags.low_batt ? "low" : "good");
    }

  return SANE_STATUS_GOOD;
}
Esempio n. 5
0
//-----------------------------------------------------------------------------
bool Filesystem::exists(const char* relative_path)
{
	FilesystemEntry dummy;

	return get_info(relative_path, dummy);
}
Esempio n. 6
0
void node_sampler::read (audio_buffer& buf, int start, int end)
{
    const sample_buffer* rate = get_input<sample_buffer> (
        node0::LINK_CONTROL, IN_C_RATE);
    const sample* rate_buf = rate ? (const sample*) &const_range (*rate) [0] : 0;

    float base_factor =
	(float) m_reader->frame_rate () / get_info ().sample_rate * m_param_rate;

    int must_read;
    int nread;
    float factor;

    bool backwards = false;;
    bool high_latency = false;

    if (m_update_mutex.try_lock ())
    {
        m_scaler.set_tempo (m_param_tempo);
        m_scaler.set_pitch (m_param_pitch);
        m_update_mutex.unlock ();
    }

    if (m_param_tempo != 1.0f ||
	m_param_pitch != 1.0f)
	high_latency = true;

    if (base_factor < 0) {
	backwards = true;
	base_factor = -base_factor;
    }
    factor = base_factor;

    assert(end >= start);
    while(m_scaler.available() < static_cast<std::size_t>(
            (high_latency ?
             TIME_STRETCH_MIN_SAMPLES :
             end - start))) {
        if (rate)
	    factor = base_factor + base_factor * rate_buf[(int) m_ctrl_pos];

	if (backwards != m_fetcher.is_backwards ())
	    m_fetcher.set_backwards (backwards);

	if (factor < 0.2)
	    factor = 0.2;

	must_read = high_latency ? get_info ().block_size : SMALL_BLOCK_SIZE;
	if (factor * m_param_tempo < 1.0)
	    must_read = (float)must_read * factor * m_param_tempo;
	else
	    must_read = must_read;

	m_update_mutex.lock();
	nread = m_fetcher.take (sub_range (range (m_inbuf), 0, must_read));

	if (nread)
        {
	    m_ctrl_pos += (float) nread / (factor * m_param_tempo);
	    if (m_ctrl_pos >= get_info ().block_size)
		m_ctrl_pos = base::phase(m_ctrl_pos) +
                    ((int) m_ctrl_pos % get_info ().block_size);

            m_scaler.set_rate (factor);
	    m_scaler.update (sub_range (range (m_inbuf), 0, nread));
	}

	m_update_mutex.unlock();
    }

    m_update_mutex.lock();
    m_scaler.receive (sub_range (range (m_inbuf), 0, end - start));
    m_update_mutex.unlock();

    copy_and_convert_frames (sub_range (range (m_inbuf), 0, end - start),
                             sub_range (range (buf), start, end - start));
}
Esempio n. 7
0
static inline void cpu_probe(void)
{
#ifdef CONFIG_CPU_MIPS32
	unsigned long config0 = read_32bit_cp0_register(CP0_CONFIG);
	unsigned long config1;

        if (config0 & (1 << 31)) {
		/* MIPS32 compliant CPU. Read Config 1 register. */
		mips_cpu.isa_level = MIPS_CPU_ISA_M32;
		mips_cpu.options = MIPS_CPU_TLB | MIPS_CPU_4KEX | 
			MIPS_CPU_4KTLB | MIPS_CPU_COUNTER | MIPS_CPU_DIVEC;
		config1 = read_mips32_cp0_config1();
		if (config1 & (1 << 3))
			mips_cpu.options |= MIPS_CPU_WATCH;
		if (config1 & (1 << 2))
			mips_cpu.options |= MIPS_CPU_MIPS16;
		if (config1 & (1 << 1))
			mips_cpu.options |= MIPS_CPU_EJTAG;
		if (config1 & 1)
			mips_cpu.options |= MIPS_CPU_FPU;
		mips_cpu.scache.flags = MIPS_CACHE_NOT_PRESENT;
	}
#endif
	mips_cpu.processor_id = read_32bit_cp0_register(CP0_PRID);
	switch (mips_cpu.processor_id & 0xff0000) {
	case PRID_COMP_LEGACY:
		switch (mips_cpu.processor_id & 0xff00) {
		case PRID_IMP_R2000:
			mips_cpu.cputype = CPU_R2000;
			mips_cpu.isa_level = MIPS_CPU_ISA_I;
			mips_cpu.options = MIPS_CPU_TLB | MIPS_CPU_NOFPUEX;
			if (cpu_has_fpu())
				mips_cpu.options |= MIPS_CPU_FPU;
			mips_cpu.tlbsize = 64;
			break;
		case PRID_IMP_R3000:
			if ((mips_cpu.processor_id & 0xff) == PRID_REV_R3000A)
				if (cpu_has_confreg())
					mips_cpu.cputype = CPU_R3081E;
				else
					mips_cpu.cputype = CPU_R3000A;
			else
				mips_cpu.cputype = CPU_R3000;
			mips_cpu.isa_level = MIPS_CPU_ISA_I;
			mips_cpu.options = MIPS_CPU_TLB | MIPS_CPU_NOFPUEX;
			if (cpu_has_fpu())
				mips_cpu.options |= MIPS_CPU_FPU;
			mips_cpu.tlbsize = 64;
			break;
		case PRID_IMP_R4000:
			if ((mips_cpu.processor_id & 0xff) == PRID_REV_R4400)
				mips_cpu.cputype = CPU_R4400SC;
			else
				mips_cpu.cputype = CPU_R4000SC;
			mips_cpu.isa_level = MIPS_CPU_ISA_III;
			mips_cpu.options = R4K_OPTS | MIPS_CPU_FPU |
			                   MIPS_CPU_32FPR | MIPS_CPU_WATCH |
			                   MIPS_CPU_VCE;
			mips_cpu.tlbsize = 48;
			break;
                case PRID_IMP_VR41XX:
                        mips_cpu.cputype = CPU_VR41XX;
                        mips_cpu.isa_level = MIPS_CPU_ISA_III;
                        mips_cpu.options = R4K_OPTS;
                        mips_cpu.tlbsize = 32;
                        break;
		case PRID_IMP_R4300:
			mips_cpu.cputype = CPU_R4300;
			mips_cpu.isa_level = MIPS_CPU_ISA_III;
			mips_cpu.options = R4K_OPTS | MIPS_CPU_FPU |
					   MIPS_CPU_32FPR;
			mips_cpu.tlbsize = 32;
			break;
		case PRID_IMP_R4600:
			mips_cpu.cputype = CPU_R4600;
			mips_cpu.isa_level = MIPS_CPU_ISA_III;
			mips_cpu.options = R4K_OPTS | MIPS_CPU_FPU;
			mips_cpu.tlbsize = 48;
			break;
		#if 0
 		case PRID_IMP_R4650:
			/*
			 * This processor doesn't have an MMU, so it's not
			 * "real easy" to run Linux on it. It is left purely
			 * for documentation.  Commented out because it shares
			 * it's c0_prid id number with the TX3900.
			 */
	 		mips_cpu.cputype = CPU_R4650;
		 	mips_cpu.isa_level = MIPS_CPU_ISA_III;
			mips_cpu.options = R4K_OPTS | MIPS_CPU_FPU;
		        mips_cpu.tlbsize = 48;
			break;
		#endif
		case PRID_IMP_TX39:
			mips_cpu.isa_level = MIPS_CPU_ISA_I;
			mips_cpu.options = MIPS_CPU_TLB;

			if ((mips_cpu.processor_id & 0xf0) ==
			    (PRID_REV_TX3927 & 0xf0)) {
				mips_cpu.cputype = CPU_TX3927;
				mips_cpu.tlbsize = 64;
				mips_cpu.icache.ways = 2;
				mips_cpu.dcache.ways = 2;
			} else {
				switch (mips_cpu.processor_id & 0xff) {
				case PRID_REV_TX3912:
					mips_cpu.cputype = CPU_TX3912;
					mips_cpu.tlbsize = 32;
					break;
				case PRID_REV_TX3922:
					mips_cpu.cputype = CPU_TX3922;
					mips_cpu.tlbsize = 64;
					break;
				default:
					mips_cpu.cputype = CPU_UNKNOWN;
					break;
				}
			}
			break;
		case PRID_IMP_R4700:
			mips_cpu.cputype = CPU_R4700;
			mips_cpu.isa_level = MIPS_CPU_ISA_III;
			mips_cpu.options = R4K_OPTS | MIPS_CPU_FPU |
			                   MIPS_CPU_32FPR;
			mips_cpu.tlbsize = 48;
			break;
		case PRID_IMP_TX49:
			mips_cpu.cputype = CPU_TX49XX;
			mips_cpu.isa_level = MIPS_CPU_ISA_III;
			mips_cpu.options = R4K_OPTS | MIPS_CPU_FPU |
			                   MIPS_CPU_32FPR;
			mips_cpu.tlbsize = 48;
			mips_cpu.icache.ways = 4;
			mips_cpu.dcache.ways = 4;
			break;
		case PRID_IMP_R5000:
			mips_cpu.cputype = CPU_R5000;
			mips_cpu.isa_level = MIPS_CPU_ISA_IV; 
			mips_cpu.options = R4K_OPTS | MIPS_CPU_FPU |
			                   MIPS_CPU_32FPR;
			mips_cpu.tlbsize = 48;
			break;
		case PRID_IMP_R5432:
			mips_cpu.cputype = CPU_R5432;
			mips_cpu.isa_level = MIPS_CPU_ISA_IV; 
			mips_cpu.options = R4K_OPTS | MIPS_CPU_FPU |
			                   MIPS_CPU_32FPR | MIPS_CPU_WATCH;
			mips_cpu.tlbsize = 48;
			break;
		case PRID_IMP_R5500:
			mips_cpu.cputype = CPU_R5500;
			mips_cpu.isa_level = MIPS_CPU_ISA_IV; 
			mips_cpu.options = R4K_OPTS | MIPS_CPU_FPU |
			                   MIPS_CPU_32FPR | MIPS_CPU_WATCH;
			mips_cpu.tlbsize = 48;
			break;
		case PRID_IMP_NEVADA:
			mips_cpu.cputype = CPU_NEVADA;
			mips_cpu.isa_level = MIPS_CPU_ISA_IV; 
			mips_cpu.options = R4K_OPTS | MIPS_CPU_FPU |
			                   MIPS_CPU_32FPR | MIPS_CPU_DIVEC;
			mips_cpu.tlbsize = 48;
			mips_cpu.icache.ways = 2;
			mips_cpu.dcache.ways = 2;
			break;
		case PRID_IMP_R6000:
			mips_cpu.cputype = CPU_R6000;
			mips_cpu.isa_level = MIPS_CPU_ISA_II;
			mips_cpu.options = MIPS_CPU_TLB | MIPS_CPU_FPU;
			mips_cpu.tlbsize = 32;
			break;
		case PRID_IMP_R6000A:
			mips_cpu.cputype = CPU_R6000A;
			mips_cpu.isa_level = MIPS_CPU_ISA_II;
			mips_cpu.options = MIPS_CPU_TLB | MIPS_CPU_FPU;
			mips_cpu.tlbsize = 32;
			break;
		case PRID_IMP_RM7000:
			mips_cpu.cputype = CPU_RM7000;
			mips_cpu.isa_level = MIPS_CPU_ISA_IV;
			mips_cpu.options = R4K_OPTS | MIPS_CPU_FPU |
			                   MIPS_CPU_32FPR;
			/*
			 * Undocumented RM7000:  Bit 29 in the info register of
			 * the RM7000 v2.0 indicates if the TLB has 48 or 64
			 * entries.
			 *
			 * 29      1 =>    64 entry JTLB
			 *         0 =>    48 entry JTLB
			 */
			mips_cpu.tlbsize = (get_info() & (1 << 29)) ? 64 : 48;
			break;
		case PRID_IMP_R8000:
			mips_cpu.cputype = CPU_R8000;
			mips_cpu.isa_level = MIPS_CPU_ISA_IV;
			mips_cpu.options = MIPS_CPU_TLB | MIPS_CPU_4KEX |
				           MIPS_CPU_FPU | MIPS_CPU_32FPR;
			mips_cpu.tlbsize = 384;      /* has wierd TLB: 3-way x 128 */
			break;
		case PRID_IMP_R10000:
			mips_cpu.cputype = CPU_R10000;
			mips_cpu.isa_level = MIPS_CPU_ISA_IV;
			mips_cpu.options = MIPS_CPU_TLB | MIPS_CPU_4KEX | 
				           MIPS_CPU_FPU | MIPS_CPU_32FPR | 
				           MIPS_CPU_COUNTER | MIPS_CPU_WATCH;
			mips_cpu.tlbsize = 64;
			break;
		case PRID_IMP_R12000:
			mips_cpu.cputype = CPU_R12000;
			mips_cpu.isa_level = MIPS_CPU_ISA_IV;
			mips_cpu.options = MIPS_CPU_TLB | MIPS_CPU_4KEX | 
				           MIPS_CPU_FPU | MIPS_CPU_32FPR | 
				           MIPS_CPU_COUNTER | MIPS_CPU_WATCH;
			mips_cpu.tlbsize = 64;
			break;
		default:
			mips_cpu.cputype = CPU_UNKNOWN;
			break;
		}
		break;
#ifdef CONFIG_CPU_MIPS32
	case PRID_COMP_MIPS:
		switch (mips_cpu.processor_id & 0xff00) {
		case PRID_IMP_4KC:
			mips_cpu.cputype = CPU_4KC;
			break;
		case PRID_IMP_4KEC:
			mips_cpu.cputype = CPU_4KEC;
			break;
		case PRID_IMP_4KSC:
			mips_cpu.cputype = CPU_4KSC;
			break;
		case PRID_IMP_5KC:
			mips_cpu.cputype = CPU_5KC;
			mips_cpu.isa_level = MIPS_CPU_ISA_M64;
			break;
		case PRID_IMP_20KC:
			mips_cpu.cputype = CPU_20KC;
			mips_cpu.isa_level = MIPS_CPU_ISA_M64;
			break;
		default:
			mips_cpu.cputype = CPU_UNKNOWN;
			break;
		}		
		break;
	case PRID_COMP_ALCHEMY:
		switch (mips_cpu.processor_id & 0xff00) {
		case PRID_IMP_AU1_REV1:
		case PRID_IMP_AU1_REV2:
			if (mips_cpu.processor_id & 0xff000000)
				mips_cpu.cputype = CPU_AU1500;
			else
				mips_cpu.cputype = CPU_AU1000;
			break;
		default:
			mips_cpu.cputype = CPU_UNKNOWN;
			break;
		}
		break;
#endif /* CONFIG_CPU_MIPS32 */
	case PRID_COMP_SIBYTE:
		switch (mips_cpu.processor_id & 0xff00) {
		case PRID_IMP_SB1:
			mips_cpu.cputype = CPU_SB1;
			mips_cpu.isa_level = MIPS_CPU_ISA_M64;
			mips_cpu.options = MIPS_CPU_TLB | MIPS_CPU_4KEX |
			                   MIPS_CPU_COUNTER | MIPS_CPU_DIVEC |
			                   MIPS_CPU_MCHECK;
#ifndef CONFIG_SB1_PASS_1_WORKAROUNDS
			/* FPU in pass1 is known to have issues. */
			mips_cpu.options |= MIPS_CPU_FPU;
#endif
			break;
		default:
			mips_cpu.cputype = CPU_UNKNOWN;
			break;
		}
		break;
	default:
		mips_cpu.cputype = CPU_UNKNOWN;
	}
	if (mips_cpu.options & MIPS_CPU_FPU)
		mips_cpu.fpu_id = cpu_get_fpu_id();
}
Esempio n. 8
0
int rp_bazaar_app_get_local_list(const char *dir, cJSON **json_root,
                                 ngx_pool_t *pool, int verbose)
{
    static int once = 1;
    if (once) {
    	if(system("bazaar idgen 0"))
            fprintf(stderr, "Problem with idfile generation");
        once = 0;
    }
    DIR *dp;
    struct dirent *ep;

    if((dp = opendir(dir)) == NULL)
        return rp_module_cmd_error(json_root, "Can not open apps directory",
                                   strerror(errno), pool);

    int lcr_meter_found = 0;
    while((ep = readdir (dp))) {
        const char *app_id = ep->d_name;
        cJSON *info = NULL;

        if (!strcmp("lcr_meter", app_id)) {
			lcr_meter_found = 1;
			continue;
		}

        /* check if structure is correct, we need:
         *  <app_id>/info/info.json
         *  <app_id>/info/icon.png
         *  <app_id>/controllerhf.so
         *  <app_id>/fpga.conf
         * And we must be able to load the application and test mandatory
         * functions.
         */

        if (!is_readable(dir, app_id, "info/icon.png"))
            continue;
        if (!is_readable(dir, app_id, "fpga.conf"))
            continue;
        if (!is_controller_ok(dir, app_id, "controllerhf.so"))
            continue;
        if (!get_info(&info, dir, app_id, pool))
            continue;
        if (info == NULL)
            continue;

        /* We have an application */
        if (verbose) {
            /* Attach whole info JSON */
            cJSON_AddItemToObject(info, "type", cJSON_CreateString("run", pool), pool);
            cJSON_AddItemToObject(*json_root, app_id, info, pool);
        } else {
            /* Include version only */
            cJSON *j_ver = cJSON_GetObjectItem(info, "version");

            if(j_ver == NULL) {
                fprintf(stderr, "Cannot get version from info JSON.\n");
                cJSON_Delete(info, pool);
                continue;
            }

            cJSON_AddItemToObject(*json_root, app_id, cJSON_CreateString(j_ver->valuestring, pool), pool);
            cJSON_AddItemToObject(*json_root, "type", cJSON_CreateString("run", pool), pool);
            cJSON_Delete(j_ver, pool);
            cJSON_Delete(info, pool);
        }
        usleep(5);
    }

    closedir(dp);

	// lcr_meter
    if (lcr_meter_found) {
        cJSON *info = NULL;

        if (!is_readable(dir, "lcr_meter", "info/icon.png"))
            return 0;
        if (!is_readable(dir, "lcr_meter", "fpga.conf"))
            return 0;
        if (!is_controller_ok(dir, "lcr_meter", "controllerhf.so"))
            return 0;
        if (!get_info(&info, dir, "lcr_meter", pool))
            return 0;
        if (info == NULL)
            return 0;

        if (verbose) {
            cJSON_AddItemToObject(info, "type", cJSON_CreateString("run", pool), pool);
            cJSON_AddItemToObject(*json_root, "lcr_meter", info, pool);
        } else {
            cJSON *j_ver = cJSON_GetObjectItem(info, "version");
            if(j_ver == NULL) {
                fprintf(stderr, "Cannot get version from info JSON.\n");
                cJSON_Delete(info, pool);
                return 0;
            } else {
				cJSON_AddItemToObject(*json_root, "lcr_meter", cJSON_CreateString(j_ver->valuestring, pool), pool);
				cJSON_AddItemToObject(*json_root, "type", cJSON_CreateString("run", pool), pool);
				cJSON_Delete(j_ver, pool);
				cJSON_Delete(info, pool);
			}
        }
	}

    return 0;
}
Esempio n. 9
0
int main(int argc, char **argv)
{
    int ch = 0;
    char *ifname = NULL, *ip = NULL;;
    int type = 0, broadcast = 0, demon = 0;
    int ret = 0, len = 0;

    while((ch = getopt(argc,argv,"i:gbdh"))!= -1)
    {
        switch(ch) {
        case 'i':
            ifname = optarg;
            break;
        case 'g':
            type = 1;
            break;
        case 'b':
            broadcast = 1;
            break;
        case 'd':
            demon = 1;
            break;
        case 'h':
            usage();
            exit(0);
            break;
        default:
            fprintf (stderr, "invaild option: %c \n", ch);
            exit(0);
            break;
        }
    }
    if(optind < argc) {
        ip = argv[optind];
    }

    if(!ifname) {
        printf("error: no ifname \n");
        exit(0);
    }

    if(!type) {
        if(!ip) {
            printf("error: no ip \n");
            exit(0);
        }

        if(!ip_check(ip)) {
            printf("invaild ip: %s \n", ip);
            exit(0);
        }

        if( inet_aton(ip, (struct in_addr *)&cheat_ip) == 0 ) {
            printf("ip addr error \n");
            exit(0);
        }
    }

    if( get_info(ifname) < 0 ) {
        printf("get info failed \n");
        exit(0);
    }

    len = put_data(broadcast, type);

    if(demon)
        wf_demon(arp_exit_system);
    else
        wf_registe_exit_signal(arp_exit_system);

    if( init_sock(ifname) < 0) {
        printf("socket failed \n");
        exit(0);
    }

    while(1)
    {
        sleep(1);
        ret = send(sockfd, arp_data, len, 0);
        if(!demon)
            printf("ret of send: %d,  %s \n", ret, strerror(errno));
    }

    arp_exit_system();
    return 0;
}
/* Walk all references for an ObjectIndex and construct the hprof CLASS dump. */
static void
dump_class_and_supers(JNIEnv *env, ObjectIndex object_index, RefIndex list)
{
    SiteIndex    site_index;
    SerialNumber trace_serial_num;
    RefIndex     index;
    ClassIndex   super_cnum;
    ObjectIndex  super_index;
    LoaderIndex  loader_index;
    ObjectIndex  signers_index;
    ObjectIndex  domain_index;
    FieldInfo   *fields;
    jvalue      *fvalues;
    jint         n_fields;
    jboolean     skip_fields;
    jint         n_fields_set;
    jlong        size;
    ClassIndex   cnum;
    char        *sig;
    ObjectKind   kind;
    TraceIndex   trace_index;
    Stack       *cpool_values;
    ConstantPoolValue *cpool;
    jint         cpool_count;

    HPROF_ASSERT(object_index!=0);
    kind        = object_get_kind(object_index);
    if ( kind != OBJECT_CLASS ) {
        return;
    }
    site_index         = object_get_site(object_index);
    HPROF_ASSERT(site_index!=0);
    cnum        = site_get_class_index(site_index);
    HPROF_ASSERT(cnum!=0);
    if ( class_get_status(cnum) & CLASS_DUMPED ) {
        return;
    }
    class_add_status(cnum, CLASS_DUMPED);
    size        = (jlong)object_get_size(object_index);

    super_index = 0;
    super_cnum  = class_get_super(cnum);
    if ( super_cnum != 0 ) {
        super_index  = class_get_object_index(super_cnum);
        if ( super_index != 0 ) {
            dump_class_and_supers(env, super_index,
                        object_get_references(super_index));
        }
    }

    trace_index      = site_get_trace_index(site_index);
    HPROF_ASSERT(trace_index!=0);
    trace_serial_num = trace_get_serial_number(trace_index);
    sig              = string_get(class_get_signature(cnum));
    loader_index     = class_get_loader(cnum);
    signers_index    = 0;
    domain_index     = 0;

    /* Get field information */
    n_fields     = 0;
    skip_fields  = JNI_FALSE;
    n_fields_set = 0;
    fields       = NULL;
    fvalues      = NULL;
    if ( class_get_all_fields(env, cnum, &n_fields, &fields) == 1 ) {
        /* Problems getting all the fields, can't trust field index values */
        skip_fields = JNI_TRUE;
        /* Class with no references at all? (ok to be unprepared if list==0?) */
        if ( list != 0 ) {
            /* It is assumed that the reason why we didn't get the fields
             *     was because the class is not prepared.
             */
            if ( gdata->debugflags & DEBUGFLAG_UNPREPARED_CLASSES ) {
                dump_ref_list(list);
                debug_message("Unprepared class with references: %s\n",
                               sig);
            }
            HPROF_ERROR(JNI_FALSE, "Trouble with unprepared classes");
        }
        /* Why would an unprepared class contain references? */
    }
    if ( n_fields > 0 ) {
        fvalues      = (jvalue*)HPROF_MALLOC(n_fields*(int)sizeof(jvalue));
        (void)memset(fvalues, 0, n_fields*(int)sizeof(jvalue));
    }

    /* We use a Stack just because it will automatically expand as needed */
    cpool_values = stack_init(16, 16, sizeof(ConstantPoolValue));
    cpool = NULL;
    cpool_count = 0;

    index      = list;
    while ( index != 0 ) {
        RefInfo    *info;
        jvalue      ovalue;
        static jvalue empty_value;

        info = get_info(index);

        switch ( info->flavor ) {
            case INFO_OBJECT_REF_DATA:
                switch ( info->refKind ) {
                    case JVMTI_HEAP_REFERENCE_FIELD:
                    case JVMTI_HEAP_REFERENCE_ARRAY_ELEMENT:
                        /* Should never be seen on a class dump */
                        HPROF_ASSERT(0);
                        break;
                    case JVMTI_HEAP_REFERENCE_STATIC_FIELD:
                        if ( skip_fields == JNI_TRUE ) {
                            break;
                        }
                        ovalue   = empty_value;
                        ovalue.i = info->object_index;
                        fill_in_field_value(list, fields, fvalues, n_fields,
                                        info->index, ovalue, 0);
                        n_fields_set++;
                        HPROF_ASSERT(n_fields_set <= n_fields);
                        break;
                    case JVMTI_HEAP_REFERENCE_CONSTANT_POOL: {
                        ConstantPoolValue cpv;
                        ObjectIndex       cp_object_index;
                        SiteIndex         cp_site_index;
                        ClassIndex        cp_cnum;

                        cp_object_index = info->object_index;
                        HPROF_ASSERT(cp_object_index!=0);
                        cp_site_index = object_get_site(cp_object_index);
                        HPROF_ASSERT(cp_site_index!=0);
                        cp_cnum = site_get_class_index(cp_site_index);
                        cpv.constant_pool_index = info->index;
                        cpv.sig_index = class_get_signature(cp_cnum);
                        cpv.value.i = cp_object_index;
                        stack_push(cpool_values, (void*)&cpv);
                        cpool_count++;
                        break;
                        }
                    case JVMTI_HEAP_REFERENCE_SIGNERS:
                        signers_index = info->object_index;
                        break;
                    case JVMTI_HEAP_REFERENCE_PROTECTION_DOMAIN:
                        domain_index = info->object_index;
                        break;
                    case JVMTI_HEAP_REFERENCE_CLASS_LOADER:
                    case JVMTI_HEAP_REFERENCE_INTERFACE:
                    default:
                        /* Ignore, not needed */
                        break;
                }
                break;
            case INFO_PRIM_FIELD_DATA:
                if ( skip_fields == JNI_TRUE ) {
                    break;
                }
                HPROF_ASSERT(info->primType!=0);
                HPROF_ASSERT(info->length==-1);
                HPROF_ASSERT(info->refKind==JVMTI_HEAP_REFERENCE_STATIC_FIELD);
                ovalue = get_key_value(index);
                fill_in_field_value(list, fields, fvalues, n_fields,
                                    info->index, ovalue, info->primType);
                n_fields_set++;
                HPROF_ASSERT(n_fields_set <= n_fields);
                break;
            case INFO_PRIM_ARRAY_DATA:
            default:
                /* Should never see these */
                HPROF_ASSERT(0);
                break;
        }

        index = info->next;
    }

    /* Get constant pool data if we have any */
    HPROF_ASSERT(cpool_count==stack_depth(cpool_values));
    if ( cpool_count > 0 ) {
        cpool = (ConstantPoolValue*)stack_element(cpool_values, 0);
    }
    io_heap_class_dump(cnum, sig, object_index, trace_serial_num,
            super_index,
            loader_object_index(env, loader_index),
            signers_index, domain_index,
            (jint)size, cpool_count, cpool, n_fields, fields, fvalues);

    stack_term(cpool_values);
    if ( fvalues != NULL ) {
        HPROF_FREE(fvalues);
    }
}
/* Walk all references for an ObjectIndex and construct the hprof INST dump. */
static void
dump_instance(JNIEnv *env, ObjectIndex object_index, RefIndex list)
{
    jvmtiPrimitiveType primType;
    SiteIndex    site_index;
    SerialNumber trace_serial_num;
    RefIndex     index;
    ObjectIndex  class_index;
    jlong        size;
    ClassIndex   cnum;
    char        *sig;
    void        *elements;
    jint         num_elements;
    jint         num_bytes;
    ObjectIndex *values;
    FieldInfo   *fields;
    jvalue      *fvalues;
    jint         n_fields;
    jboolean     skip_fields;
    jint         n_fields_set;
    ObjectKind   kind;
    TraceIndex   trace_index;
    jboolean     is_array;
    jboolean     is_prim_array;

    HPROF_ASSERT(object_index!=0);
    kind        = object_get_kind(object_index);
    if ( kind == OBJECT_CLASS ) {
        return;
    }
    site_index       = object_get_site(object_index);
    HPROF_ASSERT(site_index!=0);
    cnum             = site_get_class_index(site_index);
    HPROF_ASSERT(cnum!=0);
    size             = (jlong)object_get_size(object_index);
    trace_index      = site_get_trace_index(site_index);
    HPROF_ASSERT(trace_index!=0);
    trace_serial_num = trace_get_serial_number(trace_index);
    sig              = string_get(class_get_signature(cnum));
    class_index      = class_get_object_index(cnum);

    values       = NULL;
    elements     = NULL;
    num_elements = 0;
    num_bytes    = 0;

    n_fields     = 0;
    skip_fields  = JNI_FALSE;
    n_fields_set = 0;
    fields       = NULL;
    fvalues      = NULL;

    index      = list;

    is_array      = JNI_FALSE;
    is_prim_array = JNI_FALSE;

    if ( sig[0] != JVM_SIGNATURE_ARRAY ) {
        if ( class_get_all_fields(env, cnum, &n_fields, &fields) == 1 ) {
            /* Trouble getting all the fields, can't trust field index values */
            skip_fields = JNI_TRUE;
            /* It is assumed that the reason why we didn't get the fields
             *     was because the class is not prepared.
             */
            if ( gdata->debugflags & DEBUGFLAG_UNPREPARED_CLASSES ) {
                if ( list != 0 ) {
                    dump_ref_list(list);
                    debug_message("Instance of unprepared class with refs: %s\n",
                                   sig);
                } else {
                    debug_message("Instance of unprepared class without refs: %s\n",
                                   sig);
                }
                HPROF_ERROR(JNI_FALSE, "Big Trouble with unprepared class instances");
            }
        }
        if ( n_fields > 0 ) {
            fvalues = (jvalue*)HPROF_MALLOC(n_fields*(int)sizeof(jvalue));
            (void)memset(fvalues, 0, n_fields*(int)sizeof(jvalue));
        }
    } else {
        is_array = JNI_TRUE;
        if ( sig[0] != 0 && sigToPrimSize(sig+1) != 0 ) {
            is_prim_array = JNI_TRUE;
        }
    }

    while ( index != 0 ) {
        RefInfo *info;
        jvalue   ovalue;
        static jvalue empty_value;

        info = get_info(index);

        /* Process reference objects, many not used right now. */
        switch ( info->flavor ) {
            case INFO_OBJECT_REF_DATA:
                switch ( info->refKind ) {
                    case JVMTI_HEAP_REFERENCE_SIGNERS:
                    case JVMTI_HEAP_REFERENCE_PROTECTION_DOMAIN:
                    case JVMTI_HEAP_REFERENCE_CLASS_LOADER:
                    case JVMTI_HEAP_REFERENCE_INTERFACE:
                    case JVMTI_HEAP_REFERENCE_STATIC_FIELD:
                    case JVMTI_HEAP_REFERENCE_CONSTANT_POOL:
                        /* Should never be seen on an instance dump */
                        HPROF_ASSERT(0);
                        break;
                    case JVMTI_HEAP_REFERENCE_FIELD:
                        if ( skip_fields == JNI_TRUE ) {
                            break;
                        }
                        HPROF_ASSERT(is_array!=JNI_TRUE);
                        ovalue   = empty_value;
                        ovalue.i = info->object_index;
                        fill_in_field_value(list, fields, fvalues, n_fields,
                                        info->index, ovalue, 0);
                        n_fields_set++;
                        HPROF_ASSERT(n_fields_set <= n_fields);
                        break;
                    case JVMTI_HEAP_REFERENCE_ARRAY_ELEMENT:
                        /* We get each object element one at a time.  */
                        HPROF_ASSERT(is_array==JNI_TRUE);
                        HPROF_ASSERT(is_prim_array!=JNI_TRUE);
                        if ( num_elements <= info->index ) {
                            int nbytes;

                            if ( values == NULL ) {
                                num_elements = info->index + 1;
                                nbytes = num_elements*(int)sizeof(ObjectIndex);
                                values = (ObjectIndex*)HPROF_MALLOC(nbytes);
                                (void)memset(values, 0, nbytes);
                            } else {
                                void *new_values;
                                int   new_size;
                                int   obytes;

                                obytes = num_elements*(int)sizeof(ObjectIndex);
                                new_size = info->index + 1;
                                nbytes = new_size*(int)sizeof(ObjectIndex);
                                new_values = (void*)HPROF_MALLOC(nbytes);
                                (void)memcpy(new_values, values, obytes);
                                (void)memset(((char*)new_values)+obytes, 0,
                                                        nbytes-obytes);
                                HPROF_FREE(values);
                                num_elements = new_size;
                                values =  new_values;
                            }
                        }
                        HPROF_ASSERT(values[info->index]==0);
                        values[info->index] = info->object_index;
                        break;
                    default:
                        /* Ignore, not needed */
                        break;
                }
                break;
            case INFO_PRIM_FIELD_DATA:
                if ( skip_fields == JNI_TRUE ) {
                    break;
                }
                HPROF_ASSERT(info->primType!=0);
                HPROF_ASSERT(info->length==-1);
                HPROF_ASSERT(info->refKind==JVMTI_HEAP_REFERENCE_FIELD);
                HPROF_ASSERT(is_array!=JNI_TRUE);
                ovalue = get_key_value(index);
                fill_in_field_value(list, fields, fvalues, n_fields,
                                    info->index, ovalue, info->primType);
                n_fields_set++;
                HPROF_ASSERT(n_fields_set <= n_fields);
                break;
            case INFO_PRIM_ARRAY_DATA:
                /* Should only be one, and it's handled below */
                HPROF_ASSERT(info->refKind==0);
                /* We assert that nothing else was saved with this array */
                HPROF_ASSERT(index==list&&info->next==0);
                HPROF_ASSERT(is_array==JNI_TRUE);
                HPROF_ASSERT(is_prim_array==JNI_TRUE);
                primType = info->primType;
                elements = get_key_elements(index, primType,
                                            &num_elements, &num_bytes);
                HPROF_ASSERT(info->length==num_elements);
                size = num_bytes;
                break;
            default:
                HPROF_ASSERT(0);
                break;
        }
        index = info->next;
    }

    if ( is_array == JNI_TRUE ) {
        if ( is_prim_array == JNI_TRUE ) {
            HPROF_ASSERT(values==NULL);
            io_heap_prim_array(object_index, trace_serial_num,
                    (jint)size, num_elements, sig, elements);
        } else {
            HPROF_ASSERT(elements==NULL);
            io_heap_object_array(object_index, trace_serial_num,
                    (jint)size, num_elements, sig, values, class_index);
        }
    } else {
        io_heap_instance_dump(cnum, object_index, trace_serial_num,
                    class_index, (jint)size, sig, fields, fvalues, n_fields);
    }
    if ( values != NULL ) {
        HPROF_FREE(values);
    }
    if ( fvalues != NULL ) {
        HPROF_FREE(fvalues);
    }
    if ( elements != NULL ) {
        /* Do NOT free elements, it's a key in the table, leave it be */
    }
}
Esempio n. 12
0
int
PX4IO_Uploader::upload(const char *filenames[])
{
	int	ret;
	const char *filename = NULL;
	size_t fw_size;

#ifndef PX4IO_SERIAL_DEVICE
#error Must define PX4IO_SERIAL_DEVICE in board configuration to support firmware upload
#endif

	/* allow an early abort and look for file first */
	for (unsigned i = 0; filenames[i] != nullptr; i++) {
		_fw_fd = open(filenames[i], O_RDONLY);

		if (_fw_fd < 0) {
			log("failed to open %s", filenames[i]);
			continue;
		}

		log("using firmware from %s", filenames[i]);
		filename = filenames[i];
		break;
	}

	if (filename == NULL) {
		log("no firmware found");
		close(_io_fd);
		_io_fd = -1;
		return -ENOENT;
	}

	_io_fd = open(PX4IO_SERIAL_DEVICE, O_RDWR);

	if (_io_fd < 0) {
		log("could not open interface");
		return -errno;
	}

	/* save initial uart configuration to reset after the update */
	struct termios t_original;
	tcgetattr(_io_fd, &t_original);

	/* adjust line speed to match bootloader */
	struct termios t;
	tcgetattr(_io_fd, &t);
	cfsetspeed(&t, 115200);
	tcsetattr(_io_fd, TCSANOW, &t);

	/* look for the bootloader for 150 ms */
	for (int i = 0; i < 15; i++) {
		ret = sync();
		if (ret == OK) {
			break;
		} else {
			usleep(10000);
		}
	}

	if (ret != OK) {
		/* this is immediately fatal */
		log("bootloader not responding");
		tcsetattr(_io_fd, TCSANOW, &t_original);
		close(_io_fd);
		_io_fd = -1;
		return -EIO;
	}

	struct stat st;
	if (stat(filename, &st) != 0) {
		log("Failed to stat %s - %d\n", filename, (int)errno);
		tcsetattr(_io_fd, TCSANOW, &t_original);
		close(_io_fd);
		_io_fd = -1;
		return -errno;
	}
	fw_size = st.st_size;

	if (_fw_fd == -1) {
		tcsetattr(_io_fd, TCSANOW, &t_original);
		close(_io_fd);
		_io_fd = -1;
		return -ENOENT;
	}

	/* do the usual program thing - allow for failure */
	for (unsigned retries = 0; retries < 1; retries++) {
		if (retries > 0) {
			log("retrying update...");
			ret = sync();

			if (ret != OK) {
				/* this is immediately fatal */
				log("bootloader not responding");
				tcsetattr(_io_fd, TCSANOW, &t_original);
				close(_io_fd);
				_io_fd = -1;
				return -EIO;
			}
		}

		ret = get_info(INFO_BL_REV, bl_rev);

		if (ret == OK) {
			if (bl_rev <= BL_REV) {
				log("found bootloader revision: %d", bl_rev);
			} else {
				log("found unsupported bootloader revision %d, exiting", bl_rev);
				tcsetattr(_io_fd, TCSANOW, &t_original);
				close(_io_fd);
				_io_fd = -1;
				return OK;
			}
		}

		ret = erase();

		if (ret != OK) {
			log("erase failed");
			continue;
		}

		ret = program(fw_size);

		if (ret != OK) {
			log("program failed");
			continue;
		}

		if (bl_rev <= 2) {
			ret = verify_rev2(fw_size);
		} else if(bl_rev == 3) {
			ret = verify_rev3(fw_size);
		} else {
			/* verify rev 4 and higher still uses the same approach and
			 * every version *needs* to be verified.
			 */
			ret = verify_rev3(fw_size);
		}

		if (ret != OK) {
			log("verify failed");
			continue;
		}

		ret = reboot();

		if (ret != OK) {
			log("reboot failed");
			tcsetattr(_io_fd, TCSANOW, &t_original);
			close(_io_fd);
			_io_fd = -1;
			return ret;
		}

		log("update complete");

		ret = OK;
		break;
	}

	/* reset uart to previous/default baudrate */
	tcsetattr(_io_fd, TCSANOW, &t_original);

	close(_fw_fd);
	close(_io_fd);
	_io_fd = -1;

        // sleep for enough time for the IO chip to boot. This makes
        // forceupdate more reliably startup IO again after update
        up_udelay(100*1000);

	return ret;
}
Esempio n. 13
0
int
PX4IO_Uploader::verify_rev3(size_t fw_size_local)
{
	int ret;
	uint8_t	file_buf[4];
	ssize_t count;
	uint32_t sum = 0;
	uint32_t bytes_read = 0;
	uint32_t crc = 0;
	uint32_t fw_size_remote;
	uint8_t fill_blank = 0xff;

	log("verify...");
	lseek(_fw_fd, 0, SEEK_SET);

	ret = get_info(INFO_FLASH_SIZE, fw_size_remote);
	send(PROTO_EOC);

	if (ret != OK) {
		log("could not read firmware size");
		return ret;
	}

	/* read through the firmware file again and calculate the checksum*/
	while (bytes_read < fw_size_local) {
		size_t n = fw_size_local - bytes_read;
		if (n > sizeof(file_buf)) {
			n = sizeof(file_buf);
		}
		count = read_with_retry(_fw_fd, file_buf, n);

		if (count != (ssize_t)n) {
			log("firmware read of %u bytes at %u failed -> %d errno %d", 
			    (unsigned)n,
			    (unsigned)bytes_read,
			    (int)count,
			    (int)errno);
		}

		/* set the rest to ff */
		if (count == 0) {
			break;
		}
		/* stop if the file cannot be read */
		if (count < 0)
			return -errno;

		/* calculate crc32 sum */
		sum = crc32part((uint8_t *)&file_buf, sizeof(file_buf), sum);

		bytes_read += count;
	}

	/* fill the rest with 0xff */
	while (bytes_read < fw_size_remote) {
		sum = crc32part(&fill_blank, sizeof(fill_blank), sum);
		bytes_read += sizeof(fill_blank);
	}

	/* request CRC from IO */
	send(PROTO_GET_CRC);
	send(PROTO_EOC);

	ret = recv((uint8_t*)(&crc), sizeof(crc));

	if (ret != OK) {
		log("did not receive CRC checksum");
		return ret;
	}

	/* compare the CRC sum from the IO with the one calculated */
	if (sum != crc) {
		log("CRC wrong: received: %d, expected: %d", crc, sum);
		return -EINVAL;
	}

	return OK;
}
Esempio n. 14
0
static VALUE dictinfo_size_str(VALUE self) {
    return rb_str_new2(get_info(self)->size_str);
}
Esempio n. 15
0
static ret_t
load_common (cherokee_plugin_loader_t *loader,
	     const char               *modname,
	     int                       flags)
{
	ret_t                   ret;
	entry_t                *entry     = NULL;
	cherokee_plugin_info_t *info      = NULL;
	void                   *dl_handle = NULL;

	/* If it is already loaded just return
	 */
	ret = cherokee_avl_get_ptr (&loader->table, modname, (void **)&entry);
	if (ret == ret_ok)
		return ret_ok;

	/* Check deps
	 */
	ret = check_deps_file (loader, modname);
	if (ret != ret_ok)
		return ret;

	/* Get the module info
	 */
	ret = get_info (loader, modname, flags, &info, &dl_handle);
	switch (ret) {
	case ret_ok:
		break;
	case ret_error:
		LOG_ERROR (CHEROKEE_ERROR_PLUGIN_NO_OPEN, modname);
		return ret;
	case ret_not_found:
		LOG_ERROR (CHEROKEE_ERROR_PLUGIN_NO_INFO, modname);
		return ret;
	default:
		SHOULDNT_HAPPEN;
		return ret_error;
	}

	/* Add new entry
	 */
	entry = malloc (sizeof(entry_t));
	entry->dlopen_ref = dl_handle;
	entry->info       = info;
	entry->built_in   = false;

	ret = cherokee_avl_add_ptr (&loader->table, modname, entry);
	if (unlikely(ret != ret_ok)) {
		dlclose (entry->dlopen_ref);
		free(entry);
		return ret;
	}

	/* Execute init function
	 */
	ret = execute_init_func (loader, modname, entry);
	if (ret != ret_ok) {
		return ret;
	}

	return ret_ok;
}
Esempio n. 16
0
void protect_goal::on_create()
{
	goal::on_create();
	if (cfg_.has_attribute("value")) {
		try {
			value_ = boost::lexical_cast<double>(cfg_["value"]);
		} catch (boost::bad_lexical_cast){
			ERR_AI_GOAL << "bad value of protect_goal"<<std::endl;
			value_ = 0;
		}
	}
	if (cfg_.has_attribute("protect_radius")) {
		try {
			radius_ = boost::lexical_cast<int>(cfg_["protect_radius"]);
		} catch (boost::bad_lexical_cast){
			ERR_AI_GOAL << "bad protection radius of protect_goal"<<std::endl;
			radius_ = 1;
		}
	}

	if (radius_<1) {
		radius_=20;
	}
	const config &criteria = cfg_.child("criteria");
	if (criteria) {
		filter_ptr_ = boost::shared_ptr<terrain_filter>(new terrain_filter(vconfig(criteria),get_info().units));
	}


}
Esempio n. 17
0
void node_sampler::do_update (const node0* caller, int caller_port_type, int caller_port)
{
    audio_buffer* out = get_output<audio_buffer> (node0::LINK_AUDIO, OUT_A_OUTPUT);
    const sample_buffer* trig = get_input<sample_buffer> (node0::LINK_CONTROL, IN_C_TRIGGER);
    const sample* trig_buf = trig ? (const sample*) &const_range(*trig)[0] : 0;
    link_envelope trig_env =  get_in_envelope (LINK_CONTROL, IN_C_TRIGGER);

    /* Read the data. */
    size_t start = 0;
    size_t end = get_info ().block_size;

    if (m_reader)
    {
	while (start < get_info ().block_size) {
	    if (m_restart) {
		if (trig_buf && trig_buf[start] != 0.0f) {
		    restart();
		    m_restart = false;
		}
	    }

	    if (trig)
		end = synth::find_hill (const_range (*trig), start);

	    read(*out, start, end);

	    float env_val = (float) (audio_sample) trig_env.update (end - start);
	    if (env_val == 1.0f && trig_buf && trig_buf[end - 1] == 0.0f)
		m_restart = true;

	    start = end;
	}
    } else
	fill_frames (range (*out), audio_frame (0));

    /* Set amplitude. */
    transform_frames (
        range (*out), range (*out),
        [&] (audio_frame in) -> audio_frame {
            static_transform (in, in, [&] (audio_sample in) -> audio_sample {
                    return in * this->m_param_ampl;
                });
            return in;
        });

    /* Apply trigger envelope. */
    if (trig_buf) {
	for (size_t i = 0; i < get_info ().num_channels; ++i) {
	    sample* buf = (sample*) &range (*out)[0][i];
	    int n_samp = get_info ().block_size;
	    trig_buf = (const sample*) &const_range (*trig)[0];
	    trig_env = get_in_envelope (LINK_CONTROL, IN_C_TRIGGER);

	    while (n_samp--) {
		float env_val = (float) (audio_sample) trig_env.update();
		*buf = *buf * ((1.0f - env_val) + (env_val * *trig_buf));
		++buf;
		++trig_buf;
	    }
	}
    }

}
Esempio n. 18
0
void protect_goal::add_targets(std::back_insert_iterator< std::vector< target > > target_list)
{
	std::string goal_type;
	if (protect_unit_) {
		if (protect_only_own_unit_) {
			goal_type = "protect_my_unit";
		} else {
			goal_type = "protect_unit";
		}
	} else {
		goal_type ="protect_location";
	}

	if (!(this)->active()) {
		LOG_AI_GOAL << "skipping " << goal_type << " goal - not active" << std::endl;
		return;
	}

	const config &criteria = cfg_.child("criteria");
	if (!criteria) {
		LOG_AI_GOAL << "skipping " << goal_type << " goal - no criteria given" << std::endl;
		return;
	} else {
		DBG_AI_GOAL << goal_type << " goal with criteria" << std::endl << cfg_.child("criteria") << std::endl;
	}


	unit_map &units = get_info().units;
	std::vector<team> &teams = get_info().teams;


	std::set<map_location> items;
	if (protect_unit_) {
		for(unit_map::const_iterator u = units.begin(); u != units.end(); ++u) {

			if (protect_only_own_unit_ && u->second.side()!=get_side()) {
				continue;
			}
			//TODO: we will protect hidden units, by not testing for invisibility to current side
			if (u->second.matches_filter(vconfig(criteria),u->first)) {
				DBG_AI_GOAL << "in "<<goal_type<< ": " << u->first << " should be protected " << std::endl;
				items.insert(u->first);
			}
		}
	} else {
		filter_ptr_->get_locations(items);
	}
	DBG_AI_GOAL << "seaching for threats in "+goal_type+" goal" << std::endl;
	// Look for directions to protect a specific location or specific unit.
	foreach (const map_location &loc, items)
	{
		for(unit_map::const_iterator u = units.begin(); u != units.end(); ++u) {
			const int distance = distance_between(u->first,loc);
			if(current_team().is_enemy(u->second.side()) && distance < radius_
			&& !u->second.invisible(u->first, units, teams)) {
				DBG_AI_GOAL << "in "<<goal_type<<": found threat target. " << u->first << " is a threat to "<< loc << std::endl;
				*target_list = target(u->first, value_ * double(radius_-distance) /
							double(radius_),target::THREAT);
			}
		}
	}


}
Esempio n. 19
0
/*
  upload a firmware to the IOMCU
 */
bool AP_IOMCU::upload_fw(void)
{
    // set baudrate for bootloader
    uart.begin(115200, 256, 256);

    bool ret = false;

    /* look for the bootloader for 150 ms */
    for (uint8_t i = 0; i < 15; i++) {
        ret = sync();
        if (ret) {
            break;
        }
        hal.scheduler->delay(10);
    }

    if (!ret) {
        debug("IO update failed sync");
        return false;
    }

    uint32_t bl_rev;
    ret = get_info(INFO_BL_REV, bl_rev);

    if (!ret) {
        debug("Err: failed to contact bootloader");
        return false;
    }
    if (bl_rev > BL_REV) {
        debug("Err: unsupported bootloader revision %u", unsigned(bl_rev));
        return false;
    }
    debug("found bootloader revision: %u", unsigned(bl_rev));

    ret = erase();
    if (!ret) {
        debug("erase failed");
        return false;
    }

    ret = program(fw_size);
    if (!ret) {
        debug("program failed");
        return false;
    }

    if (bl_rev <= 2) {
        ret = verify_rev2(fw_size);
    } else {
        ret = verify_rev3(fw_size);
    }

    if (!ret) {
        debug("verify failed");
        return false;
    }

    ret = reboot();

    if (!ret) {
        debug("reboot failed");
        return false;
    }

    debug("update complete");

    // sleep for enough time for the IO chip to boot
    hal.scheduler->delay(100);

    return true;
}
void xmpp_iq_sponsor_info_updated_cb(const char *msg_id,
                                     const char *msg,
                                     void *args)
{
    /* Answer:
       <iq from='masterserver@warface/xxx' type='get'>
        <query xmlns='urn:cryonline:k01'>
         <sponsor_info_updated sponsor_id='0' sponsor_points='864'
             total_sponsor_points='2064' next_unlock_item='smg07_shop'>
          <unlocked_items>
           <item name='xxx' .../>
          </unlocked_items>
         </sponsor_info_updated>
        </query>
       </iq>
    */

    char *data = wf_get_query_content(msg);

    if (data == NULL)
        return;

    unsigned sponsor_id = get_info_int(data, "sponsor_id='", "'", NULL);
    unsigned points = get_info_int(data, "sponsor_points='", "'", NULL);
    unsigned total = get_info_int(data, "total_sponsor_points='", "'", NULL);
    char *next_item = get_info(data, "next_unlock_item='", "'", NULL);
    char *unlocked_items =
        get_info(data, "<unlocked_items>", "</unlocked_items>", NULL);

    if (unlocked_items != NULL)
    {
        const char *m = unlocked_items;
        while ((m = strstr(m, "<item")) != NULL)
        {
            char *item = get_info(m, "<item", "/>", NULL);
            char *item_name = get_info(item, "name='", "'", NULL);

            xprintf("%s: %s",
                    LANG(notif_unlock_item),
                    item_name);

            free(item_name);
            free(item);
            ++m;
        }
    }

    const char *sponsor = NULL;
    switch (sponsor_id)
    {
        case 0:
            sponsor = LANG(console_sponsor_weapon);
            break;
        case 1:
            sponsor = LANG(console_sponsor_outfit);
            break;
        case 2:
            sponsor = LANG(console_sponsor_equipment);
            break;
        default:
            break;
    }

    if (sponsor != NULL && sponsor[0])
    {
        xprintf("%s: %u (+%u) - %s %s",
                sponsor,
                total,
                points,
                LANG(notif_unlocking),
                next_item);
    }
    else
    {
        xprintf("%s: %u (+%u) - %s",
                sponsor,
                total,
                points,
                LANG(notif_unlocking_done));
    }

    free(unlocked_items);
    free(next_item);
    free(data);
}
Esempio n. 21
0
void
site_write(JNIEnv *env, int flags, double cutoff)
{
    HPROF_ASSERT(gdata->site_table!=NULL);
    LOG3("site_write", "flags", flags);

    if (flags & SITE_FORCE_GC) {
        runGC();
    }

    HPROF_ASSERT(gdata->total_live_bytes!=0);

    rawMonitorEnter(gdata->data_access_lock); {

        IterateInfo     iterate;
        int             site_table_size;
        double          accum_percent;
        void *          comment_str;
        int             i;
        int             cutoff_count;
        int             nbytes;

        accum_percent = 0;
        site_table_size = table_element_count(gdata->site_table);

        (void)memset(&iterate, 0, sizeof(iterate));
        nbytes            = site_table_size * (int)sizeof(SiteIndex);
        if ( nbytes > 0 ) {
            iterate.site_nums = HPROF_MALLOC(nbytes);
            (void)memset(iterate.site_nums, 0, nbytes);
        }
        iterate.count   = 0;
        iterate.changed_only = flags & SITE_DUMP_INCREMENTAL;
        table_walk_items(gdata->site_table, &collect_iterator, &iterate);

        site_table_size = iterate.count;

        if (flags & SITE_SORT_BY_ALLOC) {
            comment_str = "allocated bytes";
            qsort(iterate.site_nums, site_table_size, sizeof(SiteIndex),
                    &qsort_compare_allocated_bytes);
        } else {
            comment_str = "live bytes";
            qsort(iterate.site_nums, site_table_size, sizeof(SiteIndex),
                    &qsort_compare_live_bytes);
        }

        trace_output_unmarked(env);

        cutoff_count = 0;
        for (i = 0; i < site_table_size; i++) {
            SiteInfo   *info;
            SiteIndex   index;
            double      ratio;

            index= iterate.site_nums[i];
            HPROF_ASSERT(index!=0);
            info        = get_info(index);
            ratio       = (double)info->n_live_bytes / (double)gdata->total_live_bytes;
            if (ratio < cutoff) {
                break;
            }
            cutoff_count++;
        }

        io_write_sites_header(  comment_str,
                                flags,
                                cutoff,
                                gdata->total_live_bytes,
                                gdata->total_live_instances,
                                gdata->total_alloced_bytes,
                                gdata->total_alloced_instances,
                                cutoff_count);

        for (i = 0; i < cutoff_count; i++) {
            SiteInfo     *info;
            SiteKey      *pkey;
            SiteIndex     index;
            char         *class_signature;
            double        ratio;

            index = iterate.site_nums[i];
            pkey         = get_pkey(index);
            info         = get_info(index);

            ratio       = (double)info->n_live_bytes / (double)gdata->total_live_bytes;
            accum_percent += ratio;

            class_signature  = string_get(class_get_signature(pkey->cnum));

            io_write_sites_elem(i + 1,
                                ratio,
                                accum_percent,
                                class_signature,
                                class_get_serial_number(pkey->cnum),
                                trace_get_serial_number(pkey->trace_index),
                                info->n_live_bytes,
                                info->n_live_instances,
                                info->n_alloced_bytes,
                                info->n_alloced_instances);
        }

        io_write_sites_footer();

        table_walk_items(gdata->site_table, &mark_unchanged_iterator, NULL);

        if ( iterate.site_nums != NULL ) {
            HPROF_FREE(iterate.site_nums);
        }

    } rawMonitorExit(gdata->data_access_lock);
}
Esempio n. 22
0
readonly_context_impl::readonly_context_impl(side_context &context, const config &cfg)
		: cfg_(cfg),
		engines_(),
		known_aspects_(),
		aggression_(),
		attack_depth_(),
		aspects_(),
		attacks_(),
		avoid_(),
		caution_(),
		defensive_position_cache_(),
		dstsrc_(),enemy_dstsrc_(),
		enemy_possible_moves_(),
		enemy_srcdst_(),
		grouping_(),
		goals_(),
		keeps_(),
		leader_aggression_(),
		leader_goal_(),
		leader_value_(),
		move_maps_enemy_valid_(false),
		move_maps_valid_(false),
		number_of_possible_recruits_to_force_recruit_(),
		passive_leader_(),
		passive_leader_shares_keep_(),
		possible_moves_(),
		recruitment_(),
		recruitment_ignore_bad_combat_(),
		recruitment_ignore_bad_movement_(),
		recruitment_pattern_(),
		recursion_counter_(context.get_recursion_count()),
		scout_village_targeting_(),
		simple_targeting_(),
		srcdst_(),
		support_villages_(),
		unit_stats_cache_(),
		village_value_(),
		villages_per_scout_()
	{
		init_side_context_proxy(context);
		manager::add_gamestate_observer(this);

		add_known_aspect("aggression",aggression_);
		add_known_aspect("attack_depth",attack_depth_);
		add_known_aspect("attacks",attacks_);
		add_known_aspect("avoid",avoid_);
		add_known_aspect("caution",caution_);
		add_known_aspect("grouping",grouping_);
		add_known_aspect("leader_aggression",leader_aggression_);
		add_known_aspect("leader_goal",leader_goal_);
		add_known_aspect("leader_value",leader_value_);
		add_known_aspect("number_of_possible_recruits_to_force_recruit",number_of_possible_recruits_to_force_recruit_);
		add_known_aspect("passive_leader",passive_leader_);
		add_known_aspect("passive_leader_shares_keep",passive_leader_shares_keep_);
		add_known_aspect("recruitment",recruitment_);
		add_known_aspect("recruitment_ignore_bad_combat",recruitment_ignore_bad_combat_);
		add_known_aspect("recruitment_ignore_bad_movement",recruitment_ignore_bad_movement_);
		add_known_aspect("recruitment_pattern",recruitment_pattern_);
		add_known_aspect("scout_village_targeting",scout_village_targeting_);
		add_known_aspect("simple_targeting",simple_targeting_);
		add_known_aspect("support_villages",support_villages_);
		add_known_aspect("village_value",village_value_);
		add_known_aspect("villages_per_scout",villages_per_scout_);
		keeps_.init(get_info().map);

	}
Esempio n. 23
0
String Thread::to_string() const {
    return String() << "Thread: " << get_info();
}
Esempio n. 24
0
void UIloadinterface()
{
  Display	*dpy;
  Widget	MainWindow, InfoWindow, CommandWindow,
		InfoButton, CommandButton, PlayButton,
		StopButton, BStepButton, FStepButton,
		LoadButton, ScriptButton, CloseButton,
		AnimateTitle, InfoTitle, InfoText, InfoClose;
  XFontStruct  *font;
  XmFontList    fontlist;
  Arg		args[10];
  int		n, oldstderr;
  int		argcblah = 1;
  char 	       *argvblah[1] = { "Animate" };
  FILE         *dummy;

  mib_Widget   *MainForm, *InfoForm, *CommandForm;
  String	fallbacks[] = {

#ifdef dark_ui
	"*Foreground:			gray20",
	"*Background:			gray70",
#endif
#ifdef light_ui
	"*Foreground:			#000000000000",
	"*Background:			#afafafafafaf",
#endif
	"*BorderWidth:			0",
	"*XmToggleButton.selectColor:    yellow",
	"*XmToggleButton.indicatorSize:    16",
	"*XmToggleButtonGadget.selectColor:    yellow",
	"*XmToggleButtonGadget.indicatorSize:    16",
	"*XmTextField.background:	        #cc7777",
	"*fontList:\
	-adobe-helvetica-medium-r-normal--14-100-100-100-p-76-iso8859-1",
	NULL};


  /* initialize application top level widget */

  TopLevel = XtVaAppInitialize(&App, "animate", NULL, 0,
	&argcblah, argvblah, fallbacks, NULL);

  dpy = XtDisplay(TopLevel);

  oldstderr = dup(fileno(stderr));
  dummy = freopen("/dev/null", "w", stderr);

  /* configure resize policy of window */

  XtVaSetValues(TopLevel, XmNminWidth, 272, XmNminHeight, 319,
			XmNkeyboardFocusPolicy, XmPOINTER, NULL);

  /* create the application windows */

  MainWindow = XtCreateManagedWidget("MainWindow",
	xmMainWindowWidgetClass, TopLevel, NULL, 0);

/*****************************************************************************/

  n = 0;
  XtSetArg(args[n], XmNminWidth, 359); n++;
  XtSetArg(args[n], XmNminHeight, 197); n++;
  XtSetArg(args[n], XmNtitle, "Info"); n++;

  InfoWindow = XmCreateFormDialog(MainWindow, "Info", args, n);

/*****************************************************************************/

  n = 0;
  XtSetArg(args[n], XmNminWidth, 365); n++;
  XtSetArg(args[n], XmNminHeight, 64); n++;
  XtSetArg(args[n], XmNmaxHeight, 64); n++;
  XtSetArg(args[n], XmNtitle, "Command"); n++;
  XtSetArg(args[n], XmNkeyboardFocusPolicy, XmPOINTER); n++;

  CommandWindow = XmCreateFormDialog(MainWindow, "Command", args, n);

/*****************************************************************************/

  /* load the interface via the mib library */

/*
  MainForm = mib_load_interface(MainWindow,
	"interface/animate.mib", MI_FROMFILE);
  InfoForm = mib_load_interface(InfoWindow,
	"interface/info.mib", MI_FROMFILE);
  CommandForm = mib_load_interface(CommandWindow,
	"interface/command.mib", MI_FROMFILE);
*/
  MainForm = mib_load_interface(MainWindow, AnimRoot, MI_FROMSTRING);
  InfoForm = mib_load_interface(InfoWindow, InfoRoot, MI_FROMSTRING);
  CommandForm = mib_load_interface(CommandWindow, CommRoot, MI_FROMSTRING);


  /* Get widget pointers from interface */

  AnimateTitle = mib_find_name(MainForm, "AnimateTitle")->me;
  CloseButton = mib_find_name(MainForm, "CloseButton")->me;
  InfoButton = mib_find_name(MainForm, "InfoButton")->me;
  CommandButton = mib_find_name(MainForm, "CommandButton")->me;
  ScriptButton = mib_find_name(MainForm, "Script")->me;
  LoadButton = mib_find_name(MainForm, "Load")->me;
  PlayButton = mib_find_name(MainForm, "Play")->me;
  StopButton = mib_find_name(MainForm, "Stop")->me;
  BStepButton = mib_find_name(MainForm, "BStep")->me;
  FStepButton = mib_find_name(MainForm, "FStep")->me;
  SpeedScale = mib_find_name(MainForm, "SpeedScale")->me;
  FileText = mib_find_name(MainForm, "FileText")->me;
  AnimList = mib_find_name(MainForm, "AnimList")->me;
  RangeToggle = mib_find_name(MainForm, "Range")->me;
  OnceToggle = mib_find_name(MainForm, "Once")->me;
  BounceToggle = mib_find_name(MainForm, "Bounce")->me;

  InfoTitle = mib_find_name(InfoForm, "Title")->me;
  InfoText = mib_find_name(InfoForm, "TextBig")->me;
  InfoClose = mib_find_name(InfoForm, "Close")->me;

  CommandText = mib_find_name(CommandForm, "TextBox")->me;

  /* Set large font for titles */

  font = XLoadQueryFont(dpy,
        "-adobe-helvetica-bold-r-normal--24-240-75-75-p-138-iso8859-1");
  fontlist = XmFontListCreate(font, "bigger");
  XtVaSetValues(AnimateTitle, XmNfontList, fontlist, NULL);
  XtVaSetValues(InfoTitle, XmNfontList, fontlist, NULL);

  /* Set various resources and values */

  XtVaSetValues(InfoText, XmNcursorPositionVisible, False,
                           XmNeditable, False, NULL);
  XmTextSetString(InfoText, get_info());

  XtVaSetValues(AnimList, XmNselectionPolicy, XmEXTENDED_SELECT, NULL);

  XmScaleSetValue(SpeedScale, 100);

  /* Set callbacks - stupid @#$@&%!@# boiler plate code */

  XtAddCallback(CloseButton,
		XmNactivateCallback,
		(XtCallbackProc)close_callback,
		(XtPointer)NULL
		);

  XtAddCallback(InfoButton,
		XmNactivateCallback,
		(XtCallbackProc)info_callback,
		(XtPointer)InfoWindow
		);

  XtAddCallback(InfoClose,
		XmNactivateCallback,
		(XtCallbackProc)cinfo_callback,
		(XtPointer)InfoWindow
		);

  XtAddCallback(BStepButton,
		XmNactivateCallback,
		(XtCallbackProc)bstep_callback,
		(XtPointer)NULL
		);

  XtAddCallback(FStepButton,
		XmNactivateCallback,
		(XtCallbackProc)fstep_callback,
		(XtPointer)NULL
		);

  XtAddCallback(PlayButton,
		XmNactivateCallback,
		(XtCallbackProc)play_callback,
		(XtPointer)NULL
		);

  XtAddCallback(StopButton,
		XmNactivateCallback,
		(XtCallbackProc)stop_callback,
		(XtPointer)NULL
		);

  XtAddCallback(LoadButton,
		XmNactivateCallback,
		(XtCallbackProc)load_callback,
		(XtPointer)FileText
		);


  XtAddCallback(FileText,
		XmNactivateCallback,
		(XtCallbackProc)load_callback,
		(XtPointer)FileText
		);

  XtAddCallback(ScriptButton,
		XmNactivateCallback,
		(XtCallbackProc)script_callback,
		(XtPointer)FileText
		);

  XtAddCallback(CommandButton,
		XmNactivateCallback,
		(XtCallbackProc)command_callback,
		(XtPointer)CommandWindow
		);

  XtAddCallback(AnimList,
		XmNdefaultActionCallback,
		(XtCallbackProc)frameselect_callback,
		(XtPointer)NULL
		);

  XtAddCallback(RangeToggle,
		XmNvalueChangedCallback,
		(XtCallbackProc)range_callback,
		(XtPointer)NULL
		);

  XtAddCallback(OnceToggle,
		XmNvalueChangedCallback,
		(XtCallbackProc)once_callback,
		(XtPointer)NULL
		);

  XtAddCallback(BounceToggle,
		XmNvalueChangedCallback,
		(XtCallbackProc)bounce_callback,
		(XtPointer)NULL
		);

  XtAddCallback(CommandText,
		XmNactivateCallback,
		(XtCallbackProc)typecommand_cback,
		(XtPointer)CommandWindow
		);

  XtAddCallback(SpeedScale,
		XmNdragCallback,
		(XtCallbackProc)speed_callback,
		(XtPointer)NULL
		);

  dummy = freopen("/dev/null", "w", stderr);
  dup2(oldstderr, fileno(stderr));
  close(oldstderr);

  /* Bring the application window up on the screen. */
}
Esempio n. 25
0
boolean fips_partition::split (fips_harddrive hd)
{
	if (read_boot_sector ())
		error ("Error reading boot sector");

	if (global.debug_mode)
	{
		fprintf
		(
			global.debugfile,
			"\nBoot sector drive %02Xh, partition %u:\n\n",
			hd.number,
			number + 1
		);

		hexwrite
		(
			boot_sector->data,
			512,
			global.debugfile
		);
	}

	get_bpb ();

	printx ("\nBoot sector:\n\n");
	print_bpb ();

	get_info ();
	if (global.debug_mode)
		write_info_debugfile ();

	check ();

	fat16 fat1 (this,1);
	fat16 fat2 (this,2);

	fat1.check_against (&fat2);

	dword new_part_min_cylinder =
		min_cylinder (fat2, hd.geometry);

	if (ask_if_save()) save_root_and_boot(&hd,this);

	dword new_start_cylinder =
		ask_for_new_start_cylinder
		(
			partition_info->start_cylinder,
			new_part_min_cylinder,
			partition_info->end_cylinder,
			hd.geometry.heads * hd.geometry.sectors
		);

	fat2.check_empty
	(
		new_start_cylinder
			* hd.geometry.heads
			* hd.geometry.sectors
		- partition_info->start_sector_abs
	);

	hd.calculate_new_root (new_start_cylinder, this);

	hd.put_partition_table();
	hd.get_partition_table();

	printx ("\nNew partition table:\n\n");
	hd.print_partition_table ();

	hd.check (FINAL_CHECK);

	if (ask_if_continue () == false)
	{
		return (false);
	}

	calculate_new_boot ();

	put_bpb ();
	get_bpb ();

	printx ("\nNew boot sector:\n\n");
	print_bpb ();

	get_info ();
	if (global.debug_mode)
		write_info_debugfile ();

	check();

	if (!global.test_mode)
	{
		ask_for_write_permission ();

		if (hd.write_root_sector ())
			error ("Error writing root sector");

		if (write_boot_sector ())
			error ("Error writing boot sector");

		printx ("Repartitioning complete\n");
	}

	return (true);
}
Esempio n. 26
0
int main(int argc, char **argv) {
	int result = 0;
	int i;

  userui_ops[0] = &userui_text_ops;
	userui_ops[1] = FBSPLASH_OPS;
	userui_ops[2] = USPLASH_OPS;
	active_ops = &userui_text_ops;

	handle_params(argc, argv);
	setup_signal_handlers();
	open_console();
	open_misc();
	if (!test_run) {
		open_netlink();
		get_nofreeze();
		get_info();
	}

	lock_memory();

	prepare_console();

	/* Initialise all that we can, use the first */
//  active_ops = NULL;
	for (i = 0; i < NUM_UIS; i++) {
		if (userui_ops[i] && userui_ops[i]->load) {
			result = userui_ops[i]->load();
			if (result) {
				if (test_run)
					fprintf(stderr, "Failed to initialise %s module.\n", userui_ops[i]->name);
				else
					printk("Failed to initialise %s module.\n", userui_ops[i]->name);
			} else
				if (!active_ops)
					active_ops = userui_ops[i];
		}
	}

	if (active_ops->prepare)
		active_ops->prepare();

	register_keypress_handler();

	need_cleanup = 1;
	running = 1;

	result = nice(1);

	if (active_ops->memory_required)
		reserve_memory(active_ops->memory_required());
	else
		reserve_memory(4*1024*1024); /* say 4MB */

	enforce_lifesavers();

	if (test_run) {
		safe_to_exit = 0;

		do_test_run();
		return 0;
	}

	if (send_ready())
		message_loop();

	/* The only point we ever reach here is if message_loop crashed out.
	 * If this is the case, we should spin for a few hours before exiting to
	 * ensure that we don't corrupt stuff on disk (if we're past the atomic
	 * copy).
	 */
	sleep(60*60*1); /* 1 hours */
	_exit(1);
}
Esempio n. 27
0
JavaVM* get_saved_java_vm() {
  // This will *not* be the first call to get_info(), so we don't need
  // a valid JNIEnv*
  return get_info(nullptr, 0)->java_vm_;
}
Esempio n. 28
0
/*----------------------------------------------------------------------------*/
ngx_int_t rp_bazaar_cmd_handler(ngx_http_request_t *r)
{
    ngx_http_rp_loc_conf_t *lc;
    rp_bazaar_ctx_t *ctx;
    size_t i = 0;

    ctx = ngx_pcalloc(r->pool, sizeof(rp_bazaar_ctx_t));
    if (ctx == NULL) {
        return NGX_ERROR;
    }
    ctx->redirect = ngx_pcalloc(r->pool, c_redirect_len);
    if (ctx->redirect == NULL) {
        return NGX_ERROR;
    }
    ctx->json_root = NULL;
    ctx->finalize_on_post_handler = 0;
    ctx->in_buffer = NULL;
    ctx->in_buffer_len = 0;
    ctx->in_status = 0;
    ngx_http_set_ctx(r, ctx, ngx_http_rp_module);

    lc = ngx_http_get_module_loc_conf(r, ngx_http_rp_module);

    /* Just test local directory here - we would need to check it for almost
     * all calls anyway
     */
    if(lc->bazaar_dir.data == NULL) {
        fprintf(stderr, "Bazaar local directory not found\n");
        return NGX_HTTP_INTERNAL_SERVER_ERROR;
    }

    ctx->json_root = cJSON_CreateObject(r->pool);
    if(ctx->json_root == NULL) {
        fprintf(stderr, "Cannot allocate cJSON object\n");
        return NGX_HTTP_INTERNAL_SERVER_ERROR;
    }

    /* Bazaar commands */
    for(i = 0; bazaar_cmds[i].name != NULL; i++) {

        ngx_str_t arg_name = { strlen(bazaar_cmds[i].name),
                               (u_char *)bazaar_cmds[i].name };
        ngx_uint_t arg_key = ngx_hash_key(arg_name.data, arg_name.len);
        ngx_http_variable_value_t *arg_val = NULL;

        int rc;
        char **arg_argv = NULL;
        int    arg_argc = 0;

        arg_val = ngx_http_get_variable(r, &arg_name, arg_key);

        /* check validity of the specified http variables
         * note: not all attributes of arg_value are set within ngx_http_get_variable, thus
         * the order of the following checks are important otherwise it could come to the usage
         * of uninitialized value what would lead to invalid processing
         */
        if (!arg_val)                continue;
        if (arg_val->not_found == 1) continue;
        if (arg_val->valid == 0)     continue;

        arg_val->data[arg_val->len] = '\0';
        arg_argc = rp_module_cmd_parse_args((const char *)arg_val->data,
                                            arg_val->len,
                                            &arg_argv);

        fprintf(stderr, "Calling application: %s\n", &bazaar_cmds[i].name[4]);

        /* Install/Remove special case */
        if ( !strncmp(&bazaar_cmds[i].name[4], "install", 7) ||
             !strncmp(&bazaar_cmds[i].name[4], "remove",  6) ) {
            if(arg_argv) {
                for(i = 0; i < (size_t)arg_argc; i++) {
                    if(arg_argv[i]) {
                        free(arg_argv[i]);
                        arg_argv[i] = NULL;
                    }
                }
                free(arg_argv);
            }
            return rp_bazaar_install(r);
        }

        if((rc = bazaar_cmds[i].func(r, &ctx->json_root, arg_argc, arg_argv)) < 0) {
            /* error - fill the output buffer and send it back */
            fprintf(stderr, "Application %s failed: %d\n",
                     bazaar_cmds[i].name, rc);
        }

        if(arg_argv) {
            for(i = 0; i < (size_t)arg_argc; i++) {
                if(arg_argv[i]) {
                    free(arg_argv[i]);
                    arg_argv[i] = NULL;
                }
            }
            free(arg_argv);
        }

        /* Prepare response header & body */
        return rp_module_send_response(r, &ctx->json_root);
    }

    int ret = 0;

    /* Unknown command response */
    if (i >= sizeof(bazaar_cmds)/sizeof(rp_module_cmd_t)) {
        rp_module_cmd_error(&ctx->json_root, "Unknown command.", NULL, r->pool);
        return rp_module_send_response(r, &ctx->json_root);
    }

    /* Default Bazaar entry point - list of applications with versions */
    cJSON *json_tok = NULL;

    char *host = (char *)r->headers_in.server.data;
    char mac[18];
    sprintf(mac, "00:00:00:00:00:00");
    if (rp_bazaar_get_mac("/sys/class/net/eth0/address", mac)) {
        fprintf(stderr, "Cannot obtain MAC address.\n");
    }

    static unsigned long long dna = 0;
    if (!dna || dna == 1) {
		if (rp_bazaar_get_dna(&dna)) {
			fprintf(stderr, "Cannot obtain DNA number.\n");
		}
	}
    char dna_s[64];
    sprintf(dna_s, "%016llx", dna);

    /* Get Ecosystem version */
    char ecoversion[64];
    sprintf(ecoversion, "unknown");
    cJSON *ecoinfo = NULL;
    if (!get_info(&ecoinfo, (const char *)lc->bazaar_dir.data,
                  "", r->pool)) {
        fprintf(stderr, "Cannot obtain Ecosystem version.\n");
    } else {
        if (ecoinfo != NULL) {

            cJSON *j_ver = cJSON_GetObjectItem(ecoinfo, "version");
            if(j_ver == NULL) {
                fprintf(stderr, "Cannot get version from ecoinfo JSON.\n");
            } else {
                strncpy(ecoversion, j_ver->valuestring, sizeof ecoversion);
                cJSON_Delete(j_ver, r->pool);
            }

            cJSON_Delete(ecoinfo, r->pool);
        }
    }

    /* Populate JSON */
    cJSON_AddItemToObject(ctx->json_root, "version",
                          cJSON_CreateString(ecoversion, r->pool),
                          r->pool);

    cJSON_AddItemToObject(ctx->json_root, "dna",
                          cJSON_CreateString(dna_s, r->pool), r->pool);

    cJSON_AddItemToObject(ctx->json_root, "mac",
                          cJSON_CreateString(mac, r->pool), r->pool);

    // TODO: Serial number?

    cJSON_AddItemToObject(ctx->json_root, "host",
                          cJSON_CreateString(host, r->pool),
                          r->pool);

    cJSON *apps_root;
    cJSON_AddItemToObject(ctx->json_root, "apps",
                          apps_root=cJSON_CreateObject(r->pool), r->pool);
    if(apps_root == NULL) {
        fprintf(stderr, "Can not allocate cJSON object\n");
        return NGX_HTTP_INTERNAL_SERVER_ERROR;
    }

    fprintf(stderr, "Making list of apps\n");

    /* Add the non-verbose list of apps */
    rp_bazaar_app_get_local_list((const char *)lc->bazaar_dir.data,
                                 &apps_root, r->pool, 0);

    /* Issue a POST with JSON defined above to Bazaar server */
    char *js = cJSON_Print(ctx->json_root, r->pool);
    cJSON_Minify(js);

    fprintf(stderr, "Bazaar handshake:\n%s", js);

    char *jse = NULL;
    char *jsp = NULL;
    char *bazaar_dv = NULL;
    const char *c_payload = "payload=";
    const char *c_device = "/device";

    jse = url_encode(js);

    jsp = malloc(strlen(jse) + strlen(c_payload) + 1);
    if (!jsp) {
        fprintf(stderr, "Cannot malloc() payload.\n");
        ret = NGX_HTTP_INTERNAL_SERVER_ERROR;
        goto out;
    }
    sprintf(jsp, "%s%s", c_payload, jse);

    bazaar_dv = (char *)malloc(strlen((char *)lc->bazaar_server.data) +
                               strlen(c_device) + 1);
    if (!bazaar_dv) {
        fprintf(stderr, "Cannot malloc() device.\n");
        ret = NGX_HTTP_INTERNAL_SERVER_ERROR;
        goto out;
    }
    sprintf(bazaar_dv, "%s%s", lc->bazaar_server.data, c_device);
    fprintf(stderr, "post bazaar_dv %s\n", bazaar_dv);

    post_resp_t resp = { NULL, 0 };
    if (post(jsp, bazaar_dv, &resp)) {
        if (resp.data) free(resp.data);
        /* Redirect to Bazaar access error */
        fprintf(stderr, "Cannot access %s.\n", bazaar_dv);
        snprintf(ctx->redirect, c_redirect_len,
                 "http://%s/error_bazaar_access.html", host);
        goto out;
    }

    /* Get token from POST response */
    if (resp.data) {

        fprintf(stderr,"Bazaar handshake response:\n%s", resp.data);

        json_tok = cJSON_Parse(resp.data, r->pool);
        if (!json_tok) {
            /* Redirect to Bazaar protocol error */
            fprintf(stderr,"No JSON found in the following response:\n\"%s\"\n", resp.data);
            snprintf(ctx->redirect, c_redirect_len,
                     "http://%s/error_bazaar_proto.html", host);
        } else {

            cJSON *jtok = cJSON_GetObjectItem(json_tok, "token");

            if (!jtok) {
                /* Redirect to Bazaar protocol error */
                fprintf(stderr, "No token found in the following JSON:\n\"%s\"\n", resp.data);
                snprintf(ctx->redirect, c_redirect_len,
                         "http://%s/error_bazaar_proto.html", host);
            } else {
                /* Redirect to Bazaar with token */
                snprintf(ctx->redirect, c_redirect_len, "%s/token/%s",
                        lc->bazaar_server.data, jtok->valuestring);
                /* Store token for session control */
                strncpy(g_token, jtok->valuestring, c_token_len);
                g_token[c_token_len - 1] = '\0';
            }
        }

        free(resp.data);
    }

 out:
    if (jsp) free(jsp);
    if (jse) free(jse);
    if (bazaar_dv) free(bazaar_dv);
    //TODO: Is ctx->json_root handled by the pool deallocator?
    //if (ctx->json_root) cJSON_Delete(ctx->json_root, r->pool);
    if (json_tok) cJSON_Delete(json_tok, r->pool);

    if (ret) return ret;

    fprintf(stderr, "Redirecting to: %s\n", ctx->redirect);
    return rp_module_redirect(r, ctx->redirect);
}
Esempio n. 29
0
void init_NativePtr(JNIEnv* env, jobject obj, NativeObjPtr* ptr) {
  auto info = get_info(env, __LINE__);
  // Ignore previous values in NativePtr
  TwoAddrs buf(std::move(*ptr));
  buf.copy_to_scala(env, obj, info);
}
Esempio n. 30
0
static VALUE dictinfo_jargon(VALUE self) {
    return rb_str_new2(get_info(self)->jargon);
}