示例#1
0
/* read 0x9c00-0x9fff */
static BYTE finalexpansion_io3_read(WORD addr)
{
    BYTE value;

    finalexpansion_device.io_source_valid = 0;

    addr &= 0x03;
    FE_DEBUG(("Read reg%02x. (locked=%d)", addr, is_locked()));
    if (!is_locked()) {
        switch (addr) {
            case 0x02:
                value = register_a;
                finalexpansion_device.io_source_valid = 1;
                break;
            case 0x03:
                value = register_b;
                finalexpansion_device.io_source_valid = 1;
                break;
            default:
                value = vic20_cpu_last_data;
                break;
        }
    } else {
        value = vic20_cpu_last_data;
    }
    return value;
}
inline int sysmon_power_daemon_task(){
	if (__VERIFIER_nondet_int()) return __VERIFIER_nondet_int();
	mutex_enter(MTX);
	switch (__VERIFIER_nondet_int()) {
	case PSWITCH_EVENT_RELEASED:
		KASSERT(is_locked(MTX));
		if (__VERIFIER_nondet_int()) {
			mutex_exit(MTX);
			goto out;}
		break;
	case PENVSYS_EVENT_NORMAL:
		KASSERT(is_locked(MTX));
		if (__VERIFIER_nondet_int()) {
			mutex_exit(MTX);
			goto out;}
		break;
	default:
		mutex_exit(MTX);
		goto out;}
	sysmon_queue_power_event();
	if (__VERIFIER_nondet_int()) {
		mutex_exit(MTX);
		goto out;} 
	else {
		cv_broadcast(COND);
		mutex_exit(MTX);}
	out:
  assert(1);
	return __VERIFIER_nondet_int(); }
示例#3
0
文件: lock.c 项目: aaannndddyyy/fin
int unlock()
{
  char directory[STRING_BLOCK];
  char command[STRING_BLOCK];

  database_directory(directory);
  if (is_locked(directory)!=0) {
    sprintf((char*)command,"bcrypt %s/*.bfe", directory);
    if (system(command)!=0) {
      printf("Command failed\n");
    }
  }
  return is_locked(directory);
}
示例#4
0
/* store 0x9c00-0x9fff */
static void finalexpansion_io3_store(WORD addr, BYTE value)
{
    addr &= 0x03;
    FE_DEBUG(("Wrote reg%02x = %02x. (locked=%d)", addr, value, is_locked()));
    if (!is_locked()) {
        switch (addr) {
            case 0x02:
                register_a = value;
                break;
            case 0x03:
                register_b = value;
                break;
        }
    }
}
示例#5
0
 wr_lock_guard_t::~wr_lock_guard_t()
 {
     if (is_locked())
     {
         unlock();
     }
 }
/*
 * Check active_flag if PLL is in FSM mode, otherwise check lock_det
 * bit. This function assumes PLLs are already configured to the
 * right mode.
 */
static bool update_finish(struct alpha_pll_clk *pll)
{
	if (pll->fsm_en_mask)
		return is_active(pll);
	else
		return is_locked(pll);
}
示例#7
0
void CControl_Manager::reinit()
{
	if(	m_object->CCustomMonster::use_simplified_visual() ) return;
	// todo: make it simpler
	// reinit pure first, base second, custom third
	CONTROLLERS_MAP_IT it;

	for (it = m_control_elems.begin(); it != m_control_elems.end(); ++it)  
		if (is_pure(it->second)) it->second->reinit();
	
	for (it = m_control_elems.begin(); it != m_control_elems.end(); ++it)  
		if (is_base(it->second)) it->second->reinit();
	
	for (it = m_control_elems.begin(); it != m_control_elems.end(); ++it)  
		if (!is_pure(it->second) && !is_base(it->second)) it->second->reinit();

	// fill active elems
	m_active_elems.clear	();
	m_active_elems.reserve	(ControlCom::eControllersCount);
	for (it = m_control_elems.begin(); it != m_control_elems.end(); ++it)  {
		if (it->second->is_active() && !is_locked(it->second)) {
			m_active_elems.push_back(it->second);
		}
	}

}
inline void sysmonopen_power(){
	mutex_enter(MTX);
	if (__VERIFIER_nondet_int())
		KASSERT(is_locked(MTX));
	mutex_exit(MTX);
  assert(1);
}
示例#9
0
 void wr_lock_guard_t::unlock()
 {
     if (is_locked())
     {
         m_is_locked = false;
         m_mutex.unlock();
     }
 }
示例#10
0
/*---------------------------------------------------------------------*/
bool NOMAD::Cache::lock ( const std::string & file_name )
{
    if ( is_locked ( file_name ) )
        return false;
    
    Cache::_locked_files.insert ( file_name );
    _locked_file = file_name;
    
    return true;
}
static enum handoff alpha_pll_handoff(struct clk *c)
{
	struct alpha_pll_clk *pll = to_alpha_pll_clk(c);
	struct alpha_pll_masks *masks = pll->masks;
	u64 a_val;
	u32 alpha_en, l_val, regval;

