void Adaboost(TrainData *data,int T){ InitWi(data); double temptheta=0.0,theta1=0.0; double error,beta; int p=0; //p=0 <=> '<' p=0 <=> '>' double min; //////////////left is positive & right is nagitive////////////// for(int i=0;i<T;i++){ //get theta first p=0; min=DBL_MAX;//////Be careful nomalization(data); for(int j=0;j<Data_Size_G;j++){ InitStatus(data); temptheta=data[j].property; for(int k=0;k<Data_Size_G;k++){ if((data[k].property<=temptheta)&&(data[k].label==0)) data[k].status=MISS; if((data[k].property>temptheta)&&(data[k].label)) data[k].status=MISS; } error=getError(data); if(error<=min&&error<0.5){ theta1=temptheta; min=error; } } //////////////right is positive & left is nagitive////////////// temptheta=0.0; double theta2=0.0; for(int j=0;j<Data_Size_G;j++){ InitStatus(data); temptheta=data[j].property; for(int k=0;k<Data_Size_G;k++){ if((data[k].property>=temptheta)&&(data[k].label==0)) data[k].status=MISS; if((data[k].property<temptheta)&&(data[k].label)) data[k].status=MISS; } error=getError(data); if(error<=min){ theta2=temptheta; min=error; p=1; } } ////////////////////////////////////////////////////////////////////////// InitStatus(data); double theta=p?theta2:theta1; if(p) for(int k=0;k<Data_Size_G;k++){ if((data[k].property>=theta)&&(data[k].label==0)) data[k].status=MISS; if((data[k].property<theta)&&(data[k].label)) data[k].status=MISS; } else for(int k=0;k<Data_Size_G;k++){ if((data[k].property<=theta)&&(data[k].label==0)) data[k].status=MISS; if((data[k].property>theta)&&(data[k].label)) data[k].status=MISS; } error=getError(data); beta=getBeta(error); updataWi(data, beta); if(p) printf("|>=| |Threshold:%9lf|error:%9lf |Alpha:%9lf|\n",theta,error,getAlpha(beta)); else printf("|<=| |Threshold:%9lf|error:%9lf |Alpha:%9lf|\n",theta,error,getAlpha(beta)); } }
void DanglingOnTemporaryChecker::check(const MatchFinder::MatchResult &Result) { /////////////////////////////////////// // Quick annotation conflict checker // /////////////////////////////////////// const char *ErrorInvalidRefQualified = "methods annotated with " "MOZ_NO_DANGLING_ON_TEMPORARIES " "cannot be && ref-qualified"; const char *ErrorInvalidPointer = "methods annotated with " "MOZ_NO_DANGLING_ON_TEMPORARIES must " "return a pointer"; if (auto InvalidRefQualified = Result.Nodes.getNodeAs<CXXMethodDecl>("invalidMethodRefQualified")) { diag(InvalidRefQualified->getLocation(), ErrorInvalidRefQualified, DiagnosticIDs::Error); return; } if (auto InvalidPointer = Result.Nodes.getNodeAs<CXXMethodDecl>("invalidMethodPointer")) { diag(InvalidPointer->getLocation(), ErrorInvalidPointer, DiagnosticIDs::Error); return; } ////////////////// // Main checker // ////////////////// const char *Error = "calling `%0` on a temporary, potentially allowing use " "after free of the raw pointer"; const char *EscapeStmtNote = "the raw pointer escapes the function scope here"; const ObjCMessageExpr *ParentObjCMessageExpr = Result.Nodes.getNodeAs<ObjCMessageExpr>("parentObjCMessageExpr"); // We don't care about cases in ObjC message expressions. if (ParentObjCMessageExpr) { return; } const CXXMemberCallExpr *MemberCall = Result.Nodes.getNodeAs<CXXMemberCallExpr>("memberCallExpr"); const CallExpr *ParentCallExpr = Result.Nodes.getNodeAs<CallExpr>("parentCallExpr"); const CXXConstructExpr *ParentConstructExpr = Result.Nodes.getNodeAs<CXXConstructExpr>("parentConstructExpr"); const CXXOperatorCallExpr *ParentOperatorCallExpr = Result.Nodes.getNodeAs<CXXOperatorCallExpr>("parentOperatorCallExpr"); const Expr *ParentCallArg = Result.Nodes.getNodeAs<Expr>("parentCallArg"); // Just in case. if (!MemberCall) { return; } // If we have a parent call, we check whether or not we escape the function // being called. if (ParentOperatorCallExpr || ParentCallExpr || ParentConstructExpr) { // Just in case. if (!ParentCallArg) { return; } // No default constructor so we can't construct it using if/else. auto FunctionEscapeData = ParentOperatorCallExpr ? escapesFunction(ParentCallArg, ParentOperatorCallExpr) : ParentCallExpr ? escapesFunction(ParentCallArg, ParentCallExpr) : escapesFunction(ParentCallArg, ParentConstructExpr); // If there was an error in the escapesFunction call. if (std::error_code ec = FunctionEscapeData.getError()) { // FIXME: For now we ignore the variadic case and just consider that the // argument doesn't escape the function. Same for the case where we can't // find the function declaration or if the function is builtin. if (static_cast<EscapesFunctionError>(ec.value()) == EscapesFunctionError::FunctionIsVariadic || static_cast<EscapesFunctionError>(ec.value()) == EscapesFunctionError::FunctionDeclNotFound || static_cast<EscapesFunctionError>(ec.value()) == EscapesFunctionError::FunctionIsBuiltin) { return; } // We emit the internal checker error and return. diag(MemberCall->getExprLoc(), std::string(ec.category().name()) + " error: " + ec.message(), DiagnosticIDs::Error); return; } // We deconstruct the function escape data. const Stmt *EscapeStmt; const Decl *EscapeDecl; std::tie(EscapeStmt, EscapeDecl) = *FunctionEscapeData; // If we didn't escape a parent function, we're done: we don't emit any // diagnostic. if (!EscapeStmt || !EscapeDecl) { return; } // We emit the error diagnostic indicating that we are calling the method // temporary. diag(MemberCall->getExprLoc(), Error, DiagnosticIDs::Error) << MemberCall->getMethodDecl()->getName() << MemberCall->getSourceRange(); // We indicate the escape statement. diag(EscapeStmt->getLocStart(), EscapeStmtNote, DiagnosticIDs::Note) << EscapeStmt->getSourceRange(); // We build the escape note along with its source range. StringRef EscapeDeclNote; SourceRange EscapeDeclRange; if (isa<ParmVarDecl>(EscapeDecl)) { EscapeDeclNote = "through the parameter declared here"; EscapeDeclRange = EscapeDecl->getSourceRange(); } else if (isa<VarDecl>(EscapeDecl)) { EscapeDeclNote = "through the variable declared here"; EscapeDeclRange = EscapeDecl->getSourceRange(); } else if (isa<FieldDecl>(EscapeDecl)) { EscapeDeclNote = "through the field declared here"; EscapeDeclRange = EscapeDecl->getSourceRange(); } else if (auto FuncDecl = dyn_cast<FunctionDecl>(EscapeDecl)) { EscapeDeclNote = "through the return value of the function declared here"; EscapeDeclRange = FuncDecl->getReturnTypeSourceRange(); } else { return; } // We emit the declaration note indicating through which decl the argument // escapes. diag(EscapeDecl->getLocation(), EscapeDeclNote, DiagnosticIDs::Note) << EscapeDeclRange; } else { // We emit the error diagnostic indicating that we are calling the method // temporary. diag(MemberCall->getExprLoc(), Error, DiagnosticIDs::Error) << MemberCall->getMethodDecl()->getName() << MemberCall->getSourceRange(); } }
/*! ** @brief Xsocket implemention of the standard getsockopt function. ** ** Xgetsockopt is used to retrieve the settings of the underlying Xsocket ** in the Click layer. It does not access the settings of the actual ** socket passed in which is used by the API to communicate with Click. ** ** Supported Options: ** \n XOPT_HLIM Retrieves the 'hop limit' element of the XIA header as an integer value ** \n XOPT_NEXT_PROTO Gets the next proto field in the XIA header ** ** @param sockfd The control socket ** @param optname The socket option to set (currently must be IP_TTL) ** @param optval A pointer to the value to retrieve ** @param optlen A pointer to the length of optval. On input this ** should be set to the length of the data passed in. If optlen is not ** large enough, Xgetsockopt will set it to the size needed and return ** with errno set to EINVAL. If larger than needed, Xgetsockopt will set ** it to the actual length of the returned data. ** ** @returns 0 on success ** @returns -1 on error with errno set ** @returns errno values: ** @returns EBADF: The socket descriptor is invalid ** @returns EINVAL: Either optval is null, or optlen is invalid, or optval is out of range ** @returns ENOPROTOOPT: the specified optname is not recognized */ int Xgetsockopt(int sockfd, int optname, void *optval, socklen_t *optlen) { char buf[MAXBUFLEN]; /* TODO: we may need to check the type of the socket at some point, but for now ** treat them all the same as far as options go. ** ** Should we add a validate socket function that takes the expected type? */ if (getSocketType(sockfd) == XSOCK_INVALID) { errno = EBADF; return -1; } if (!optval || !optlen) { errno = EINVAL; return -1; } xia::XSocketMsg xsm; xsm.set_type(xia::XGETSOCKOPT); xia::X_Getsockopt_Msg *msg = xsm.mutable_x_getsockopt(); msg->set_opt_type(optname); switch (optname) { case SO_ERROR: { if (*optlen < sizeof(int)) { *optlen = sizeof(int); errno = EINVAL; return -1; } *(int *)optval = getError(sockfd); break; } case XOPT_HLIM: { if (*optlen < sizeof(int)) { *optlen = sizeof(int); errno = EINVAL; return -1; } int flags = fcntl(sockfd, F_GETFL); fcntl(sockfd, F_SETFL, flags &= ~O_NONBLOCK); if (click_send(sockfd, &xsm) < 0) { LOGF("Error talking to Click: %s", strerror(errno)); fcntl(sockfd, F_SETFL, flags); return -1; } xia::XSocketMsg reply; if (click_reply(sockfd, xia::XGETSOCKOPT, buf, sizeof(buf)) < 0) { LOGF("Error getting status from Click: %s", strerror(errno)); fcntl(sockfd, F_SETFL, flags); return -1; } fcntl(sockfd, F_SETFL, flags); xsm.Clear(); xsm.ParseFromString(buf); xia::X_Getsockopt_Msg *msg = xsm.mutable_x_getsockopt(); int hlim = msg->int_opt(); *optlen = sizeof(int); *(int *)optval = hlim; break; } case XOPT_NEXT_PROTO: { if (*optlen < sizeof(int)) { *optlen = sizeof(int); errno = EINVAL; return -1; } int flags = fcntl(sockfd, F_GETFL); fcntl(sockfd, F_SETFL, flags &= ~O_NONBLOCK); if (click_send(sockfd, &xsm) < 0) { fcntl(sockfd, F_SETFL, flags); LOGF("Error talking to Click: %s", strerror(errno)); return -1; } xia::XSocketMsg reply; if (click_reply(sockfd, xia::XGETSOCKOPT, buf, sizeof(buf)) < 0) { fcntl(sockfd, F_SETFL, flags); LOGF("Error getting status from Click: %s", strerror(errno)); return -1; } fcntl(sockfd, F_SETFL, flags); xsm.Clear(); xsm.ParseFromString(buf); xia::X_Getsockopt_Msg *msg = xsm.mutable_x_getsockopt(); int nxt = msg->int_opt(); *optlen = sizeof(int); *(int *)optval = nxt; break; } default: errno = ENOPROTOOPT; return -1; } return 0; }
//##ModelId=424426D6039B CycleSHMIntHashIndex::CycleSHMIntHashIndex(ABMException &oExp,char *shmname) : SHMAccess(oExp, shmname), m_piHashValue(0), m_piTotal(0), m_piUsed(0), m_poHash(0) { if (m_poSHM&&!getError()) open (); }
void TreeSocket::OnError(BufferedSocketError e) { ServerInstance->SNO->WriteGlobalSno('l', "Connection to '\002%s\002' failed with error: %s", linkID.c_str(), getError().c_str()); LinkState = DYING; }
bool StochasticSupervisor::trainFor(NeuralNetwork &neuralNetwork, const int count) { emit started(count); qreal bestError = 1e100; NeuralNetwork networkBackup; RandomSupervisor rnd(-5, 5); rnd.train(neuralNetwork); NeuralNetwork bestNetwork = neuralNetwork; emit iterationInfo(0, count); emit targetErrorInfo(EPS, bestError, bestError); for(int e = 1; e < count; ++e) { const qreal temperature = MAX_TEMPERATURE / (1 + e); const qreal temperature2 = temperature * temperature; const qreal oldError = getError(neuralNetwork, trainingSet()); networkBackup = neuralNetwork; for (NeuralLayer &layer: neuralNetwork) for (Neuron &neuron: layer) for (int i = 0; i < neuron.weightNumber(); ++i) neuron.setWeight(i, neuron.weight(i) + randReal(-0.25, 0.25)); const qreal error = getError(neuralNetwork, trainingSet()); { // info if (e % 100 == 0) { qDebug() << 100. * e / count << error << bestError; // FIXME DEBUG emit iterationInfo(e, count); emit targetErrorInfo(EPS, error, bestError); QCoreApplication::processEvents(); if (checkAborted()) { emit finished(false); qDebug() << "ABORTED"; return false; } } } if (error > oldError) { const qreal errorDiff = error - oldError; const qreal errorDiff2 = errorDiff * errorDiff; const qreal P = temperature2 / (temperature2 + errorDiff2); const qreal random = randReal(0, 1); if (random > P) neuralNetwork.swap(networkBackup); } else { if (error < bestError) { bestNetwork = neuralNetwork; bestError = error; } } if (error < EPS) { emit iterationInfo(e, count); emit targetErrorInfo(EPS, error, bestError); emit finished(true); qDebug() << "SUCCESS"; return true; } } neuralNetwork.swap(bestNetwork); emit iterationInfo(count, count); emit targetErrorInfo(EPS, bestError, bestError); emit finished(false); qDebug() << "FAILED"; return false; }
static int8_t module(void *state, Message *msg) { app_state_t *s = (app_state_t *) state; MsgParam *p = (MsgParam*)(msg->data); /** * Switch to the correct message handler */ switch (msg->type){ case MSG_INIT: { DEBUG("RATS: node %d initializing\n", ker_id()); s->pid = msg->did; s->ts_list = NULL; s->ts_packet.type = NORMAL_PACKET; //Notify neighbors that RATS is starting (in case node rebooted while it was //synchronizing with another node post_net(s->pid, s->pid, MSG_INVALIDATE_ENTRY, 0, NULL, 0, BCAST_ADDRESS); return SOS_OK; } case MSG_RATS_CLIENT_START: { MsgParam *p = (MsgParam *)msg->data; DEBUG("RATS: Received MSG_RATS_CLIENT_START for node %d\n", p->word); uint8_t request_status = add_request(s, p->word, p->byte); //If a new request was created, then send packet to parent if(request_status != NO_REQUEST_CREATED) { DEBUG("RATS: Transmitting request to node %d\n", p->word); LED_DBG(LED_RED_TOGGLE); //If the current node is the parent of the target node, then the target node will //reply by informing the parent, who will add the target to its list of children. post_net(s->pid, s->pid, MSG_RATS_SERVER_START, 0, NULL, 0, p->word); } else { //Request already exists DEBUG("RATS: Request already exists\n"); } //If this was the first request that was created, we need to start the panic timer if(request_status == CREATED_FIRST_REQUEST) { DEBUG("RATS: PANIC_TIMER started\n"); #ifdef USE_PANIC_PACKETS sys_timer_start(PANIC_TIMER, MIN_SAMPLING_PERIOD*1024, TIMER_REPEAT); #endif //USE_PANIC_PACKETS } return SOS_OK; } case MSG_RATS_SERVER_START: { timesync_t * temp_ts_ptr = get_timesync_ptr(s, msg->saddr); DEBUG("RATS: Received request from node %d\n", msg->saddr); if(temp_ts_ptr == NULL) { DEBUG("RATS: Starting timesync with node %d\n", msg->saddr); LED_DBG(LED_RED_TOGGLE); //If request is coming from node, with whom the node is not synchronizing, then //synchronization is starting sys_timer_stop(TRANSMIT_TIMER); sys_timer_stop(VALIDATION_TIMER); s->ts_packet.transmission_period = INITIAL_TRANSMISSION_PERIOD; s->ts_packet.min_period_node_id = msg->saddr; s->transmit_timer_counter = 1; //s->ts_packet.transmission_period/INITIAL_TRANSMISSION_PERIOD; s->validation_timer_counter = 5; //s->transmit_timer_counter + 4; s->validation_timer_retransmissions = TOTAL_VALIDATION_RETRANSMISSIONS; sys_timer_start(TRANSMIT_TIMER, MIN_SAMPLING_PERIOD*1024, TIMER_REPEAT); sys_timer_start(VALIDATION_TIMER, MIN_SAMPLING_PERIOD*1024, TIMER_REPEAT); } return SOS_OK; } case MSG_RATS_GET_TIME: { //If the module passed a NULL pointer or if the data size is wrong, then discard if( (msg->data == NULL) #ifndef PC_PLATFORM || (msg->len != sizeof(rats_t) ) #endif //PC_PLATFORM ) { DEBUG("RATS: Invalid data received in MSG_RATS_GET_TIME\n"); break; } rats_t * rats_ptr = (rats_t *)sys_msg_take_data(msg); DEBUG("RATS: Received MSG_RATS_GET_TIME (mod_id=%d node=%d)\n", rats_ptr->mod_id, msg->saddr); if(rats_ptr->source_node_id == ker_id()) { timesync_t * temp_ts_ptr = get_timesync_ptr(s, rats_ptr->target_node_id); if(temp_ts_ptr == NULL) { DEBUG("RATS: Target node %d is not time synced\n", rats_ptr->target_node_id); sys_free(rats_ptr); break; } else { DEBUG("RATS: Calculating time for target node %d locally\n", rats_ptr->target_node_id); if(temp_ts_ptr->packet_count < BUFFER_SIZE) // learning state { rats_ptr->time_at_target_node = 0; rats_ptr->error = 0; } else { rats_ptr->time_at_target_node = convert_from_mine_to_parent_time(rats_ptr->time_at_source_node, rats_ptr->target_node_id); rats_ptr->error = getError(&temp_ts_ptr->timestamps[0], &temp_ts_ptr->my_time[0], BUFFER_SIZE, temp_ts_ptr->window_size, BUFFER_SIZE - temp_ts_ptr->window_size, &temp_ts_ptr->a, &temp_ts_ptr->b, temp_ts_ptr->sampling_period, FALSE); } } } else if (rats_ptr->target_node_id == ker_id()) { timesync_t * temp_ts_ptr = get_timesync_ptr(s, rats_ptr->source_node_id); if(temp_ts_ptr == NULL) { DEBUG("RATS: Source node %d is not time synced\n", rats_ptr->source_node_id); sys_free(rats_ptr); break; } else { DEBUG("RATS: Calculating time for source node %d locally\n", rats_ptr->source_node_id); if(temp_ts_ptr->packet_count < BUFFER_SIZE) // learning state { rats_ptr->time_at_target_node = 0; rats_ptr->error = 0; } else { rats_ptr->time_at_target_node = convert_from_parent_to_my_time(rats_ptr->time_at_source_node, rats_ptr->source_node_id); rats_ptr->error = getError(&temp_ts_ptr->timestamps[0], &temp_ts_ptr->my_time[0], BUFFER_SIZE, temp_ts_ptr->window_size, BUFFER_SIZE - temp_ts_ptr->window_size, &temp_ts_ptr->a, &temp_ts_ptr->b, temp_ts_ptr->sampling_period, TRUE); } } } else { DEBUG("RATS: Invalid request (source = %d, target - %d)\n", rats_ptr->source_node_id, rats_ptr->target_node_id); sys_free(rats_ptr); break; } DEBUG("RATS: Sending reply to module %d\n", rats_ptr->mod_id); post_long(rats_ptr->mod_id, s->pid, rats_ptr->msg_type, sizeof(rats_t), rats_ptr, SOS_MSG_RELEASE); break; } case MSG_RATS_CLIENT_STOP: { MsgParam *p = (MsgParam *)msg->data; uint16_t node_id = p->word; //First we need to remove node from list of parents /* Select node at head of list */ timesync_t * ts_list_ptr = s->ts_list; timesync_t * ts_delete_list_ptr; timesync_t * ts_previous_list_ptr = s->ts_list; /* Loop until we've reached the end of the list */ while( ts_list_ptr != NULL ) { if(ts_list_ptr->node_id == node_id) { if(--ts_list_ptr->ref_counter > 0) return SOS_OK; DEBUG("RATS: Removing node %d from list of parents. Sending MSG_RATS_SERVER_STOP.\n", node_id); post_net(s->pid, s->pid, MSG_RATS_SERVER_STOP, 0, NULL, 0, node_id); /* Found the item to be deleted, re-link the list around it */ if( ts_list_ptr == s->ts_list ) /* We're deleting the head */ s->ts_list = ts_list_ptr->next; else ts_previous_list_ptr->next = ts_list_ptr->next; ts_delete_list_ptr = ts_list_ptr; ts_list_ptr = ts_list_ptr->next; /* Free the node */ sys_free( ts_delete_list_ptr ); //If the parent list is empty, then we're stopping the panic timer if(s->ts_list == NULL) { DEBUG("RATS: Parent list is empty. Stopping panic timer\n"); #ifdef USE_PANIC_PACKETS sys_timer_stop(PANIC_TIMER); #endif //USE_PANIC_PACKETS } return SOS_OK; } ts_previous_list_ptr = ts_list_ptr; ts_list_ptr = ts_list_ptr->next; } DEBUG("RATS: Requested parent %d was not found\n", node_id); break; } case MSG_RATS_SERVER_STOP: { DEBUG("RATS: Received MSG_RATS_SERVER_STOP from %d\n", msg->saddr); //If node has minimum period, then go to validation protocol if(msg->saddr == s->ts_packet.min_period_node_id) { DEBUG("RATS: Going to validation protocol\n"); s->validation_timer_counter = 1; s->validation_timer_retransmissions = BROADCAST_VALIDATION_RETRANSMISSIONS; s->validation_node_id = ker_id(); } break; } case MSG_TIMER_TIMEOUT: { switch(p->byte) { case TRANSMIT_TIMER: { if( (--(s->transmit_timer_counter)) == 0) { DEBUG("RATS: Broadcasting MSG_TIMESTAMP packet\n"); LED_DBG(LED_GREEN_TOGGLE); post_net(s->pid, s->pid, MSG_TIMESTAMP, sizeof(ts_packet_t), &s->ts_packet, 0, BCAST_ADDRESS); #ifdef UART_DEBUG post_uart(s->pid, s->pid, UART_TIMESTAMP, sizeof(ts_packet_t), &s->ts_packet, 0, BCAST_ADDRESS); #endif //UART_DEBUG s->transmit_timer_counter = (uint16_t)(s->ts_packet.transmission_period / MIN_SAMPLING_PERIOD); } break; } case VALIDATION_TIMER: { if( (--(s->validation_timer_counter)) == 0) { s->validation_timer_counter = 1; //Send up to MSG_PERIOD_REQUEST packets (UNICAST_VALIDATION_RETRANSMISSIONS times) to node with minimum period. //If the node doesn't respond until then, then broadcast BROADCAST_VALIDATION_RETRANSMISSIONS times //After the transmitting BROADCAST_VALIDATION_RETRANSMISSIONS packets, use the minimum period that //was sent during that interval if( s->validation_timer_retransmissions > BROADCAST_VALIDATION_RETRANSMISSIONS ) { --s->validation_timer_retransmissions; DEBUG("RATS: Transmitting MSG_PERIOD_REQUEST (retries left = %d) to node %d\n", s->validation_timer_retransmissions, s->ts_packet.min_period_node_id); post_net(s->pid, s->pid, MSG_PERIOD_REQUEST, 0, NULL, 0, s->ts_packet.min_period_node_id); #ifdef UART_DEBUG post_uart(s->pid, s->pid, UART_PERIOD_REQUEST, 0, NULL, 0, s->ts_packet.min_period_node_id); #endif //UART_DEBUG } else if( s->validation_timer_retransmissions > 0) { --s->validation_timer_retransmissions; DEBUG("RATS: Broadcasting MSG_PERIOD_REQUEST (retries left = %d)\n", s->validation_timer_retransmissions); //Invalidate node with minimum period s->validation_node_id = ker_id(); post_net(s->pid, s->pid, MSG_PERIOD_REQUEST, 0, NULL, 0, BCAST_ADDRESS); #ifdef UART_DEBUG post_uart(s->pid, s->pid, UART_PERIOD_REQUEST, 0, NULL, 0, BCAST_ADDRESS); #endif //UART_DEBUG } else //s->validation_timer_retransmissions == 0 { sys_timer_stop(TRANSMIT_TIMER); sys_timer_stop(VALIDATION_TIMER); //Restart normal procedure only if there was a reply if(ker_id() != s->validation_node_id) { DEBUG("RATS: Setting node %d as the one with min period (%d)\n", s->validation_node_id, s->validation_period); s->ts_packet.min_period_node_id = s->validation_node_id; s->ts_packet.transmission_period = s->validation_period; s->transmit_timer_counter = s->ts_packet.transmission_period/INITIAL_TRANSMISSION_PERIOD; s->validation_timer_counter = s->transmit_timer_counter + 4; s->validation_timer_retransmissions = TOTAL_VALIDATION_RETRANSMISSIONS; sys_timer_start(TRANSMIT_TIMER, MIN_SAMPLING_PERIOD*1024, TIMER_REPEAT); sys_timer_start(VALIDATION_TIMER, MIN_SAMPLING_PERIOD*1024, TIMER_REPEAT); } else { DEBUG("RATS: Validation timer expired, without receiving any packets\n"); sys_timer_stop(TRANSMIT_TIMER); sys_timer_stop(VALIDATION_TIMER); } } } break; } case PANIC_TIMER: { //There is a fixed number of retransmissions. If the corresponding counter //reaches zero, then the child is removed from the list /* Select node at head of list */ timesync_t * ts_list_ptr = s->ts_list; timesync_t * ts_delete_list_ptr; timesync_t * ts_previous_list_ptr = s->ts_list; /* Loop until we've reached the end of the list */ while( ts_list_ptr != NULL ) { if(--ts_list_ptr->panic_timer_counter == 0) { if(ts_list_ptr->panic_timer_retransmissions > 0) { //Transmit the packet --ts_list_ptr->panic_timer_retransmissions; DEBUG("RATS: Sending panic packet to node %d (retries=%d)\n", ts_list_ptr->node_id, ts_list_ptr->panic_timer_retransmissions); post_net(s->pid, s->pid, MSG_PANIC, 0, NULL, 0, ts_list_ptr->node_id); //The retransmission period should be INITIAL_TRANSMISSION_PERIOD ts_list_ptr->panic_timer_counter = 1; } else { DEBUG("RATS: Removing node %d from list of parents\n", ts_list_ptr->node_id); /* Found the item to be deleted, re-link the list around it */ if( ts_list_ptr == s->ts_list ) /* We're deleting the head */ s->ts_list = ts_list_ptr->next; else ts_previous_list_ptr->next = ts_list_ptr->next; ts_delete_list_ptr = ts_list_ptr; ts_list_ptr = ts_list_ptr->next; /* Free the node */ sys_free( ts_delete_list_ptr ); continue; } } ts_previous_list_ptr = ts_list_ptr; ts_list_ptr = ts_list_ptr->next; } //If the parent list is empty, then we're stopping the panic timer if(s->ts_list == NULL) { DEBUG("RATS: Parent list is empty. Stopping panic timer\n"); #ifdef USE_PANIC_PACKETS sys_timer_stop(PANIC_TIMER); #endif //USE_PANIC_PACKETS } break; } default: break; } return SOS_OK; } case MSG_PERIOD_CHANGE: { uint16_t temp_transmission_period; DEBUG("RATS: Received packet for period change from %d\n", msg->saddr); LED_DBG(LED_YELLOW_TOGGLE); if((msg->data == NULL) || (msg->len != sizeof(uint16_t)) ) { DEBUG("RATS: Invalid parameters in MSG_PERIOD_CHANGE\n"); break; } temp_transmission_period = (* (uint16_t*)(msg->data)); //Change period if: //a)received period is smaller than period in use //b)node that sent period is the one that has the current smallest period //c)I am currently using myself as the node with the smallest period (used in the beginning and in transitive modes) if((temp_transmission_period < s->ts_packet.transmission_period) || (s->ts_packet.min_period_node_id == msg->saddr) || (s->ts_packet.min_period_node_id == ker_id()) ) { DEBUG("RATS: Changing period (new_period=%d new_node=%d). Sending to UART\n", temp_transmission_period, msg->saddr); sys_timer_stop(TRANSMIT_TIMER); sys_timer_stop(VALIDATION_TIMER); #ifdef UART_DEBUG period_packet_t * period_packet_ptr = sys_malloc(sizeof(period_packet_t)); period_packet_ptr->saddr = msg->saddr; period_packet_ptr->old_period = s->ts_packet.transmission_period; period_packet_ptr->new_period = temp_transmission_period; post_uart(s->pid, s->pid, UART_PERIOD_CHANGE, sizeof(period_packet_t), period_packet_ptr, SOS_MSG_RELEASE, UART_ADDRESS); #endif //UART_DEBUG s->ts_packet.transmission_period = temp_transmission_period; s->ts_packet.min_period_node_id = msg->saddr; s->transmit_timer_counter = (uint16_t)(s->ts_packet.transmission_period / MIN_SAMPLING_PERIOD); s->validation_timer_counter = s->transmit_timer_counter + 4; s->validation_timer_retransmissions = TOTAL_VALIDATION_RETRANSMISSIONS; sys_timer_start(TRANSMIT_TIMER, INITIAL_TRANSMISSION_PERIOD*1024, TIMER_REPEAT); sys_timer_start(VALIDATION_TIMER, INITIAL_TRANSMISSION_PERIOD*1024, TIMER_REPEAT); } return SOS_OK; } case MSG_TIMESTAMP: { ts_packet_t *ts_packet_ptr = (ts_packet_t *)msg->data; DEBUG("RATS: MSG_TIMESTAMP with type = %d\n", ts_packet_ptr->type); if(ts_packet_ptr->type == NORMAL_PACKET) { DEBUG("RATS: Receiving timestamp data from node %d\n", msg->saddr); if( add_values(s, msg) == TRUE) { LED_DBG(LED_GREEN_TOGGLE); DEBUG("RATS: Accessed internal structure\n"); } else { DEBUG("RATS: Discarding MSG_TIMESTAMP from node %d\n", msg->saddr); } } else // TEST_PACKET { if(ker_id() == ROOT_NODE) { DEBUG("RATS: Receiving test data from node %d. Sending to UART\n", msg->saddr); #ifdef UART_DEBUG ext_packet_t * ext_packet_ptr = (ext_packet_t *)msg->data; debug_packet_t * debug_packet_ptr = (debug_packet_t *)sys_malloc(sizeof(debug_packet_t)); debug_packet_ptr->time[0] = ticks_to_msec_float(ext_packet_ptr->time[0]); debug_packet_ptr->time[1] = ticks_to_msec_float(ext_packet_ptr->time[1]); debug_packet_ptr->node_id = ker_id(); debug_packet_ptr->int_parent_time = ext_packet_ptr->time[1]; post_uart(s->pid, s->pid, UART_FORWARD_EXT, sizeof(debug_packet_t), debug_packet_ptr, SOS_MSG_RELEASE, UART_ADDRESS); #endif //UART_DEBUG } else { DEBUG("RATS: Receiving test data from node %d. Sending to parent\n", msg->saddr); #ifdef UART_DEBUG ext_packet_t * ext_packet_ptr = (ext_packet_t *)msg->data; uint32_t parent_time = convert_from_mine_to_parent_time(ext_packet_ptr->time[1], ROOT_NODE); //Break if the parent is not found in the timestamping list if(parent_time == 0) { break; } debug_packet_t * debug_packet_ptr = (debug_packet_t *)sys_malloc(sizeof(debug_packet_t)); debug_packet_ptr->time[0] = ticks_to_msec_float(ext_packet_ptr->time[0]); debug_packet_ptr->time[1] = ticks_to_msec_float(parent_time); debug_packet_ptr->int_parent_time = parent_time; debug_packet_ptr->node_id = ker_id(); post_uart(s->pid, s->pid, UART_FORWARD_EXT, sizeof(debug_packet_t), debug_packet_ptr, SOS_MSG_RELEASE, UART_ADDRESS); #endif //UART_DEBUG } } break; } case MSG_PERIOD_REQUEST: { DEBUG("RATS: Received MSG_PERIOD_REQUEST packet from node %d\n", msg->saddr); timesync_t * temp_ts_ptr = get_timesync_ptr(s, msg->saddr); if(temp_ts_ptr == NULL) { DEBUG("RATS: Discarding MSG_PERIOD_REQUEST\n"); break; } uint16_t *sampling_period = (uint16_t *)sys_malloc(sizeof(uint16_t)); if(sampling_period != NULL) { *sampling_period = temp_ts_ptr->sampling_period; DEBUG("RATS: Sending MSG_PERIOD_REPLY packet (period=%d) to node %d\n", *sampling_period, msg->saddr); post_net(s->pid, s->pid, MSG_PERIOD_REPLY, sizeof(uint16_t), sampling_period, SOS_MSG_RELEASE, msg->saddr); } break; } case MSG_PERIOD_REPLY: { uint16_t transmission_period; DEBUG("RATS: Received MSG_PERIOD_REPLY packet from node %d\n", msg->saddr); memcpy(&transmission_period, &msg->data[0], sizeof(transmission_period)); s->validation_timer_counter = s->transmit_timer_counter + 4; s->validation_timer_retransmissions = TOTAL_VALIDATION_RETRANSMISSIONS; if((transmission_period < s->validation_period) || (s->validation_node_id == ker_id() ) ) { DEBUG("RATS: Changing VALIDATION period (new_period=%d new_node=%d)\n", transmission_period, msg->saddr); s->validation_period = transmission_period; s->validation_node_id = msg->saddr; } break; } case MSG_PANIC: { //Transmit MSG_TIMESTAMP, restart timer, recalculate value for transmit_timer_counter sys_timer_stop(TRANSMIT_TIMER); sys_timer_stop(VALIDATION_TIMER); #ifdef UART_DEBUG uint16_t *data = (uint16_t *)sys_malloc(sizeof(uint16_t)); *data = msg->saddr; post_uart(s->pid, s->pid, UART_PANIC, sizeof(uint16_t), data, SOS_MSG_RELEASE, UART_ADDRESS); #endif //UART_DEBUG post_net(s->pid, s->pid, MSG_TIMESTAMP, sizeof(ts_packet_t), &s->ts_packet, 0, BCAST_ADDRESS); s->transmit_timer_counter = (uint16_t)(s->ts_packet.transmission_period / MIN_SAMPLING_PERIOD); s->validation_timer_counter = s->transmit_timer_counter + 4; s->validation_timer_retransmissions = TOTAL_VALIDATION_RETRANSMISSIONS; sys_timer_start(TRANSMIT_TIMER, INITIAL_TRANSMISSION_PERIOD*1024, TIMER_REPEAT); sys_timer_start(VALIDATION_TIMER, INITIAL_TRANSMISSION_PERIOD*1024, TIMER_REPEAT); break; } case MSG_INVALIDATE_ENTRY: { DEBUG("RATS: Received invalidation message from node %d\n", msg->saddr); timesync_t * temp_ts_ptr = get_timesync_ptr(s, msg->saddr); if(temp_ts_ptr == NULL) { DEBUG("RATS: Discarding MSG_INVALIDATE_ENTRY\n"); break; } DEBUG("RATS: Invalidation entry for node %d\n", msg->saddr); temp_ts_ptr->packet_count = 0; temp_ts_ptr->a = 0; temp_ts_ptr->b = 0; temp_ts_ptr->sampling_period = INITIAL_TRANSMISSION_PERIOD; temp_ts_ptr->window_size = (uint8_t)BUFFER_SIZE; temp_ts_ptr->panic_timer_counter = 5; //(s->ts_list->sampling_period / INITIAL_TRANSMISSION_PERIOD) + 4; temp_ts_ptr->panic_timer_retransmissions = PANIC_TIMER_RETRANSMISSIONS; memset(temp_ts_ptr->timestamps, 0, BUFFER_SIZE*sizeof(uint32_t)); memset(temp_ts_ptr->my_time, 0, BUFFER_SIZE*sizeof(uint32_t)); //Notify node to start procedure from beginning post_net(s->pid, s->pid, MSG_RATS_SERVER_START, 0, NULL, 0, msg->saddr); break; } case MSG_FINAL: { sys_timer_stop(TRANSMIT_TIMER); sys_timer_stop(VALIDATION_TIMER); #ifdef USE_PANIC_PACKETS sys_timer_stop(PANIC_TIMER); #endif //USE_PANIC_PACKETS return SOS_OK; } default: return -EINVAL; } /** * Return SOS_OK for those handlers that have successfully been handled. */ return SOS_OK; }
int SQ_Device_Write (int did, u_char *writebuf, int nbytes) { int ret; ret = write ( did, writebuf, nbytes ); if ( ret == -1 ) return ( getError ( SYS, errno ) ); return ( ret ); }
int SQ_Device_Read (int did, u_char *readbuf, int tout) { int ret; ret = isatty ( did ); if ( ret == 1 ) return ( SQ_Device_Read_TTY ( did, readbuf, tout ) ); else return ( getError ( INT, ERRZ24 ) ); }
void Server::tick(NetworkEvent* event) { event->eventCode = eNone; // try to initialize if (serverSock_ == INVALID_SOCKET && clientSock_ == INVALID_SOCKET) { serverSock_ = socket(PF_INET, SOCK_STREAM, 0); if (serverSock_ == INVALID_SOCKET) { cleanup(); event->eventCode = eCreateSocketError; return; } int yes = 1; if (setsockopt(serverSock_, SOL_SOCKET, SO_REUSEADDR, (const char*)&yes, sizeof(int)) == -1) { cleanup(); event->eventCode = eSetReuseAddrError; return; } sockaddr_in ai_addr; memset(&ai_addr, 0, sizeof(ai_addr)); ai_addr.sin_family = AF_INET; ai_addr.sin_addr.s_addr = htonl(INADDR_ANY); ai_addr.sin_port = htons(port_); if (bind(serverSock_, (sockaddr *)&ai_addr, sizeof(ai_addr)) == -1) { cleanup(); event->eventCode = eBindError; return; } if (listen(serverSock_, BACKLOG) == -1) { cleanup(); event->eventCode = eListenError; return; } setNonBlocking(serverSock_, true); } // try to accept if (serverSock_ != INVALID_SOCKET && clientSock_ == INVALID_SOCKET) { sockaddr_in client_addr; socklen_t sizeof_client_addr = sizeof(client_addr); clientSock_ = accept(serverSock_, (sockaddr *)&client_addr, &sizeof_client_addr); if (clientSock_ == INVALID_SOCKET) { if (getError() == EWOULDBLOCK2) { // no connections are present to be accepted, everything is ok, just return return; } else { // there is another error cleanup(); event->eventCode = eAcceptError; return; } } setNonBlocking(clientSock_, true); // we close the listening serverSock_ in order to prevent more incoming connections on the same port setNonBlocking(serverSock_, false); closesocket(serverSock_); serverSock_ = INVALID_SOCKET; event->eventCode = eOtherSideConnected; return; } // send and recv if (clientSock_ != INVALID_SOCKET) { tickRecv(event); if (eFirstError < event->eventCode && event->eventCode < eLastError) { cleanup(); return; } if (event->eventCode != eNone) return; tickSend(event); if (eFirstError < event->eventCode && event->eventCode < eLastError) { cleanup(); return; } } }
void Client::tick(NetworkEvent* event) { event->eventCode = eNone; if (clientSock_ == INVALID_SOCKET) { // create socket clientSock_ = socket(PF_INET, SOCK_STREAM, 0); if (clientSock_ == INVALID_SOCKET) { cleanup(); event->eventCode = eCreateSocketError; return; } setNonBlocking(clientSock_, true); connecting_ = true; } if (connecting_ == true) { // connect sockaddr_in ai_addr; ai_addr.sin_family = AF_INET; ai_addr.sin_addr.s_addr = inet_addr(ip_.c_str()); ai_addr.sin_port = htons(port_); int c = connect(clientSock_, (struct sockaddr*)&ai_addr, sizeof(ai_addr)); if (c == 0 || getError() == EISCONN2) { connecting_ = false; event->eventCode = eOtherSideConnected; return; } else { if (getError() == EWOULDBLOCK2 || getError() == EALREADY2 || getError() == EINPROGRESS2 || getError() == EINVAL2) { // still trying to connect return; } else { cleanup(); event->eventCode = eConnectError; return; } } } // send and recv if (clientSock_ != INVALID_SOCKET) { tickRecv(event); if (eFirstError < event->eventCode && event->eventCode < eLastError) { cleanup(); return; } if (event->eventCode != eNone) return; tickSend(event); if (eFirstError < event->eventCode && event->eventCode < eLastError) { cleanup(); return; } } }
void NetworkBase::tickRecv(NetworkEvent* event) { const unsigned int headerSize = sizeof(unsigned int) * 3; if (receiveData_ == 0) { // first allocate data for header receiveData_ = (char*)malloc(headerSize); receiveCurrent_ = 0; } if (receiveCurrent_ < headerSize) { // header has not arrived yet, try to get the header unsigned int bytesToReceive = headerSize - receiveCurrent_; int bytes = recv(clientSock_, receiveData_ + receiveCurrent_, bytesToReceive, 0); if (bytes == 0) { // other side closed the connection gracefully cleanup(); event->eventCode = eOtherSideClosedConnection; return; } else if (bytes == -1) { if (getError() == EWOULDBLOCK2) { // nothing in receive queue, nothing to worry about, just return } else { // there is another error cleanup(); event->eventCode = eOtherSideClosedConnection; // most probably other side closed the connection ungracefully. return; } } else if (bytes > 0) { dataReceived_ += bytes; receiveCurrent_ += bytes; // we grab the header, reallocate to full size if (receiveCurrent_ == headerSize) { unsigned int* header = (unsigned int*)receiveData_; receiveSize_ = header[0]; receiveId_ = header[1]; receiveType_ = header[2]; receiveData_ = (char*)realloc(receiveData_, receiveSize_); } } } else { // continue to recv data unsigned int bytesToReceive = receiveSize_ - receiveCurrent_; int bytes = recv(clientSock_, receiveData_ + receiveCurrent_, bytesToReceive, 0); if (bytes == 0) { // other side closed the connection gracefully cleanup(); event->eventCode = eOtherSideClosedConnection; return; } else if (bytes == -1) { if (getError() == EWOULDBLOCK2) { // nothing in receive queue, nothing to worry about, just return } else { // there is another error cleanup(); event->eventCode = eOtherSideClosedConnection; // most probably other side closed the connection ungracefully return; } } else if (bytes > 0) { dataReceived_ += bytes; receiveCurrent_ += bytes; if (receiveCurrent_ == receiveSize_) { // we finished receiving the data if (receiveType_ == 0) { event->eventCode = eDataReceived; event->data.resize(receiveSize_ - headerSize); memcpy(&event->data[0], receiveData_ + headerSize, receiveSize_ - headerSize); sendAck(receiveId_); } else if (receiveType_ == 1) { event->eventCode = eDataSent; event->id = *(unsigned int*)(receiveData_ + headerSize); } free(receiveData_); receiveData_ = 0; } } } }
static PyObject * oXformProperty_setValues(PyObject * self, PyObject * args) { ALEMBIC_TRY_STATEMENT oXformProperty * prop = (oXformProperty*)self; if(prop->mArchive == NULL) { PyErr_SetString(getError(), "Archive already closed!"); return NULL; } PyObject * tuple = NULL; if(!PyArg_ParseTuple(args, "O", &tuple)) { PyErr_SetString(getError(), "No sample tuple specified!"); return NULL; } if(!PyTuple_Check(tuple) && !PyList_Check(tuple)) { PyErr_SetString(getError(), "Sample tuple argument is not a tuple!"); return NULL; } /*if(prop->mMembers->mXformSchema.getNumSamples() >= prop->mMaxNbSamples) { PyErr_SetString(getError(), "Already stored the maximum number of samples!"); return NULL; }*/ size_t nbItems = 0; if(PyTuple_Check(tuple)) nbItems = PyTuple_Size(tuple); else nbItems = PyList_Size(tuple); if(nbItems != 16) { PyErr_SetString(getError(), "Sample tuple should contain 16 items!"); return NULL; } std::vector<double> values(16); for(size_t i=0;i<16;i++) { PyObject * item = NULL; if(PyTuple_Check(tuple)) item = PyTuple_GetItem(tuple,i); else item = PyList_GetItem(tuple,i); if(!PyArg_Parse(item,"d",&values[i])) { PyErr_SetString(getError(), "Some item of the sample tuple is not a floating point number!"); return NULL; } } Imath::M44d matrix(values[0],values[1],values[2],values[3],values[4],values[5],values[6],values[7], values[8],values[9],values[10],values[11],values[12],values[13],values[14],values[15]); prop->mMembers->mSample.setInheritsXforms(true); prop->mMembers->mSample.setMatrix(matrix); prop->mMembers->mXformSchema.set(prop->mMembers->mSample); return Py_BuildValue("I",prop->mMembers->mXformSchema.getNumSamples()); ALEMBIC_PYOBJECT_CATCH_STATEMENT }
int HolisticFeatureExtractor::resampleTrace(const LTKTrace& inTrace,int resamplePoints, LTKTrace& outTrace) { LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entered PCAShapeRecognizer::resampleTrace" << endl; int pointIndex; // a variable to loop over the points of a trace int currentPointIndex =0; // index of the current point float xSum = 0.0f; // sum of the x coordinate values float ySum = 0.0f; // sum of the y coordinate values int numTracePoints; // number of points in a trace int ptIndex = 0; // index of point in a trace float x; // an x coord value float y; // an y coord value float xDiff; // differenc in x direction float yDiff; // diference in y direction float xTemp; // temp x storage float yTemp; // temp y storage float unitLength = 0; // estimated length of each segment after resampling float pointDistance; float balanceDistance = 0; // distance between the last resampled point and // the next raw sample point float measuredDistance; float m1,m2; floatVector xVec; floatVector resampledXVec; floatVector yVec; floatVector resampledYVec; floatVector distanceVec; numTracePoints = inTrace.getNumberOfPoints(); if(numTracePoints == 0) { LOG( LTKLogger::LTK_LOGLEVEL_ERR) << string(getError(EEMPTY_TRACE)) << endl; LTKReturnError(EEMPTY_TRACE); } //xVec = inTrace.getChannelValues(xChannelstr); xVec = inTrace.getChannelValues("X"); //yVec = inTrace.getChannelValues(yChannelstr); yVec = inTrace.getChannelValues("Y"); LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << "resamplePoints = " , resamplePoints << endl; if(resamplePoints < 1) { resamplePoints = 1; } if(resamplePoints == 1) { xSum=accumulate(xVec.begin(),xVec.end(),0.0f); ySum=accumulate(yVec.begin(),yVec.end(),0.0f); x = xSum/ numTracePoints; //As only 1 point is required, this ratio is computed. y = ySum/ numTracePoints; LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << "x mean = " << x << endl; LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << "y mean = " << y << endl; resampledXVec.push_back(x); resampledYVec.push_back(y); outTrace.addChannel(resampledXVec, xChannelstr); outTrace.addChannel(resampledYVec, yChannelstr); } else if(numTracePoints <= 1) { x = xVec.at(0); y = yVec.at(0); for(pointIndex = 0; pointIndex < resamplePoints; ++pointIndex) { resampledXVec.push_back(x); resampledYVec.push_back(y); LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << "resampled point " << x << y << endl; } outTrace.addChannel(resampledXVec, xChannelstr); outTrace.addChannel(resampledYVec, yChannelstr); } else { LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << "Point distances" << endl; for( pointIndex = 0; pointIndex < (numTracePoints-1); ++pointIndex) { xDiff = xVec.at(pointIndex) - xVec.at(pointIndex+1); yDiff = yVec.at(pointIndex) - yVec.at(pointIndex+1); pointDistance = (float) (sqrt(xDiff*xDiff + yDiff*yDiff)); //distance between 2 points. unitLength += pointDistance; // finding the length of trace. distanceVec.push_back(pointDistance); //storing distances between every 2 consecutive points. LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << "point distance: " << pointDistance << endl; } unitLength /= (resamplePoints -1); LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << "unitLength = " << unitLength << endl; x = xVec.at(0); // adding x of first point; y = yVec.at(0); // adding y of first point; resampledXVec.push_back(x); resampledYVec.push_back(y); LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << "resampled point " << x << y << endl; for(pointIndex = 1; pointIndex < (resamplePoints-1); ++pointIndex) { measuredDistance = balanceDistance; while(measuredDistance < unitLength) { measuredDistance += distanceVec.at(ptIndex++); if(ptIndex == 1) { currentPointIndex = 1; } else { currentPointIndex++; } } if(ptIndex < 1) ptIndex = 1; m2 = measuredDistance - unitLength; m1 = distanceVec.at(ptIndex -1) - m2; if( fabs(m1+m2) > EPS) { xTemp = (m1* xVec.at(currentPointIndex) + m2* xVec.at(currentPointIndex -1))/(m1+m2); yTemp = (m1* yVec.at(currentPointIndex) + m2* yVec.at(currentPointIndex -1))/(m1+m2); } else { xTemp = xVec.at(currentPointIndex); yTemp = yVec.at(currentPointIndex); } resampledXVec.push_back(xTemp); resampledYVec.push_back(yTemp); LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << "resampled point " << xTemp << yTemp << endl; balanceDistance = m2; } x = xVec.at(xVec.size() - 1); // adding x of last point; y = yVec.at(yVec.size() - 1); // adding y of last point; resampledXVec.push_back(x); resampledYVec.push_back(y); LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << "resampled point " << x << y << endl; outTrace.addChannel(resampledXVec, xChannelstr); outTrace.addChannel(resampledYVec, yChannelstr); } LOG( LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting PCAShapeRecognizer::resampleTrace" << endl; return SUCCESS; }
int MprSocket::write(char *buf, int bufsize) { #if BLD_FEATURE_IPV6 struct addrinfo hints, *res; struct sockaddr_storage server6; char port_string[MPR_MAX_IP_PORT]; int rc; #endif struct sockaddr_in server; struct sockaddr *sa; MprSocklen addrlen; int sofar, errCode, len, written; mprAssert(buf); mprAssert(bufsize >= 0); mprAssert((flags & MPR_SOCKET_CLOSED) == 0); addrlen = 0; sa = 0; lock(); if (flags & (MPR_SOCKET_BROADCAST | MPR_SOCKET_DATAGRAM)) { #if BLD_FEATURE_IPV6 if (ipv6) { memset((char *) &hints, '\0', sizeof(hints)); memset((char *) &server, '\0', sizeof(struct sockaddr_storage)); mprSprintf(port_string, sizeof(port_string), "%d", port); hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_NUMERICHOST; if (strcmp(ipAddr, "") == 0) { // Note that IPv6 does not support broadcast, there is no // 255.255.255.255 equiv. Multicast can be used over a specific // link, but the user must provide that address plus %scope_id. unlock(); return -1; } rc = getaddrinfo(ipAddr, port_string, &hints, &res); if (rc) { unlock(); return -1; } else { memcpy(&server, res->ai_addr, res->ai_addrlen); addrlen = res->ai_addrlen; freeaddrinfo(res); } sa = (struct sockaddr*) &server6; } else #endif { memset((char*) &server, '\0', sizeof(struct sockaddr_in)); addrlen = sizeof(struct sockaddr_in); server.sin_family = AF_INET; server.sin_port = htons((short) (port & 0xFFFF)); if (strcmp(ipAddr, "") != 0) { server.sin_addr.s_addr = inet_addr(ipAddr); } else { server.sin_addr.s_addr = INADDR_ANY; } sa = (struct sockaddr*) &server; } } if (flags & MPR_SOCKET_EOF) { sofar = bufsize; } else { errCode = 0; len = bufsize; sofar = 0; while (len > 0) { if ((flags & MPR_SOCKET_BROADCAST) || (flags & MPR_SOCKET_DATAGRAM)) { written = sendto(sock, &buf[sofar], len, MSG_NOSIGNAL, sa, addrlen); } else { written = send(sock, &buf[sofar], len, MSG_NOSIGNAL); } if (written < 0) { errCode = getError(); if (errCode == EINTR) { mprLog(8, log, "%d: write: EINTR\n", sock); continue; } else if (errCode == EAGAIN || errCode == EWOULDBLOCK) { mprLog(8, log, "%d: write: EAGAIN returning %d\n", sock, sofar); unlock(); return sofar; } mprLog(8, log, "%d: write: error %d\n", sock, -errCode); unlock(); return -errCode; } len -= written; sofar += written; } } mprLog(8, log, "%d: write: %d bytes, ask %d, flags %x\n", sock, sofar, bufsize, flags); unlock(); return sofar; }
void UserIOHandler::OnError(BufferedSocketError) { ServerInstance->Users->QuitUser(user, getError()); }
void ConnectionHandler::onClosed() { LOG(info, "channel closed: " << addr()); requests_queue_.clear(getError() ? getError() : base::net::E_NET_HANDLER_CLOSED); }
ElevatorLabWindow::ElevatorLabWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::ElevatorLabWindow) { ui->setupUi(this); //Set up constants //Positive means up for everything /// Mass of the mass, kilograms const double mass = 0.5; /// Floor height, meters const double floorHeight = 4.1; /// Initial height above the ground, meters //TODO when the algorithm is working: Change this to the const double initialHeight = floorHeight * 6; /// Time elapsed between lines in the CSV file, seconds const double lineTime = 0.1; //Set up loop variables /// Velocity, meters/second double velocity = 0; /// Height, meters double height = initialHeight; //Hard-coded file path. Change this if running on another computer. QFile csvFile("/Users/samcrow/Downloads/elevator_lab.csv"); csvFile.open(QIODevice::Text | QIODevice::ReadOnly); //Read and ignore the first line (headers) csvFile.readLine(); //Open the output file in the same directory as the input file QFileInfo csvInfo(csvFile); QString outPath = csvInfo.absoluteDir().path() + "/elevator_out.csv"; qDebug() << outPath; QFile outFile(outPath); outFile.open(QIODevice::Text | QIODevice::Truncate | QIODevice::WriteOnly); outFile.write("Time, Acceleration, Velocity, Corrected Velocity, Height, Floor\n"); //Iterate through every line while(true) { QString line = csvFile.readLine(); //Exit condition: Leave the loop if the end of file is reached if(line.isEmpty()) { break; } QStringList parts = line.split(','); double time = parts.at(0).trimmed().toDouble(); //The downward force, in newtons, excluding the force of gravity, that the 0.5 kg mass applies to the elevator //If this force is negative, the elevator is accelerating upwards and applying an equal and opposite force to the mass double forceOnElevator = parts.at(2).trimmed().toDouble(); //The equal and opposite force that the elevator applies to the mass to accelerate it double forceOnMass = -forceOnElevator; //f = m a //a = f / m double acceleration = forceOnMass / mass; velocity += acceleration * lineTime; /// The velocity, corrected to reduce accumulated error double correctedVelocity = velocity - getError(time); //Try to correct for any additional error in the corrected velocity by setting values with very small magnitudes to zero if(qAbs<double>(correctedVelocity) < 0.1) { correctedVelocity = 0; } height += correctedVelocity * lineTime; //Calculate which floor the elevator is on int floor = qRound(height / floorHeight); qDebug() << "Time" << time << "\tVelocity" << velocity << "\tCorrected velocity" << correctedVelocity << "\tError" << getError(time) << "\tHeight" << height; //Write data to the CSV file outFile.write(QByteArray::number(time)); outFile.write(","); outFile.write(QByteArray::number(acceleration)); outFile.write(","); outFile.write(QByteArray::number(velocity)); outFile.write(","); outFile.write(QByteArray::number(correctedVelocity)); outFile.write(","); outFile.write(QByteArray::number(height)); outFile.write(","); outFile.write(QByteArray::number(floor)); outFile.write("\n"); } outFile.close(); csvFile.close(); }
void StateGraphViewerPanel::workerTaskLoop() { while (true) { std::unique_lock<std::mutex> Lock{TaskMutex}; // Wait until the main thread gives us a task. TaskCV.wait(Lock); // This indicates that we should end the worker thread because the panel is // being destroyed. if (!TaskAccess && !TaskProcess) return; // Create a graph of the process state in dot format. auto const GraphString = workerGenerateDot(); if (GraphString.empty()) { wxLogDebug("GraphString.empty()"); continue; } // The remainder of the graph generation does not use the state, so we can // release access to the task information. Lock.unlock(); // Write the graph to a temporary file. llvm::SmallString<256> GraphPath; { int GraphFD; auto const GraphErr = llvm::sys::fs::createTemporaryFile("seecgraph", "dot", GraphFD, GraphPath); if (GraphErr) { wxLogDebug("Couldn't create temporary dot file: %s", wxString(GraphErr.message())); continue; } llvm::raw_fd_ostream GraphStream(GraphFD, true); GraphStream << GraphString; } // Remove the temporary file when we exit this function. auto const RemoveGraph = seec::scopeExit([&] () { bool Existed = false; llvm::sys::fs::remove(GraphPath.str(), Existed); }); // Create a temporary filename for the dot result. llvm::SmallString<256> SVGPath; auto const SVGErr = llvm::sys::fs::createTemporaryFile("seecgraph", "svg", SVGPath); if (SVGErr) { wxLogDebug("Couldn't create temporary svg file: %s", wxString(SVGErr.message())); continue; } auto const RemoveSVG = seec::scopeExit([&] () { bool Existed = false; llvm::sys::fs::remove(SVGPath.str(), Existed); }); // Run dot using the temporary input/output files. char const *Args[] = { "dot", "-Gfontnames=svg", #if defined(__APPLE__) "-Nfontname=\"Times-Roman\"", #endif "-o", SVGPath.c_str(), "-Tsvg", GraphPath.c_str(), nullptr }; std::vector<char const *> Environment; #if !defined(_WIN32) Environment.emplace_back(PathToGraphvizLibraries.c_str()); Environment.emplace_back(PathToGraphvizPlugins.c_str()); #endif Environment.emplace_back(nullptr); char const **EnvPtr = Environment.size() > 1 ? Environment.data() : nullptr; std::string ErrorMsg; bool ExecFailed = false; auto const Result = HiddenExecuteAndWait(PathToDot, Args, EnvPtr, &ErrorMsg, &ExecFailed); if (!ErrorMsg.empty()) { wxLogDebug("Dot failed: %s", ErrorMsg); continue; } if (Result) { // TODO: send a message to the user - possibly they have selected the // wrong executable? wxLogDebug("Dot returned non-zero."); continue; } // Read the dot-generated SVG from the temporary file. auto ErrorOrSVGData = llvm::MemoryBuffer::getFile(SVGPath.str()); if (!ErrorOrSVGData) { wxLogDebug("Couldn't read temporary svg file: %s", wxString(ErrorOrSVGData.getError().message())); continue; } auto &SVGData = *ErrorOrSVGData; auto SharedSVG = std::make_shared<std::string>(SVGData->getBufferStart(), SVGData->getBufferEnd()); // Remove all non-print characters from the SVG and prepare it to be sent to // the WebView via javascript. auto SharedScript = std::make_shared<wxString>(); auto &Script = *SharedScript; Script.reserve(SVGData->getBufferSize() + 256); Script << "SetState(\""; for (auto const Ch : *SharedSVG) { if (std::isprint(Ch)) { if (Ch == '\\' || Ch == '"') Script << '\\'; Script << Ch; } } Script << "\");"; auto EvPtr = seec::makeUnique<GraphRenderedEvent> (SEEC_EV_GRAPH_RENDERED, this->GetId(), std::move(SharedSVG), std::move(SharedScript)); EvPtr->SetEventObject(this); wxQueueEvent(this->GetEventHandler(), EvPtr.release()); } }
int main(int argc, char** argv) { #ifdef CH_MPI MPI_Init(&argc, &argv); #endif int eekflag = 0; {//begin forever present scoping trick const char* in_file = "ramp.inputs"; //parse input file ParmParse pp(0,NULL,NULL,in_file); //define the geometry object. //need the new and delete because of //strong construction //make the gometry. this makes the first Chombo_EBIS Box domainFine, domainCoar; Real dxFine, dxCoar; //and defines it using a geometryservice eekflag = makeGeometry(domainFine, dxFine); CH_assert(eekflag == 0); domainCoar = coarsen(domainFine, 2); dxCoar = 2.0*dxFine; //make grids DisjointBoxLayout gridsFine, gridsCoar; eekflag = makeLayout(gridsFine, domainFine); CH_assert(eekflag == 0); coarsen(gridsCoar, gridsFine, 2); ///create ebislayout int nghost = 2; EBISLayout ebislFine, ebislCoar; eekflag = makeEBISL(ebislFine, gridsFine, domainFine, nghost); if (eekflag != 0) return eekflag; eekflag = makeEBISL(ebislCoar, gridsCoar, domainCoar, nghost); if (eekflag != 0) return eekflag; int nvar = 1; EBCellFactory ebcellfactFine(ebislFine); EBCellFactory ebcellfactCoar(ebislCoar); IntVect ivghost = nghost*IntVect::Unit; LevelData<EBCellFAB> errorFine(gridsFine, nvar, ivghost,ebcellfactFine); LevelData<EBCellFAB> errorCoar(gridsCoar, nvar, ivghost,ebcellfactCoar); eekflag = getError(errorFine,ebislFine, gridsFine, domainFine, dxFine); if (eekflag != 0) return eekflag; eekflag = getError(errorCoar,ebislCoar, gridsCoar, domainCoar, dxCoar); if (eekflag != 0) return eekflag; eekflag = compareError(errorFine, ebislFine, gridsFine, domainFine, errorCoar, ebislCoar, gridsCoar, domainCoar); if (eekflag != 0) return eekflag; }//end omnipresent scoping trick EBIndexSpace* ebisPtr = Chombo_EBIS::instance(); ebisPtr->clear(); if (eekflag == 0) { pout() << "aggpwlfpTest passed" << endl; } #ifdef CH_MPI MPI_Finalize(); #endif return eekflag; }
uint8_t add_values(app_state_t *s, Message *msg) { timesync_t *ts_list_ptr; ts_packet_t *ts_packet_ptr = (ts_packet_t *)msg->data; float est_error = 0; // Case 1: Empty list if(s->ts_list == NULL) { return FALSE; } // Case 2: Entry found ts_list_ptr = s->ts_list; while(ts_list_ptr) { if(ts_list_ptr->node_id == msg->saddr) { uint8_t i; DEBUG("RATS: Found entry for node %d\n", msg->saddr); //first we have to move the old data one position downwards for(i = 0; i< BUFFER_SIZE-1 ; i++) { ts_list_ptr->timestamps[i] = ts_list_ptr->timestamps[i+1]; ts_list_ptr->my_time[i] = ts_list_ptr->my_time[i+1]; } //afterwards we write the new data in the last position ts_list_ptr->timestamps[BUFFER_SIZE-1] = ts_packet_ptr->time[0]; ts_list_ptr->my_time[BUFFER_SIZE-1] = ts_packet_ptr->time[1]; //calculate error and new window size if(ts_list_ptr->packet_count < BUFFER_SIZE) // learning state { ts_list_ptr->packet_count++; DEBUG("RATS: Learning state: %d packets received\n", ts_list_ptr->packet_count); } else { getRegression(&ts_list_ptr->timestamps[0], &ts_list_ptr->my_time[0], BUFFER_SIZE, ts_list_ptr->window_size, BUFFER_SIZE - ts_list_ptr->window_size, &ts_list_ptr->a, &ts_list_ptr->b); DEBUG("RATS: est_error * SCALING_FACTOR = %f\n", est_error * SCALING_FACTOR); DEBUG("RATS: LOWER_THRESHOLD * sync_precision = %f\n", LOWER_THRESHOLD * ts_list_ptr->sync_precision); est_error = getError(&ts_list_ptr->timestamps[0], &ts_list_ptr->my_time[0], BUFFER_SIZE, ts_list_ptr->window_size, BUFFER_SIZE - ts_list_ptr->window_size, &ts_list_ptr->a, &ts_list_ptr->b, ts_list_ptr->sampling_period, FALSE); if( (est_error) < (LOWER_THRESHOLD * ts_list_ptr->sync_precision)) { if( (ts_list_ptr->sampling_period * 2) <= MAX_SAMPLING_PERIOD) ts_list_ptr->sampling_period *= 2; else ts_list_ptr->sampling_period = MAX_SAMPLING_PERIOD; DEBUG("RATS: New period (doubled): %d\n", ts_list_ptr->sampling_period); } else if((est_error) > (HIGHER_THRESHOLD * ts_list_ptr->sync_precision)) { if( (ts_list_ptr->sampling_period / 2) >= MIN_SAMPLING_PERIOD) ts_list_ptr->sampling_period /= 2; else ts_list_ptr->sampling_period = MIN_SAMPLING_PERIOD; DEBUG("RATS: New period (divided by 2): %d\n", ts_list_ptr->sampling_period); } else { DEBUG("RATS: Period remains constant: %d\n", ts_list_ptr->sampling_period); } // window size has to be in the limits of [2, BUFFER_SIZE] uint8_t temp = (uint8_t)(TIME_CONSTANT/ts_list_ptr->sampling_period); if((temp >= 2)&& (temp <= BUFFER_SIZE)) { ts_list_ptr->window_size = temp; } else if (temp < 2) ts_list_ptr->window_size = (uint8_t)2; DEBUG("RATS: Current window size : %d\n", ts_list_ptr->window_size); } // send packet only if calculated period is less than the one used by the parent // or if I am the node that has the minimum period or if transmitter has set // his id equal to the id with the minimum period (used in transitive modes) if((ts_list_ptr->sampling_period < ts_packet_ptr->transmission_period) || (ts_packet_ptr->min_period_node_id == ker_id()) || (ts_packet_ptr->min_period_node_id == msg->saddr) ) { DEBUG("RATS: new_period=min OR I am min_period_node => transmit new_period\n"); post_net(s->pid, s->pid, MSG_PERIOD_CHANGE, sizeof(uint16_t), &ts_list_ptr->sampling_period, 0, msg->saddr); } //Update fields for panic packets ts_list_ptr->panic_timer_retransmissions = PANIC_TIMER_RETRANSMISSIONS; ts_list_ptr->panic_timer_counter = (ts_list_ptr->sampling_period / INITIAL_TRANSMISSION_PERIOD) + 4; LED_DBG(LED_YELLOW_TOGGLE); #ifdef UART_DEBUG send_debug_packet(s, ts_packet_ptr, est_error); #endif //UART_DEBUG return TRUE; } if(ts_list_ptr->next != NULL) ts_list_ptr = ts_list_ptr->next; else break; } // Case 3: Entry not found return FALSE; }
RawSocketDevice::RecvPacketResult RawSocketDevice::receivePacket(RawPacket& rawPacket, bool blocking, int timeout) { #if defined(WIN32) || defined(WINx64) || defined(PCAPPP_MINGW_ENV) if (!isOpened()) { LOG_ERROR("Device is not open"); return RecvError; } SOCKET fd = ((SocketContainer*)m_Socket)->fd; char* buffer = new char[RAW_SOCKET_BUFFER_LEN]; memset(buffer, 0, RAW_SOCKET_BUFFER_LEN); // value of 0 timeout means disabling timeout if (timeout < 0) timeout = 0; u_long blockingMode = (blocking? 0 : 1); ioctlsocket(fd, FIONBIO, &blockingMode); DWORD timeoutVal = timeout * 1000; setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeoutVal, sizeof(timeoutVal)); //recvfrom(fd, buffer, RAW_SOCKET_BUFFER_LEN, 0, (struct sockaddr*)&sockAddr,(socklen_t*)&sockAddrLen); int bufferLen = recv(fd, buffer, RAW_SOCKET_BUFFER_LEN, 0); if (bufferLen < 0) { delete [] buffer; int errorCode = 0; RecvPacketResult error = getError(errorCode); if (error == RecvError) LOG_ERROR("Error reading from recvfrom. Error code is %d", errorCode); return error; } if (bufferLen > 0) { timeval time; gettimeofday(&time, NULL); rawPacket.setRawData((const uint8_t*)buffer, bufferLen, time, LINKTYPE_DLT_RAW1); return RecvSuccess; } LOG_ERROR("Buffer length is zero"); delete [] buffer; return RecvError; #elif LINUX if (!isOpened()) { LOG_ERROR("Device is not open"); return RecvError; } int fd = ((SocketContainer*)m_Socket)->fd; char* buffer = new char[RAW_SOCKET_BUFFER_LEN]; memset(buffer, 0, RAW_SOCKET_BUFFER_LEN); // value of 0 timeout means disabling timeout if (timeout < 0) timeout = 0; // set blocking or non-blocking flag int flags = fcntl(fd, F_GETFL, 0); if (flags == -1) { LOG_ERROR("Cannot get socket flags"); return RecvError; } flags = (blocking ? (flags & ~O_NONBLOCK) : (flags | O_NONBLOCK)); if (fcntl(fd, F_SETFL, flags) != 0) { LOG_ERROR("Cannot set socket non-blocking flag"); return RecvError; } // set timeout on socket struct timeval timeoutVal; timeoutVal.tv_sec = timeout; timeoutVal.tv_usec = 0; setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeoutVal, sizeof(timeoutVal)); int bufferLen = recv(fd, buffer, RAW_SOCKET_BUFFER_LEN, 0); if (bufferLen < 0) { delete [] buffer; int errorCode = errno; RecvPacketResult error = getError(errorCode); if (error == RecvError) LOG_ERROR("Error reading from recvfrom. Error code is %d", errorCode); return error; } if (bufferLen > 0) { timeval time; gettimeofday(&time, NULL); rawPacket.setRawData((const uint8_t*)buffer, bufferLen, time, LINKTYPE_ETHERNET); return RecvSuccess; } LOG_ERROR("Buffer length is zero"); delete [] buffer; return RecvError; #else LOG_ERROR("Raw socket are not supported on this platform"); return RecvError; #endif }
// wrapper around the reference Punycode implementation static int32_t convertToPuny(const UChar* src, int32_t srcLength, UChar* dest, int32_t destCapacity, UErrorCode& status){ uint32_t b1Stack[MAX_LABEL_BUFFER_SIZE]; int32_t b1Len = 0, b1Capacity = MAX_LABEL_BUFFER_SIZE; uint32_t* b1 = b1Stack; char b2Stack[MAX_LABEL_BUFFER_SIZE]; char* b2 = b2Stack; int32_t b2Len =MAX_LABEL_BUFFER_SIZE ; punycode_status error; unsigned char* caseFlags = NULL; u_strToUTF32((UChar32*)b1,b1Capacity,&b1Len,src,srcLength,&status); if(status == U_BUFFER_OVERFLOW_ERROR){ // redo processing of string /* we do not have enough room so grow the buffer*/ b1 = (uint32_t*) uprv_malloc(b1Len * sizeof(uint32_t)); if(b1==NULL){ status = U_MEMORY_ALLOCATION_ERROR; goto CLEANUP; } status = U_ZERO_ERROR; // reset error u_strToUTF32((UChar32*)b1,b1Len,&b1Len,src,srcLength,&status); } if(U_FAILURE(status)){ goto CLEANUP; } //caseFlags = (unsigned char*) uprv_malloc(b1Len *sizeof(unsigned char)); error = punycode_encode(b1Len,b1,caseFlags, (uint32_t*)&b2Len, b2); status = getError(error); if(status == U_BUFFER_OVERFLOW_ERROR){ /* we do not have enough room so grow the buffer*/ b2 = (char*) uprv_malloc( b2Len * sizeof(char)); if(b2==NULL){ status = U_MEMORY_ALLOCATION_ERROR; goto CLEANUP; } status = U_ZERO_ERROR; // reset error punycode_status error = punycode_encode(b1Len,b1,caseFlags, (uint32_t*)&b2Len, b2); status = getError(error); } if(U_FAILURE(status)){ goto CLEANUP; } if(b2Len < destCapacity){ convertASCIIToUChars(b2,dest,b2Len); }else{ status =U_BUFFER_OVERFLOW_ERROR; } CLEANUP: if(b1Stack != b1){ uprv_free(b1); } if(b2Stack != b2){ uprv_free(b2); } uprv_free(caseFlags); return b2Len; }
int MprSocket::read(char *buf, int bufsize) { #if BLD_FEATURE_IPV6 struct sockaddr_storage server6; #endif struct sockaddr_in server; struct sockaddr *sa; MprSocklen addrlen; int bytes, errCode; mprAssert(buf); mprAssert(bufsize > 0); mprAssert(~(flags & MPR_SOCKET_CLOSED)); lock(); if (flags & MPR_SOCKET_EOF) { unlock(); return 0; } again: if (flags & MPR_SOCKET_DATAGRAM) { #if BLD_FEATURE_IPV6 if (ipv6) { sa = (struct sockaddr*) &server6; addrlen = sizeof(server6); } else #endif { sa = (struct sockaddr*) &server; addrlen = sizeof(server); } bytes = recvfrom(sock, buf, bufsize, MSG_NOSIGNAL, sa, (SocketLenPtr) &addrlen); } else { bytes = recv(sock, buf, bufsize, MSG_NOSIGNAL); } if (bytes < 0) { errCode = getError(); if (errCode == EINTR) { goto again; } else if (errCode == EAGAIN || errCode == EWOULDBLOCK) { bytes = 0; // No data available } else if (errCode == ECONNRESET) { flags |= MPR_SOCKET_EOF; // Disorderly disconnect bytes = 0; } else { flags |= MPR_SOCKET_EOF; // Some other error bytes = -errCode; } } else if (bytes == 0) { // EOF flags |= MPR_SOCKET_EOF; mprLog(8, log, "%d: read: %d bytes, EOF\n", sock, bytes); } else { mprLog(8, log, "%d: read: %d bytes\n", sock, bytes); } unlock(); return bytes; }
void EmitterSystem::init(bool firsttime) { std::cout << "-> Initialize particles as a circle." << std::endl; cl_int err = 0; std::random_device rd; std::mt19937 eng(rd()); std::uniform_real_distribution<float> dist(1.f, 3.5f); std::uniform_real_distribution<float> dist_life(0.1f, 1.5f); std::uniform_real_distribution<float> dist_vel(0.f, 1.f); std::uniform_real_distribution<float> dist_polar(0.f, Pi2); std::uniform_real_distribution<float> dist_half_polar(-PiDiv2, PiDiv2); glBindBuffer(GL_ARRAY_BUFFER, m_vbo[Index::Particles]); Particle *p = static_cast<Particle*>(glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY)); for (std::size_t i = 0; i < m_particleCount; i++) p[i].position = Vector3(0.f, 0.f, 0.f); if (firsttime) { m_glBuffer[Index::Particles] = cl::BufferGL(getContext(), CL_MEM_READ_WRITE, m_vbo[Index::Particles], &err); if (err) std::cout << "ERROR (" << getError(err) << "): kernel loading failed." << std::endl; m_clBuffer[Index::Particles] = cl::Buffer(getContext(), CL_MEM_READ_WRITE, m_particleCount * sizeof(Particle), NULL, &err); } err = getQueue().enqueueWriteBuffer(m_clBuffer[Index::Particles], CL_TRUE, 0, m_particleCount * sizeof(Particle), p); if (err) std::cout << "ERROR -> " << getError(err) << std::endl; glUnmapBuffer(GL_ARRAY_BUFFER); glBindBuffer(GL_ARRAY_BUFFER, m_vbo[Index::Velocity]); Vector3 * v = static_cast<Vector3*>(glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY)); for (std::size_t i = 0; i < m_particleCount; i++) { Vector3 vec = Vector3(dist(eng), dist(eng), dist(eng)); v[i * 2 + 0] = vec; v[i * 2 + 1] = vec; } if (firsttime) { m_glBuffer[Index::Velocity] = cl::BufferGL(getContext(), CL_MEM_READ_WRITE, m_vbo[Index::Velocity], &err); if (err) std::cout << "ERROR (" << getError(err) << "): kernel loading failed." << std::endl; m_clBuffer[Index::Velocity] = cl::Buffer(getContext(), CL_MEM_READ_WRITE, 2 * m_particleCount * sizeof(Vector3), NULL, &err); if (err) std::cout << "ERROR (" << err << ")" << getError(err) << std::endl; } err = getQueue().enqueueWriteBuffer(m_clBuffer[Index::Velocity], CL_TRUE, 0, 2 * m_particleCount * sizeof(Vector3), v); if (err) std::cout << "ERROR -> " << getError(err) << std::endl; glUnmapBuffer(GL_ARRAY_BUFFER); glBindBuffer(GL_ARRAY_BUFFER, m_vbo[Index::Life]); float *l = static_cast<float*>(glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY)); for (std::size_t i = 0; i < m_particleCount; i++) { l[i * 2 + 0] = 0.f; l[i * 2 + 1] = dist_life(eng); } if (firsttime) { m_glBuffer[Index::Life] = cl::BufferGL(getContext(), CL_MEM_READ_WRITE, m_vbo[Index::Life], &err); if (err) std::cout << "ERROR (" << getError(err) << "): kernel loading failed." << std::endl; m_clBuffer[Index::Life] = cl::Buffer(getContext(), CL_MEM_READ_WRITE, 2 * m_particleCount * sizeof(float), NULL, &err); if (err) std::cout << "ERROR (" << err << ")" << getError(err) << std::endl; } err = getQueue().enqueueWriteBuffer(m_clBuffer[Index::Life], CL_TRUE, 0, 2 * m_particleCount * sizeof(float), l); if (err) std::cout << "ERROR -> " << getError(err) << std::endl; glUnmapBuffer(GL_ARRAY_BUFFER); }
int MprSocket::openClient(char *addr, int portNum, int initialFlags) { #if BLD_FEATURE_IPV6 struct addrinfo hints, *res; struct sockaddr_storage remoteAddr6; char portNum_string[MPR_MAX_IP_PORT]; char addrBuf[MPR_MAX_IP_ADDR]; #endif struct sockaddr_in remoteAddr; struct hostent *hostent; struct sockaddr *sa; MprSocklen addrlen; int broadcast, datagram, rc, err; mprLog(6, log, "openClient: %s:%d, flags %x\n", addr, portNum, initialFlags); #if BLD_FEATURE_IPV6 if (addr[0] == '[') { ipv6 = 1; mprStrcpy(addrBuf, sizeof(addr), &addr[1]); mprAssert(addrBuf[strlen(addrBuf) - 2] == ']'); addrBuf[strlen(addrBuf) - 2] = '\0'; addr = addrBuf; } else { ipv6 = 0; } if (ipv6) { memset((char*) &hints, '\0', sizeof(hints)); memset((char*) &remoteAddr6, '\0', sizeof(struct sockaddr_storage)); mprSprintf(portNum_string, sizeof(portNum_string), "%d", portNum); hints.ai_socktype = SOCK_STREAM; rc = getaddrinfo(addr, portNum_string, &hints, &res); if (rc) { /* no need to unlock yet */ return MPR_ERR_CANT_OPEN; } sa = (struct sockaddr*) &remoteAddr6; memcpy(sa, res->ai_addr, res->ai_addrlen); addrlen = res->ai_addrlen; freeaddrinfo(res); } else #endif { memset((char *) &remoteAddr, '\0', sizeof(struct sockaddr_in)); remoteAddr.sin_family = AF_INET; remoteAddr.sin_port = htons((short) (portNum & 0xFFFF)); sa = (struct sockaddr*) &remoteAddr; addrlen = sizeof(remoteAddr); } lock(); port = portNum; flags = (initialFlags & (MPR_SOCKET_BROADCAST | MPR_SOCKET_DATAGRAM | MPR_SOCKET_BLOCK | MPR_SOCKET_LISTENER | MPR_SOCKET_NOREUSE | MPR_SOCKET_NODELAY)); // Save copy of the address ipAddr = mprStrdup(addr); #if BLD_FEATURE_IPV6 if (!ipv6) { // Nothing here } else #endif { remoteAddr.sin_addr.s_addr = inet_addr(ipAddr); if (remoteAddr.sin_addr.s_addr == INADDR_NONE) { hostent = mprGetHostByName(ipAddr); if (hostent != 0) { memcpy((char*) &remoteAddr.sin_addr, (char*) hostent->h_addr_list[0], (size_t) hostent->h_length); mprFreeGetHostByName(hostent); } else { unlock(); return MPR_ERR_NOT_FOUND; } } } broadcast = flags & MPR_SOCKET_BROADCAST; if (broadcast) { flags |= MPR_SOCKET_DATAGRAM; } datagram = flags & MPR_SOCKET_DATAGRAM; // // Create the O/S socket // sock = socket(sa->sa_family, datagram ? SOCK_DGRAM: SOCK_STREAM, 0); if (sock < 0) { err = getError(); unlock(); return -err; } #if !WIN && !WINCE && !VXWORKS fcntl(sock, F_SETFD, FD_CLOEXEC); // Children won't inherit this fd #endif if (broadcast) { int flag = 1; if (setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (char *) &flag, sizeof(flag)) < 0) { err = getError(); ::closesocket(sock); sock = -1; unlock(); return -err; } } if (!datagram) { flags |= MPR_SOCKET_CONNECTING; rc = connect(sock, sa, addrlen); if (rc < 0) { err = getError(); ::closesocket(sock); sock = -1; unlock(); #if UNUSED // // If the listen backlog is too high, ECONNREFUSED is returned // if (err == EADDRINUSE || err == ECONNREFUSED) { return MPR_ERR_BUSY; } #endif return -err; } } setBlockingMode((bool) (flags & MPR_SOCKET_BLOCK)); // // TCP/IP stacks have the No delay option (nagle algorithm) on by default. // if (flags & MPR_SOCKET_NODELAY) { setNoDelay(1); } unlock(); return sock; }
virtual void run() { fTraceInfo = 1; LocalPointer<NumberFormat> percentFormatter; UErrorCode status = U_ZERO_ERROR; #if 0 // debugging code, for (int i=0; i<4000; i++) { status = U_ZERO_ERROR; UDataMemory *data1 = udata_openChoice(0, "res", "en_US", isAcceptable, 0, &status); UDataMemory *data2 = udata_openChoice(0, "res", "fr", isAcceptable, 0, &status); udata_close(data1); udata_close(data2); if (U_FAILURE(status)) { error("udata_openChoice failed.\n"); break; } } return; #endif #if 0 // debugging code, int m; for (m=0; m<4000; m++) { status = U_ZERO_ERROR; UResourceBundle *res = NULL; const char *localeName = NULL; Locale loc = Locale::getEnglish(); localeName = loc.getName(); // localeName = "en"; // ResourceBundle bund = ResourceBundle(0, loc, status); //umtx_lock(&gDebugMutex); res = ures_open(NULL, localeName, &status); //umtx_unlock(&gDebugMutex); //umtx_lock(&gDebugMutex); ures_close(res); //umtx_unlock(&gDebugMutex); if (U_FAILURE(status)) { error("Resource bundle construction failed.\n"); break; } } return; #endif // Keep this data here to avoid static initialization. FormatThreadTestData kNumberFormatTestData[] = { FormatThreadTestData((double)5.0, UnicodeString("5", "")), FormatThreadTestData( 6.0, UnicodeString("6", "")), FormatThreadTestData( 20.0, UnicodeString("20", "")), FormatThreadTestData( 8.0, UnicodeString("8", "")), FormatThreadTestData( 8.3, UnicodeString("8.3", "")), FormatThreadTestData( 12345, UnicodeString("12,345", "")), FormatThreadTestData( 81890.23, UnicodeString("81,890.23", "")), }; int32_t kNumberFormatTestDataLength = (int32_t)(sizeof(kNumberFormatTestData) / sizeof(kNumberFormatTestData[0])); // Keep this data here to avoid static initialization. FormatThreadTestData kPercentFormatTestData[] = { FormatThreadTestData((double)5.0, CharsToUnicodeString("500\\u00a0%")), FormatThreadTestData( 1.0, CharsToUnicodeString("100\\u00a0%")), FormatThreadTestData( 0.26, CharsToUnicodeString("26\\u00a0%")), FormatThreadTestData( 16384.99, CharsToUnicodeString("1\\u00a0638\\u00a0499\\u00a0%")), // U+00a0 = NBSP FormatThreadTestData( 81890.23, CharsToUnicodeString("8\\u00a0189\\u00a0023\\u00a0%")), }; int32_t kPercentFormatTestDataLength = (int32_t)(sizeof(kPercentFormatTestData) / sizeof(kPercentFormatTestData[0])); int32_t iteration; status = U_ZERO_ERROR; LocalPointer<NumberFormat> formatter(NumberFormat::createInstance(Locale::getEnglish(),status)); if(U_FAILURE(status)) { error("Error on NumberFormat::createInstance()."); goto cleanupAndReturn; } percentFormatter.adoptInstead(NumberFormat::createPercentInstance(Locale::getFrench(),status)); if(U_FAILURE(status)) { error("Error on NumberFormat::createPercentInstance()."); goto cleanupAndReturn; } for(iteration = 0;!getError() && iteration<kFormatThreadIterations;iteration++) { int32_t whichLine = (iteration + fOffset)%kNumberFormatTestDataLength; UnicodeString output; formatter->format(kNumberFormatTestData[whichLine].number, output); if(0 != output.compare(kNumberFormatTestData[whichLine].string)) { error("format().. expected " + kNumberFormatTestData[whichLine].string + " got " + output); goto cleanupAndReturn; } // Now check percent. output.remove(); whichLine = (iteration + fOffset)%kPercentFormatTestDataLength; percentFormatter->format(kPercentFormatTestData[whichLine].number, output); if(0 != output.compare(kPercentFormatTestData[whichLine].string)) { error("percent format().. \n" + showDifference(kPercentFormatTestData[whichLine].string,output)); goto cleanupAndReturn; } // Test message error const int kNumberOfMessageTests = 3; UErrorCode statusToCheck; UnicodeString patternToCheck; Locale messageLocale; Locale countryToCheck; double currencyToCheck; UnicodeString expected; // load the cases. switch((iteration+fOffset) % kNumberOfMessageTests) { default: case 0: statusToCheck= U_FILE_ACCESS_ERROR; patternToCheck= "0:Someone from {2} is receiving a #{0}" " error - {1}. Their telephone call is costing " "{3,number,currency}."; // number,currency messageLocale= Locale("en","US"); countryToCheck= Locale("","HR"); currencyToCheck= 8192.77; expected= "0:Someone from Croatia is receiving a #4 error - " "U_FILE_ACCESS_ERROR. Their telephone call is costing $8,192.77."; break; case 1: statusToCheck= U_INDEX_OUTOFBOUNDS_ERROR; patternToCheck= "1:A customer in {2} is receiving a #{0} error - {1}. Their telephone call is costing {3,number,currency}."; // number,currency messageLocale= Locale("de","DE@currency=DEM"); countryToCheck= Locale("","BF"); currencyToCheck= 2.32; expected= CharsToUnicodeString( "1:A customer in Burkina Faso is receiving a #8 error - U_INDEX_OUTOFBOUNDS_ERROR. Their telephone call is costing 2,32\\u00A0DM."); break; case 2: statusToCheck= U_MEMORY_ALLOCATION_ERROR; patternToCheck= "2:user in {2} is receiving a #{0} error - {1}. " "They insist they just spent {3,number,currency} " "on memory."; // number,currency messageLocale= Locale("de","AT@currency=ATS"); // Austrian German countryToCheck= Locale("","US"); // hmm currencyToCheck= 40193.12; expected= CharsToUnicodeString( "2:user in Vereinigte Staaten is receiving a #7 error" " - U_MEMORY_ALLOCATION_ERROR. They insist they just spent" " \\u00f6S\\u00A040.193,12 on memory."); break; } UnicodeString result; UErrorCode status = U_ZERO_ERROR; formatErrorMessage(status,patternToCheck,messageLocale,statusToCheck, countryToCheck,currencyToCheck,result); if(U_FAILURE(status)) { UnicodeString tmp(u_errorName(status)); error("Failure on message format, pattern=" + patternToCheck + ", error = " + tmp); goto cleanupAndReturn; } if(result != expected) { error("PatternFormat: \n" + showDifference(expected,result)); goto cleanupAndReturn; } } /* end of for loop */ cleanupAndReturn: // while (fNum == 4) {SimpleThread::sleep(10000);} // Force a failure by preventing thread from finishing fTraceInfo = 2; }
void MprSocket::acceptProc(int isMprPoolThread) { MprSocket *nsp; MprSocketService *ss; #if BLD_FEATURE_IPV6 struct sockaddr_storage addr6; char hbuf[NI_MAXHOST]; char sbuf[NI_MAXSERV]; int rc; #endif struct sockaddr_in addr; struct sockaddr *sa; char callerIpAddr[MPR_MAX_IP_ADDR]; MprSocklen addrlen; int fd, max, numClients; if (acceptCallback == 0) { return; } lock(); #if BLD_FEATURE_IPV6 if (ipv6) { sa = (struct sockaddr*) &addr6; addrlen = sizeof(addr6); } else #endif { sa = (struct sockaddr*) &addr; addrlen = sizeof(addr); } fd = accept(sock, sa, (SocketLenPtr) &addrlen); if (fd < 0) { mprLog(0, log, "%d: acceptProc: accept failed %d\n", sock, getError()); unlock(); return; } #if !WIN && !WINCE && !VXWORKS fcntl(fd, F_SETFD, FD_CLOEXEC); // Prevent children inheriting #endif ss = mprGetMpr()->socketService; max = ss->getMaxClients(); numClients = ss->getNumClients(); if (max > 0 && numClients >= max) { mprLog(3, "Rejecting connection, too many client connections (%d)\n", numClients); #if CYGWIN || LINUX || MACOSX || SOLARIS || VXWORKS || FREEBSD shutdown(fd, MPR_SHUTDOWN_BOTH); #endif ::closesocket(fd); mprGetMpr()->selectService->awaken(0); unlock(); return; } nsp = newSocket(); nsp->lock(); nsp->sock = fd; nsp->ipAddr = mprStrdup(ipAddr); nsp->acceptData = acceptData; nsp->ioData = ioData; nsp->ioData2 = ioData2; nsp->port = port; nsp->acceptCallback = acceptCallback; nsp->flags = flags; nsp->flags &= ~MPR_SOCKET_LISTENER; nsp->setBlockingMode((nsp->flags & MPR_SOCKET_BLOCK) ? 1: 0); if (nsp->flags & MPR_SOCKET_NODELAY) { nsp->setNoDelay(1); } nsp->inUse++; mprLog(6, log, "%d: acceptProc: isMprPoolThread %d, newSock %d\n", sock, isMprPoolThread, fd); nsp->unlock(); // // Call the user accept callback. // #if BLD_FEATURE_IPV6 if (ipv6) { rc = getnameinfo(sa, addrlen, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf), NI_NUMERICHOST | NI_NUMERICSERV); if (rc) { mprError(MPR_L, MPR_LOG, "Exiting acceptProc with failed getnameinfo"); delete nsp; return; } (nsp->acceptCallback)(nsp->acceptData, nsp, hbuf, atoi(sbuf), this, isMprPoolThread); } else #endif { mprInetNtoa(callerIpAddr, sizeof(callerIpAddr), addr.sin_addr); (nsp->acceptCallback)(nsp->acceptData, nsp, callerIpAddr, ntohs(addr.sin_port), this, isMprPoolThread); } nsp->lock(); if (--nsp->inUse == 0 && nsp->flags & MPR_SOCKET_DISPOSED) { mprLog(9, log, "%d: acceptProc: Leaving deleted\n", sock); delete nsp; } else{ nsp->unlock(); } unlock(); }
bool Pipe::_configInitWGLEW() { //----- Create and make current a temporary GL context to initialize WGLEW // window class std::ostringstream className; className << "TMP" << (void*)this; const std::string& classStr = className.str(); HINSTANCE instance = GetModuleHandle( 0 ); WNDCLASS wc = { 0 }; wc.lpfnWndProc = DefWindowProc; wc.hInstance = instance; wc.hIcon = LoadIcon( 0, IDI_WINLOGO ); wc.hCursor = LoadCursor( 0, IDC_ARROW ); wc.lpszClassName = classStr.c_str(); if( !RegisterClass( &wc )) { setError( ERROR_WGLPIPE_REGISTERCLASS_FAILED ); EQWARN << getError() << ": " << co::base::sysError << std::endl; return false; } // window DWORD windowStyleEx = WS_EX_APPWINDOW; DWORD windowStyle = WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_OVERLAPPEDWINDOW; HWND hWnd = CreateWindowEx( windowStyleEx, wc.lpszClassName, "TMP", windowStyle, 0, 0, 1, 1, 0, 0, // parent, menu instance, 0 ); if( !hWnd ) { setError( ERROR_SYSTEMPIPE_CREATEWINDOW_FAILED ); EQWARN << getError() << ": " << co::base::sysError << std::endl; UnregisterClass( classStr.c_str(), instance ); return false; } HDC dc = GetDC( hWnd ); PIXELFORMATDESCRIPTOR pfd = {0}; pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR); pfd.nVersion = 1; pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL; int pf = ChoosePixelFormat( dc, &pfd ); if( pf == 0 ) { setError( ERROR_SYSTEMPIPE_PIXELFORMAT_NOTFOUND ); EQWARN << getError() << ": " << co::base::sysError << std::endl; DestroyWindow( hWnd ); UnregisterClass( classStr.c_str(), instance ); return false; } if( !SetPixelFormat( dc, pf, &pfd )) { setError( ERROR_WGLPIPE_SETPF_FAILED ); EQWARN << getError() << ": " << co::base::sysError << std::endl; ReleaseDC( hWnd, dc ); DestroyWindow( hWnd ); UnregisterClass( classStr.c_str(), instance ); return false; } // context HGLRC context = wglCreateContext( dc ); if( !context ) { setError( ERROR_SYSTEMPIPE_CREATECONTEXT_FAILED ); EQWARN << getError() << ": " << co::base::sysError << std::endl; ReleaseDC( hWnd, dc ); DestroyWindow( hWnd ); UnregisterClass( classStr.c_str(), instance ); return false; } HDC oldDC = wglGetCurrentDC(); HGLRC oldContext = wglGetCurrentContext(); wglMakeCurrent( dc, context ); const GLenum result = wglewInit(); bool success = result == GLEW_OK; if( success ) { EQINFO << "Pipe WGLEW initialization successful" << std::endl; success = configInitGL(); } else { setError( ERROR_WGLPIPE_WGLEWINIT_FAILED ); EQWARN << getError() << ": " << result << std::endl; } wglDeleteContext( context ); ReleaseDC( hWnd, dc ); DestroyWindow( hWnd ); UnregisterClass( classStr.c_str(), instance ); wglMakeCurrent( oldDC, oldContext ); return success; }
EFI_STATUS efi_main(EFI_HANDLE ImageHandle, EFI_SYSTEM_TABLE *SystemTable) { InitializeLib(ImageHandle, SystemTable); CallConstructors(); EFI_STATUS Status; const char16_t* searchdir = u"\\EFI\\ChaiOS\\"; if (Status = SetWorkingDirectory(searchdir)) printf(u"Error setting working directory: %s\r\n", getError(Status)); CHAIOS_BOOT_FILES* bootfile = nullptr; while (bootfile = iterateBootFiles(bootfile)) { if (bootfile->loadLocation != nullptr) continue; //Support in-memory images EFI_FILE* file = OpenFile(bootfile->fileName, "r"); if (!file) { printf(u"Error: could not open %s: %s\r\n", bootfile->fileName, getError(getErrno())); } UINT64 fileSize = GetFileSize(file); VOID* bootfilebuf = kmalloc(fileSize+1); UINTN read = ReadFile(bootfilebuf, 1, fileSize, file); if (read < fileSize) printf(u"Read %d bytes, failed\r\n", read); else printf(u"Successfully read %d bytes\r\n", read); //Boot file is now loaded into memory CloseFile(file); bootfile->loadLocation = bootfilebuf; bootfile->fileSize = fileSize; if (bootfile->bootType == CHAIOS_BOOT_CONFIGURATION) { //We need to parse this now. INI format ((char*)bootfilebuf)[fileSize] = '\0'; ini_parse_string((const char*)bootfilebuf, &bootini_handler, nullptr); } } //size_t value = GetIntegerInput(u"Enter scrolling lines configuration: "); //set_scrolllines(value); UINT32 AutoMode = IterateGraphicsMode(&match_config_resoultion); EFI_GRAPHICS_OUTPUT_MODE_INFORMATION* info; UINTN SizeOfInfo; if (AutoMode == UINT32_MAX) { if (!EFI_ERROR(GetGraphicsModeInfo(AutoMode, &info, &SizeOfInfo))) { IterateGraphicsMode(&print_graphics_mode); size_t value = GetIntegerInput(u"Enter boot graphics mode: "); SetGraphicsMode(value); AutoMode = value; } } else { SetGraphicsMode(AutoMode); } if (!EFI_ERROR(GetGraphicsModeInfo(AutoMode, &info, &SizeOfInfo))) { printf(u"Graphics mode %d: %dx%d\r\n", AutoMode, info->HorizontalResolution, info->VerticalResolution); } puts(u"ChaiOS 0.09 UEFI Loader\r\n"); int majorver = SystemTable->Hdr.Revision / (1 << 16); int minorver = SystemTable->Hdr.Revision % (1 << 16); printf(u"Firmware Vendor: %s, version: %d (UEFI:%d.%d)\r\n", SystemTable->FirmwareVendor, SystemTable->FirmwareRevision, majorver, minorver); //Read ACPI configuration tables //startup_acpi(SystemTable); //startup_multiprocessor(); const size_t EARLY_PAGE_STACK_SIZE = 1024*1024; EFI_PHYSICAL_ADDRESS earlyPhypageStack = 0; if (EFI_ERROR(SystemTable->BootServices->AllocatePages(AllocateAnyPages, EfiLoaderData, EARLY_PAGE_STACK_SIZE / EFI_PAGE_SIZE, &earlyPhypageStack))) { puts(u"Could not allocate page stack\r\n"); return EFI_OUT_OF_RESOURCES; } SystemTable->BootServices->SetWatchdogTimer(0, 0, 0, nullptr); PrepareExitBootServices(); EfiMemoryMap map; map.MemMapSize = map.MapKey = map.DescriptorSize = map.DescriptorVersion = 0; SystemTable->BootServices->GetMemoryMap(&map.MemMapSize, nullptr, &map.MapKey, &map.DescriptorSize, &map.DescriptorVersion); //Give a nice bit of room to spare (memory map can change) map.MemMapSize += 16 * map.DescriptorSize; map.memmap = (EFI_MEMORY_DESCRIPTOR*)kmalloc(map.MemMapSize); //Allocate a nice buffer SystemTable->BootServices->GetMemoryMap(&map.MemMapSize, map.memmap, &map.MapKey, &map.DescriptorSize, &map.DescriptorVersion); printf(u"EFI Memory Map: Descriptor size %d\n", map.DescriptorSize); #if 0 //Dump the UEFI memory map to a file for testing EFI_FILE* file = OpenFile(u"efimap.dat", "w"); if (!file) { printf(u"Error: could not open %s: %s\r\n", u"efimap.dat", getError(getErrno())); } WriteFile(map.memmap, 1, map.MemMapSize, file); CloseFile(file); #endif if (EFI_ERROR(Status = SystemTable->BootServices->ExitBootServices(ImageHandle, map.MapKey))) { printf(u"Failed to exit boot services: %s\r\n", getError(Status)); UINTN index; SystemTable->BootServices->WaitForEvent(1, &SystemTable->ConIn->WaitForKey, &index); return EFI_SUCCESS; } //We need to take control of the hardware now. Setup basic memory management setLiballocAllocator(nullptr, nullptr); InitializePmmngr(map, (void*)earlyPhypageStack, EARLY_PAGE_STACK_SIZE); puts(u"Physical memory manager intialized\n"); arch_initialize_paging(); puts(u"Paging initialized\n"); setLiballocAllocator(&arch_allocate_pages, &arch_free_pages); //Now load the OS! bootfile = nullptr; kimage_entry kentry = nullptr; KLOAD_HANDLE kernel = NULL; while (bootfile = iterateBootFiles(bootfile)) { printf(u"Boot file: %s @ %x, length %d, type %d\n", bootfile->fileName, bootfile->loadLocation, bootfile->fileSize, bootfile->bootType); if (!bootfile->loadLocation) continue; if (bootfile->bootType == CHAIOS_DLL) { KLOAD_HANDLE dll = LoadImage(bootfile->loadLocation, bootfile->fileName); if (GetProcAddress(dll, "memcpy")) { set_memcpy((memcpy_proc)GetProcAddress(dll, "memcpy")); } } else if (bootfile->bootType == CHAIOS_KERNEL) { kernel = LoadImage(bootfile->loadLocation, bootfile->fileName); kentry = GetEntryPoint(kernel); } } size_t kstacksize = GetStackSize(kernel); if (!paging_map(stackaddr, PADDR_T_MAX, kstacksize, PAGE_ATTRIBUTE_WRITABLE)) { puts(u"Error: could not allocate kernel stack\n"); while (1); } KERNEL_BOOT_INFO bootinfo; fill_pmmngr_info(bootinfo.pmmngr_info); fill_arch_paging_info(bootinfo.paging_info); fill_modloader_info(bootinfo.modloader_info); get_framebuffer_info(bootinfo.fbinfo); populate_kterm_info(bootinfo.kterm_status); bootinfo.efi_system_table = SystemTable; bootinfo.memory_map = ↦ bootinfo.loaded_files = &bootfiles; bootinfo.boottype = CHAIOS_BOOT_TYPE_UEFI; bootinfo.printf_proc = &printf; bootinfo.puts_proc = &puts; printf(u"Success: Kernel entry point at %x, stack at %x, length %x\n", kentry, stackaddr, kstacksize); call_kernel(&bootinfo, kentry, stackaddr, kstacksize); puts(u"Kernel returned"); while (1); }