	/* Set the PLL_HW_UPDATE_LOGIC_BYPASS bit before continuing */
	if (pll->dynamic_update) {
		regval = readl_relaxed(MODE_REG(pll));
		regval |= ALPHA_PLL_HW_UPDATE_LOGIC_BYPASS;
		writel_relaxed(regval, MODE_REG(pll));
	}

	update_vco_tbl(pll);

	if (!is_locked(pll)) {
		if (pll->slew) {
			if (c->rate && dyna_alpha_pll_set_rate(c, c->rate))
				WARN(1, "%s: Failed to configure rate\n",
					c->dbg_name);
		} else {
			if (c->rate && alpha_pll_set_rate(c, c->rate))
				WARN(1, "%s: Failed to configure rate\n",
					c->dbg_name);
		}
		__init_alpha_pll(c);
		return HANDOFF_DISABLED_CLK;
	} else if (pll->fsm_en_mask && !is_fsm_mode(MODE_REG(pll))) {
		WARN(1, "%s should be in FSM mode but is not\n", c->dbg_name);
	}

	l_val = readl_relaxed(L_REG(pll));
	/* read u64 in two steps to satisfy alignment constraint */
	a_val = readl_relaxed(A_REG(pll) + 0x4);
	a_val = a_val << 32 | readl_relaxed(A_REG(pll));
	/* get upper 32 bits */
	a_val = a_val >> (ALPHA_REG_BITWIDTH - ALPHA_BITWIDTH);

	alpha_en = readl_relaxed(ALPHA_EN_REG(pll));
	alpha_en &= masks->alpha_en_mask;
	if (!alpha_en)
		a_val = 0;

	c->rate = compute_rate(pll, l_val, a_val);

	/*
	 * Unconditionally vote for the PLL; it might be on because of
	 * another master's vote.
	 */
	if (pll->fsm_en_mask)
		__alpha_pll_vote_enable(pll);

	return HANDOFF_ENABLED_CLK;
}
示例#12
0
void markOopDesc::print_on(outputStream* st) const {
  if (is_locked()) {
    st->print("locked(0x%lx)->", value());
    markOop(*(markOop*)value())->print_on(st);
  } else {
    assert(is_unlocked(), "just checking");
    st->print("mark(");
    st->print("hash %#lx,", hash());
    st->print("age %d)", age());
  }
}
示例#13
0
文件: command.c 项目: dtaht/hashlet
bool lock (int fd, enum DATA_ZONE zone, uint16_t crc)
{

  uint8_t param1 = 0;
  uint8_t param2[2];
  uint8_t response;
  bool result = false;

  if (is_locked (fd, zone))
    return true;

  memcpy (param2, &crc, sizeof (param2));

  const uint8_t CONFIG_MASK = 0;
  const uint8_t DATA_MASK = 1;

  switch (zone)
    {
    case CONFIG_ZONE:
      param1 |= CONFIG_MASK;
      break;
    case DATA_ZONE:
    case OTP_ZONE:
      param1 |= DATA_MASK;
      break;
    default:
      assert (false);
    }

  struct Command_ATSHA204 c = make_command ();

  set_opcode (&c, COMMAND_LOCK);
  set_param1 (&c, param1);
  set_param2 (&c, param2);
  set_data (&c, NULL, 0);
  set_execution_time (&c, 0, LOCK_AVG_EXEC);

  if (RSP_SUCCESS == process_command (fd, &c, &response, sizeof (response)))
    {
      if (0 == response)
        {
          result = true;
          CTX_LOG (DEBUG, "Lock Successful");
        }
      else
        {
          CTX_LOG (DEBUG, "Lock Failed");
        }
    }


  return result;

}
示例#14
0
void u2f_init()
{
	int8_t i,ec;
	uint8_t * clear = 0;
	struct atecc_response res;
	
	if (is_locked(appdata.tmp)) {	
		eeprom_read(U2F_EEPROM_CONFIG, (uint8_t* )&key_store, sizeof(struct key_storage_header));

		// initialize key handles
		if (key_store.num_keys != U2F_NUM_KEYS)
		{
			//watchdog();
	
			for (i=0; i < U2F_NUM_KEYS; i++)
			{
				//watchdog();
				ec = atecc_send_recv(ATECC_CMD_RNG,ATECC_RNG_P1,ATECC_RNG_P2,
								NULL, 0,
								appdata.tmp,
								sizeof(appdata.tmp), &res);
				if (ec != 0)
				{
					//u2f_printb("atecc_send_recv failed ",2,i,-ec);
	
					// erase eeprom
					//eeprom_erase(U2F_EEPROM_CONFIG);
	
					// erase ram
					//for (i=0; i<0x400;i++)
					//{
					//	*(clear++) = 0x0;
					//}
					// reset
					//reboot();
					return;
				}
				res.buf[0] = i+1;

				eeprom_write(U2F_KEYS_ADDR + i * U2F_KEY_HANDLE_SIZE,
							 res.buf, U2F_KEY_HANDLE_SIZE);
			}

			key_store.num_keys = U2F_NUM_KEYS;
			key_store.valid_keys = 0;
			key_store.num_issued = 0;
			flush_key_store();
		}
	}
}
示例#15
0
文件: lock.c 项目: aaannndddyyy/fin
int lock()
{
  char directory[STRING_BLOCK];
  char command[STRING_BLOCK];
  int retval=0;

  database_directory(directory);

  if (is_locked(directory)==0) {
    sprintf((char*)command,"bcrypt %s/*", directory);
    retval = system(command);
  }
  return retval;
}
示例#16
0
PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC

void markOopDesc::print_on(outputStream* st) const {
  if (is_locked()) {
    st->print("locked(" INTPTR_FORMAT ")->", value());
    markOop(*(markOop*)value())->print_on(st);
  } else {
    assert(is_unlocked() || has_bias_pattern(), "just checking");
    st->print("mark(");
    if (has_bias_pattern())  st->print("biased,");
    st->print("hash %#lx,", hash());
    st->print("age %d)", age());
  }
}
示例#17
0
文件: open.c 项目: jophxy/samba
static int truncate_unless_locked(struct connection_struct *conn, files_struct *fsp)
{
	SMB_BIG_UINT mask = (SMB_BIG_UINT)-1;

	if (is_locked(fsp,fsp->conn,mask,0,WRITE_LOCK,True)){
		errno = EACCES;
		unix_ERR_class = ERRDOS;
		unix_ERR_code = ERRlock;
		unix_ERR_ntstatus = dos_to_ntstatus(ERRDOS, ERRlock);
		return -1;
	} else {
		return conn->vfs_ops.ftruncate(fsp,fsp->fd,0); 
	}
}
示例#18
0
int Amazons::add_player(Player& p) {
    if (mImpl->p_count >= mImpl->board_size) {
        fprintf(p.get_out_stream(), "Cannot add more players than the side"
                                    "of the board.\n");
        lock_game();
        return 0;
    }
    if (is_locked()) {
        fprintf(stderr, "Game is locked.\n");
        return 0;
    }
    mImpl->p[mImpl->p_count] = &p;
    mImpl->p_count++;
    return mImpl->p_count;
}
示例#19
0
void JavaNear::print_value_on(Stream* st) {
  if (is_locked()) {
    st->print("locked ");
  }
  st->print("JavaNear");
  if (has_hash()) {
    st->print(" [hash = %d]", hash_value());
  }
  JavaClass::Raw klass     = this->klass();
  JavaNear::Raw  protoNear = klass().prototypical_near();
  if (this->equals(&protoNear)) { 
    st->print(" prototype for ");
    klass().print_name_on(st);
  }
}
示例#20
0
PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC

void markOopDesc::print_on(outputStream* st) const {
  if (is_marked()) {
    st->print(" marked(" INTPTR_FORMAT ")", value());
  } else if (has_monitor()) {
    // have to check has_monitor() before is_locked()
    st->print(" monitor(" INTPTR_FORMAT ")=", value());
    ObjectMonitor* mon = monitor();
    if (mon == NULL) {
      st->print("NULL (this should never be seen!)");
    } else {
      st->print("{count=" INTPTR_FORMAT ",waiters=" INTPTR_FORMAT
                ",recursions=" INTPTR_FORMAT ",owner=" INTPTR_FORMAT "}",
                mon->count(), mon->waiters(), mon->recursions(),
                p2i(mon->owner()));
    }
  } else if (is_locked()) {
    st->print(" locked(" INTPTR_FORMAT ")->", value());
    if (is_neutral()) {
      st->print("is_neutral");
      if (has_no_hash()) {
        st->print(" no_hash");
      } else {
        st->print(" hash=" INTPTR_FORMAT, hash());
      }
      st->print(" age=%d", age());
    } else if (has_bias_pattern()) {
      st->print("is_biased");
      JavaThread* jt = biased_locker();
      st->print(" biased_locker=" INTPTR_FORMAT, p2i(jt));
    } else {
      st->print("??");
    }
  } else {
    assert(is_unlocked() || has_bias_pattern(), "just checking");
    st->print("mark(");
    if (has_bias_pattern()) st->print("biased,");
    st->print("hash %#lx,", hash());
    st->print("age %d)", age());
  }
}
示例#21
0
void LinearSolver::set_solve_b()
{
	m_solve_b_vec.clear();
	for (size_t i = 0; i < m_equation_vec.size(); i++)
	{
		vector<pair<int, double> >& cur_equ = m_equation_vec[i];

		if (i == 1251)
		{
			size_t aaaaa = 5;
		}

		//
		double sum_b = m_right_b_vec[i];
		size_t lock_num = 0;
		for (size_t j = 0 ; j < cur_equ.size(); j++)
		{
			pair<int, double>& var_ = cur_equ[j];
			if (is_locked(var_.first))
			{
				sum_b -= m_xc_[var_.first] * var_.second;
				lock_num++;
			}
		}

		if (lock_num < cur_equ.size())
		{
          // Warning: the following codes commented by hywei, there may be error 
			// if (_isnan(sum_b))
			// {
			// 	printf("is nan b.\n");
			// 	size_t aaaaaa = 6;
			// }
			m_solve_b_vec.push_back(sum_b);
			
		}
	}
}
static enum handoff fabia_alpha_pll_handoff(struct clk *c)
{
	struct alpha_pll_clk *pll = to_alpha_pll_clk(c);
	u64 a_val;
	u32 l_val, regval;

	/* Set the PLL_HW_UPDATE_LOGIC_BYPASS bit before continuing */
	regval = readl_relaxed(MODE_REG(pll));
	regval |= ALPHA_PLL_HW_UPDATE_LOGIC_BYPASS;
	writel_relaxed(regval, MODE_REG(pll));

	if (!is_locked(pll)) {
		if (c->rate && fabia_alpha_pll_set_rate(c, c->rate))
			WARN(1, "%s: Failed to configure rate\n", c->dbg_name);
		__init_alpha_pll(c);
		return HANDOFF_DISABLED_CLK;
	} else if (pll->fsm_en_mask && !is_fsm_mode(MODE_REG(pll))) {
		WARN(1, "%s should be in FSM mode but is not\n", c->dbg_name);
	}

	l_val = readl_relaxed(FABIA_L_REG(pll));

	if (pll->fabia_frac_offset)
		a_val = readl_relaxed(FABIA_FRAC_OFF(pll));
	else
		a_val = readl_relaxed(FABIA_FRAC_REG(pll));

	c->rate = compute_rate(pll, l_val, a_val);

	/*
	 * Unconditionally vote for the PLL; it might be on because of
	 * another master's vote.
	 */
	if (pll->fsm_en_mask)
		__alpha_pll_vote_enable(pll);

	return HANDOFF_ENABLED_CLK;
}
示例#23
0
 BOOST_DLLEXPORT static T & get_mutable_instance(){
     BOOST_ASSERT(! is_locked());
     return get_instance();
 }
示例#24
0
static int save_lua_report(udefrag_job_parameters *jp)
{
    wchar_t *path = NULL;
    WINX_FILE *f;
    wchar_t *cn;
    wchar_t compname[MAX_COMPUTERNAME_LENGTH + 1];
    char utf8_compname[(MAX_COMPUTERNAME_LENGTH + 1) * 4];
    char buffer[512];
    struct prb_traverser t;
    winx_file_info *file;
    char *comment;
    char *status;
    int length;
    winx_time tm;
    
    /* should be enough for any path in UTF-8 encoding */
    #define MAX_UTF8_PATH_LENGTH (256 * 1024)
    char *utf8_path;
    
    utf8_path = winx_tmalloc(MAX_UTF8_PATH_LENGTH);
    if(utf8_path == NULL){
        mtrace();
        return (-1);
    }
    
    path = get_report_path(jp);
    if(path == NULL)
        return UDEFRAG_NO_MEM;
    
    f = winx_fbopen(path,"w",RSB_SIZE);
    if(f == NULL){
        f = winx_fopen(path,"w");
        if(f == NULL){
            winx_free(path);
            winx_free(utf8_path);
            return (-1);
        }
    }

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

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

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

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

    itrace("report saved to %ws",path);
    winx_fclose(f);
    winx_free(path);
    winx_free(utf8_path);
    return 0;
}
示例#25
0
    void CGraphTetgen::tetrahedralize() {
        if(surface_ != nil) {
            graphite_to_tetgen() ;
        }

        FOR_EACH_HALFEDGE(Map, surface_, it) {
            if(it->is_border()) {
                Logger::err("CGraphTetgen") 
                    << "Surface was not closed, cannot stuff open surface" 
                    << std::endl ;
                return ;
            }
        }

        // Create tetgen argument string.

        std::ostringstream s ;
        // p: input data is surfacic
        // n: output tet neighbors
        // q: desired quality
        s << "pnq" << max_tet_shape_ ;
        if(max_tet_volume_ > 0.0) {
            s << "a" << max_tet_volume_ ;
        }

        // AA: generate region tags 
        // for each shell.
        if(tag_regions_) {
            s << "AA" ;
        }
        
        // YY: prohibit steiner points on boundaries
        // (first Y for exterior boundary, second Y for the
        // other ones).

        if(
            add_steiner_points_on_exterior_boundary_ &&
            !add_steiner_points_on_interior_boundary_
        ) {
            Logger::warn("CGraphTetgen") 
                << "Invalid combination of flags (do not preserve exterior boundary and preserve interior ones)"
                << " - preserving exterior boundary as well ..."
                << std::endl ;
            add_steiner_points_on_exterior_boundary_ = false ;
        }

        if(!add_steiner_points_on_exterior_boundary_) {
            s << "Y" ;
        }

        if(!add_steiner_points_on_interior_boundary_) {
            s << "Y" ;
        }

        std::string tetgen_args = s.str() ;
        try {
            ::tetrahedralize((char*)(tetgen_args.c_str()), &tetgen_surface_, &tetgen_volume_) ;
        } catch(...) {
            Logger::err("CGraphTetgen") 
                << "tetgen encountered an error, relaunching in diagnose mode" << std::endl ;
            ::tetrahedralize("d", &tetgen_surface_, &tetgen_volume_) ;

            if(lock_intersections_) {
                // Mark the vertices of the facets that intersect.
                MapVertexLock is_locked(surface_) ;
                std::set<int>& isects = tetgen_surface_.isectvertices ;
                int cur_id = 1 ;
                FOR_EACH_VERTEX(Map, surface_, it) {
                    is_locked[it] = (isects.find(cur_id) != isects.end()) ;
                    cur_id++ ;
                }
            }
        }
示例#26
0
/* the main program... */
int main(int argc, char *argv[])
{
  int i;
  sigset_t signalmask, oldmask;
#ifdef HAVE_PTHREAD_TIMEDJOIN_NP
  struct timespec ts;
#endif /* HAVE_PTHREAD_TIMEDJOIN_NP */
  /* close all file descriptors (except stdin/out/err) */
  i = sysconf(_SC_OPEN_MAX) - 1;
  /* if the system does not have OPEN_MAX just close the first 32 and
     hope we closed enough */
  if (i < 0)
    i = 32;
  for (; i > 3; i--)
    close(i);
  /* parse the command line */
  parse_cmdline(argc, argv);
  /* clean the environment */
#ifdef HAVE_CLEARENV
  if (clearenv() || putenv("HOME=/") || putenv("TMPDIR=/tmp") ||
      putenv("LDAPNOINIT=1"))
  {
    log_log(LOG_ERR, "clearing environment failed");
    exit(EXIT_FAILURE);
  }
#else /* not HAVE_CLEARENV */
  /* this is a bit ugly */
  environ = sane_environment;
#endif /* not HAVE_CLEARENV */
  /* disable the nss_ldap module for this process */
  disable_nss_ldap();
  /* set LDAP log level */
  if (myldap_set_debuglevel(nslcd_debugging) != LDAP_SUCCESS)
    exit(EXIT_FAILURE);
  /* read configuration file */
  cfg_init(NSLCD_CONF_PATH);
  /* set default mode for pidfile and socket */
  (void)umask((mode_t)0022);
  /* see if someone already locked the pidfile
     if --check option was given exit TRUE if daemon runs
     (pidfile locked), FALSE otherwise */
  if (nslcd_checkonly)
  {
    if (is_locked(NSLCD_PIDFILE))
    {
      log_log(LOG_DEBUG, "pidfile (%s) is locked", NSLCD_PIDFILE);
      exit(EXIT_SUCCESS);
    }
    else
    {
      log_log(LOG_DEBUG, "pidfile (%s) is not locked", NSLCD_PIDFILE);
      exit(EXIT_FAILURE);
    }
  }
  /* normal check for pidfile locked */
  if (is_locked(NSLCD_PIDFILE))
  {
    log_log(LOG_ERR, "daemon may already be active, cannot acquire lock (%s): %s",
            NSLCD_PIDFILE, strerror(errno));
    exit(EXIT_FAILURE);
  }
  /* daemonize */
  if ((!nslcd_debugging) && (!nslcd_nofork) && (daemon(0, 0) < 0))
  {
    log_log(LOG_ERR, "unable to daemonize: %s", strerror(errno));
    exit(EXIT_FAILURE);
  }
  /* intilialize logging */
  if (!nslcd_debugging)
    log_startlogging();
  log_log(LOG_INFO, "version %s starting", VERSION);
  /* start subprocess to do invalidating if reconnect_invalidate is set */
  for (i = 0; i < LM_NONE; i++)
    if (nslcd_cfg->reconnect_invalidate[i])
      break;
  if (i < LM_NONE)
    invalidator_start();
  /* write pidfile */
  create_pidfile(NSLCD_PIDFILE);
  /* install handler to close stuff off on exit and log notice */
  if (atexit(exithandler))
  {
    log_log(LOG_ERR, "atexit() failed: %s", strerror(errno));
    exit(EXIT_FAILURE);
  }
  /* create socket */
  nslcd_serversocket = create_socket(NSLCD_SOCKET);
  if ((nslcd_cfg->gid != NOGID) && (nslcd_cfg->uidname != NULL))
  {
#ifdef HAVE_INITGROUPS
    /* load supplementary groups */
    if (initgroups(nslcd_cfg->uidname, nslcd_cfg->gid) < 0)
      log_log(LOG_WARNING, "cannot initgroups(\"%s\",%d) (ignored): %s",
              nslcd_cfg->uidname, (int)nslcd_cfg->gid, strerror(errno));
    else
      log_log(LOG_DEBUG, "initgroups(\"%s\",%d) done",
              nslcd_cfg->uidname, (int)nslcd_cfg->gid);
#else /* not HAVE_INITGROUPS */
#ifdef HAVE_SETGROUPS
    /* just drop all supplemental groups */
    if (setgroups(0, NULL) < 0)
      log_log(LOG_WARNING, "cannot setgroups(0,NULL) (ignored): %s",
              strerror(errno));
    else
      log_log(LOG_DEBUG, "setgroups(0,NULL) done");
#else /* not HAVE_SETGROUPS */
    log_log(LOG_DEBUG, "neither initgroups() or setgroups() available");
#endif /* not HAVE_SETGROUPS */
#endif /* not HAVE_INITGROUPS */
  }
  /* change to nslcd gid */
  if (nslcd_cfg->gid != NOGID)
  {
    if (setgid(nslcd_cfg->gid) != 0)
    {
      log_log(LOG_ERR, "cannot setgid(%d): %s",
              (int)nslcd_cfg->gid, strerror(errno));
      exit(EXIT_FAILURE);
    }
    log_log(LOG_DEBUG, "setgid(%d) done", (int)nslcd_cfg->gid);
  }
  /* change to nslcd uid */
  if (nslcd_cfg->uid != NOUID)
  {
    if (setuid(nslcd_cfg->uid) != 0)
    {
      log_log(LOG_ERR, "cannot setuid(%d): %s",
              (int)nslcd_cfg->uid, strerror(errno));
      exit(EXIT_FAILURE);
    }
    log_log(LOG_DEBUG, "setuid(%d) done", (int)nslcd_cfg->uid);
  }
  /* block all these signals so our worker threads won't handle them */
  sigemptyset(&signalmask);
  sigaddset(&signalmask, SIGHUP);
  sigaddset(&signalmask, SIGINT);
  sigaddset(&signalmask, SIGQUIT);
  sigaddset(&signalmask, SIGABRT);
  sigaddset(&signalmask, SIGPIPE);
  sigaddset(&signalmask, SIGTERM);
  sigaddset(&signalmask, SIGUSR1);
  sigaddset(&signalmask, SIGUSR2);
  pthread_sigmask(SIG_BLOCK, &signalmask, &oldmask);
  /* start worker threads */
  log_log(LOG_INFO, "accepting connections");
  nslcd_threads = (pthread_t *)malloc(nslcd_cfg->threads * sizeof(pthread_t));
  if (nslcd_threads == NULL)
  {
    log_log(LOG_CRIT, "main(): malloc() failed to allocate memory");
    exit(EXIT_FAILURE);
  }
  for (i = 0; i < nslcd_cfg->threads; i++)
  {
    if (pthread_create(&nslcd_threads[i], NULL, worker, NULL))
    {
      log_log(LOG_ERR, "unable to start worker thread %d: %s",
              i, strerror(errno));
      exit(EXIT_FAILURE);
    }
  }
  pthread_sigmask(SIG_SETMASK, &oldmask, NULL);
  /* install signalhandlers for some signals */
  install_sighandler(SIGHUP, sig_handler);
  install_sighandler(SIGINT, sig_handler);
  install_sighandler(SIGQUIT, sig_handler);
  install_sighandler(SIGABRT, sig_handler);
  install_sighandler(SIGPIPE, SIG_IGN);
  install_sighandler(SIGTERM, sig_handler);
  install_sighandler(SIGUSR1, sig_handler);
  install_sighandler(SIGUSR2, SIG_IGN);
  /* wait until we received a signal */
  while ((nslcd_receivedsignal == 0) || (nslcd_receivedsignal == SIGUSR1))
  {
    sleep(INT_MAX); /* sleep as long as we can or until we receive a signal */
    if (nslcd_receivedsignal == SIGUSR1)
    {
      log_log(LOG_INFO, "caught signal %s (%d), refresh retries",
              signame(nslcd_receivedsignal), nslcd_receivedsignal);
      myldap_immediate_reconnect();
      nslcd_receivedsignal = 0;
    }
  }
  /* print something about received signal */
  log_log(LOG_INFO, "caught signal %s (%d), shutting down",
          signame(nslcd_receivedsignal), nslcd_receivedsignal);
  /* cancel all running threads */
  for (i = 0; i < nslcd_cfg->threads; i++)
    if (pthread_cancel(nslcd_threads[i]))
      log_log(LOG_WARNING, "failed to stop thread %d (ignored): %s",
              i, strerror(errno));
  /* close server socket to trigger failures in threads waiting on accept() */
  close(nslcd_serversocket);
  nslcd_serversocket = -1;
  /* if we can, wait a few seconds for the threads to finish */
#ifdef HAVE_PTHREAD_TIMEDJOIN_NP
  ts.tv_sec = time(NULL) + 3;
  ts.tv_nsec = 0;
#endif /* HAVE_PTHREAD_TIMEDJOIN_NP */
  for (i = 0; i < nslcd_cfg->threads; i++)
  {
#ifdef HAVE_PTHREAD_TIMEDJOIN_NP
    pthread_timedjoin_np(nslcd_threads[i], NULL, &ts);
#endif /* HAVE_PTHREAD_TIMEDJOIN_NP */
    if (pthread_kill(nslcd_threads[i], 0) == 0)
      log_log(LOG_ERR, "thread %d is still running, shutting down anyway", i);
  }
  /* we're done */
  return EXIT_FAILURE;
}
示例#27
0
//////////////////////////////////////////////////////////////////////
// private methods
//////////////////////////////////////////////////////////////////////
void LinearSolver::set_solve_matrix()
{
	//
	vector<bool> row_valid_flag(m_equation_vec.size());
	fill(row_valid_flag.begin(), row_valid_flag.end(), false);
	int row_size = 0;
	for (size_t i = 0; i < m_equation_vec.size(); i++)
	{
		vector<pair<int, double> >& cur_equ = m_equation_vec[i];

		//
		size_t lock_num = 0;
		for (size_t j = 0 ; j < cur_equ.size(); j++)
		{
			pair<int, double>& var_ = cur_equ[j];
			if (is_locked(var_.first))
			{
				lock_num++;
			}
		}
		if (lock_num < cur_equ.size()) {
			row_size++;
			row_valid_flag[i] = true;
		}
	}
	int col_size = nb_free_variables_;

	//
	CMeshSparseMatrix solve_matrix;
	solve_matrix.SetRowCol(row_size, col_size);

	int row_ = 0;
	for (size_t i = 0; i < m_equation_vec.size(); i++)
	{
		if (row_valid_flag[i])
		{
			vector<pair<int, double> >& cur_equ = m_equation_vec[i];

			//
			for (size_t j = 0 ; j < cur_equ.size(); j++)
			{
				pair<int, double>& var_ = cur_equ[j];
				if (is_free(var_.first)) 
				{
                    // Warning : the following comment by hywei, there may be error
					// if (_isnan(var_.second))
					// {
					// 	printf("is nan.\n");
					// 	size_t aaaaaa = 6;
					//}
					solve_matrix.AddElement(row_, var_.first, var_.second);
				}
			}
			row_++;
		}
	}

	//
	size_t invalid_num = 0;
	vector<size_t> tmp_equ_div_flag_vec(m_equ_div_flag_vec);
	for (size_t i = 1; i < tmp_equ_div_flag_vec.size(); i++)
	{
		size_t start_eqn = tmp_equ_div_flag_vec[i-1];
		size_t end_eqn = tmp_equ_div_flag_vec[i];
		for (size_t j = start_eqn; j < end_eqn; j++)
		{
			if (!row_valid_flag[j])
			{
				invalid_num++;
			}
		}
		m_equ_div_flag_vec[i] = end_eqn - invalid_num;
	}

	//
	solve_matrix.Transpose(m_solve_matrix_AT_);
}
示例#28
0
uint8_t custom_command(struct u2f_hid_msg * msg)
{
	struct atecc_response res;
	struct u2f_hid_msg * reply = (struct u2f_hid_msg *)appdata.tmp;
	uint8_t ec;

	if (msg->cid != U2FHID_BROADCAST) return 0;

	switch(msg->pkt.init.cmd)
	{
		case U2F_CUSTOM_GET_SERIAL_NUMBER:
			if (atecc_send_recv(ATECC_CMD_READ, ATECC_RW_CONFIG | ATECC_RW_EXT, 0,
				NULL, 0, reply->pkt.init.payload, sizeof(reply->pkt.init.payload), &res) == 0 )
			{
				if (res.len > 15)
					res.len = 15;
				reply->cid = msg->cid;
				reply->pkt.init.cmd = msg->pkt.init.cmd;
				U2FHID_SET_LEN(reply, res.len);
				usb_write((uint8_t*)reply, 64);
			}
			else
			{
				reply->cid = msg->cid;
				reply->pkt.init.cmd = msg->pkt.init.cmd;
				U2FHID_SET_LEN(reply, 0);
				usb_write((uint8_t*)reply, 64);
			}
			break;
		case U2F_CUSTOM_GET_CONFIG:
			if (atecc_send_recv(ATECC_CMD_READ, ATECC_RW_CONFIG | ATECC_RW_EXT,
				(msg->pkt.init.payload[0] << 8) | msg->pkt.init.payload[1], NULL, 0, 
				reply->pkt.init.payload, sizeof(reply->pkt.init.payload), &res) == 0)
			{
				if (res.len > 40)
					res.len = 40;
				reply->cid = msg->cid;
				reply->pkt.init.cmd = msg->pkt.init.cmd;
				U2FHID_SET_LEN(reply, res.len);
				usb_write((uint8_t*)reply, 64);
			}
			else
			{
				U2FHID_SET_LEN(msg, 0);
				usb_write((uint8_t*)msg, 64);
			}
			break;
		case U2F_CUSTOM_INIT_CONFIG:
			atecc_setup_config();
			U2FHID_SET_LEN(msg, 0);
			usb_write((uint8_t*)msg, 64);
			break;
		case U2F_CUSTOM_LOCK_CONFIG:
			if (is_locked(appdata.tmp)) {
				msg->pkt.init.payload[0] = 0xff;
				U2FHID_SET_LEN(msg, 1);
				usb_write((uint8_t*)msg, 64);
			}
			else if (atecc_send_recv(ATECC_CMD_LOCK, ATECC_LOCK_CONFIG,
				(msg->pkt.init.payload[0] << 8) | msg->pkt.init.payload[1], NULL, 0, 
				appdata.tmp, sizeof(appdata.tmp), NULL))
			{
				msg->pkt.init.payload[0] = 0xfe;
				U2FHID_SET_LEN(msg, 1);
				usb_write((uint8_t*)msg, 64);
			}
			else
			{
				msg->pkt.init.payload[0] = 0x00;
				U2FHID_SET_LEN(msg, 1);
				usb_write((uint8_t*)msg, 64);
			}
			break;
		case U2F_CUSTOM_GEN_ATT_KEY:
			if (atecc_send_recv(ATECC_CMD_GENKEY, ATECC_GENKEY_PRIVATE, U2F_ATTESTATION_KEY_SLOT,
				NULL, 0, appdata.tmp, sizeof(appdata.tmp), &res) == 0 && res.len <= 64)
			{
				U2FHID_SET_LEN(msg, res.len - 1);
				memmove(msg->pkt.init.payload, res.buf, res.len - 1);
				usb_write((uint8_t*)msg, 64);
			}
			else
			{
				U2FHID_SET_LEN(msg, 0);
				usb_write((uint8_t*)msg, 64);
			}
			break;
			/*
		case U2F_CUSTOM_GET_RNG:
			if (atecc_send_recv(ATECC_CMD_RNG,ATECC_RNG_P1,ATECC_RNG_P2,
				NULL, 0,
				appdata.tmp,
				sizeof(appdata.tmp), &res) == 0 )
			{
				memmove(msg->pkt.init.payload, res.buf, 32);
				U2FHID_SET_LEN(msg, 32);
				usb_write((uint8_t*)msg, 64);
			}
			else
			{
				U2FHID_SET_LEN(msg, 0);
				usb_write((uint8_t*)msg, 64);
			}

			break;
		case U2F_CUSTOM_SEED_RNG:
			ec = atecc_send_recv(ATECC_CMD_NONCE,ATECC_NONCE_RNG_UPDATE,0,
							msg->pkt.init.payload, 20,
							appdata.tmp,
							sizeof(appdata.tmp), &res);
			U2FHID_SET_LEN(msg, 1);
			msg->pkt.init.payload[0] = ec == 0 ? 1 : 0;
			usb_write((uint8_t*)msg, 64);
			break;
			*/
		case U2F_CUSTOM_WIPE_KEYS:

			U2FHID_SET_LEN(msg, 1);
			ec=u2f_wipe_keys();
			msg->pkt.init.payload[0] = ec == 0 ? 1 : 0;
			usb_write((uint8_t*)msg, 64);

			break;
			
		case U2F_CUSTOM_ENTER_BOOTLOADER:
			USB_Detach();
			enterBootloader();
			break;
		case U2F_CUSTOM_INC_COUNT:
			if (atecc_send_recv(ATECC_CMD_COUNTER,
							ATECC_COUNTER_INC, ATECC_COUNTER0,NULL,0,
							appdata.tmp, sizeof(appdata.tmp), &res) == 0)
			{
				memmove(msg->pkt.init.payload, res.buf, res.len);
				U2FHID_SET_LEN(msg, res.len);
				usb_write((uint8_t*)msg, 64);
			}
			else
			{
				U2FHID_SET_LEN(msg, 0);
				usb_write((uint8_t*)msg, 64);
			}
			break;				
		default:
			return 0;
	}
	return 1;
}
示例#29
0
/*---------------------------------------------------------------------*/
bool NOMAD::Cache::load ( const std::string & file_name       ,
                         const int         * p_nb_bb_outputs ,
                         bool                display           )
{
    if ( !file_name.empty() && file_name == _locked_file )
        return true;
    
    if ( file_name.empty() || !_locked_file.empty() || is_locked(file_name) )
        return false;
    
    // the file exists:
    if ( NOMAD::check_read_file ( file_name ) ) {
        
        int           id;
        std::ifstream fin ( file_name.c_str() , std::ios::binary );
        
        fin.read ( (char *) &id , sizeof(int) );
        
        // it is a valid cache file:
        if ( !fin.fail() && id == NOMAD::CACHE_FILE_ID ) {
            
            // display:
            if ( display )
                _out << std::endl
                << NOMAD::open_block ( "loading of \'" + file_name + "\'" );
            
            // read the points:
            if ( !read_points_from_cache_file ( fin , p_nb_bb_outputs , display ) ) {
                fin.close();
                return false;  // it is not a valid cache file
            }
            
            // lock the file:
            lock ( file_name );
            
            fin.close();
            
            if ( display )
                _out.close_block();
            
            return true;
        }
        
        // it is not a valid cache file:
        else {
            fin.close();
            return false;
        }
    }
    
    // the file does not exist:
    else {
        
        // display:
        if ( display )
            _out << std::endl << "creating cache file \'" << file_name << "\'" << std::endl;
        
        // create the file as a valid cache file:
        std::ofstream fout ( file_name.c_str() , std::ios::binary );
        
        if ( fout.fail() ) {
            fout.close();
            return false;
        }
        
        fout.write ( (char *) &NOMAD::CACHE_FILE_ID , sizeof ( NOMAD::CACHE_FILE_ID ) );
        fout.close();
        
        // lock:
        lock ( file_name );
    }
    
    return true;
}
inline void sysmonclose_power(){
	mutex_enter(MTX);
	KASSERT(is_locked(MTX));
	mutex_exit(MTX);
  assert(1);
}