Exemplo n.º 1
1
PackedPayloadHashTable::PackedPayloadHashTable(
    const std::vector<const Type *> &key_types,
    const std::size_t num_entries,
    const std::vector<AggregationHandle *> &handles,
    StorageManager *storage_manager)
    : key_types_(key_types),
      num_handles_(handles.size()),
      handles_(handles),
      total_payload_size_(ComputeTotalPayloadSize(handles)),
      storage_manager_(storage_manager),
      kBucketAlignment(alignof(std::atomic<std::size_t>)),
      kValueOffset(sizeof(std::atomic<std::size_t>) + sizeof(std::size_t)),
      key_manager_(key_types_, kValueOffset + total_payload_size_),
      bucket_size_(ComputeBucketSize(key_manager_.getFixedKeySize())) {
  std::size_t payload_offset_running_sum = sizeof(SpinMutex);
  for (const auto *handle : handles) {
    payload_offsets_.emplace_back(payload_offset_running_sum);
    payload_offset_running_sum += handle->getPayloadSize();
  }

  // NOTE(jianqiao): Potential memory leak / double freeing by copying from
  // init_payload to buckets if payload contains out of line data.
  init_payload_ =
      static_cast<std::uint8_t *>(calloc(this->total_payload_size_, 1));
  DCHECK(init_payload_ != nullptr);

  for (std::size_t i = 0; i < num_handles_; ++i) {
    handles_[i]->initPayload(init_payload_ + payload_offsets_[i]);
  }

  // Bucket size always rounds up to the alignment requirement of the atomic
  // size_t "next" pointer at the front or a ValueT, whichever is larger.
  //
  // Give base HashTable information about what key components are stored
  // inline from 'key_manager_'.
  setKeyInline(key_manager_.getKeyInline());

  // Pick out a prime number of slots and calculate storage requirements.
  std::size_t num_slots_tmp =
      get_next_prime_number(num_entries * kHashTableLoadFactor);
  std::size_t required_memory =
      sizeof(Header) + num_slots_tmp * sizeof(std::atomic<std::size_t>) +
      (num_slots_tmp / kHashTableLoadFactor) *
          (bucket_size_ + key_manager_.getEstimatedVariableKeySize());
  std::size_t num_storage_slots =
      this->storage_manager_->SlotsNeededForBytes(required_memory);
  if (num_storage_slots == 0) {
    FATAL_ERROR(
        "Storage requirement for SeparateChainingHashTable "
        "exceeds maximum allocation size.");
  }

  // Get a StorageBlob to hold the hash table.
  const block_id blob_id =
      this->storage_manager_->createBlob(num_storage_slots);
  this->blob_ = this->storage_manager_->getBlobMutable(blob_id);

  void *aligned_memory_start = this->blob_->getMemoryMutable();
  std::size_t available_memory = num_storage_slots * kSlotSizeBytes;
  if (align(alignof(Header),
            sizeof(Header),
            aligned_memory_start,
            available_memory) == nullptr) {
    // With current values from StorageConstants.hpp, this should be
    // impossible. A blob is at least 1 MB, while a Header has alignment
    // requirement of just kCacheLineBytes (64 bytes).
    FATAL_ERROR(
        "StorageBlob used to hold resizable "
        "SeparateChainingHashTable is too small to meet alignment "
        "requirements of SeparateChainingHashTable::Header.");
  } else if (aligned_memory_start != this->blob_->getMemoryMutable()) {
    // This should also be impossible, since the StorageManager allocates slots
    // aligned to kCacheLineBytes.
    DEV_WARNING("StorageBlob memory adjusted by "
                << (num_storage_slots * kSlotSizeBytes - available_memory)
                << " bytes to meet alignment requirement for "
                << "SeparateChainingHashTable::Header.");
  }

  // Locate the header.
  header_ = static_cast<Header *>(aligned_memory_start);
  aligned_memory_start =
      static_cast<char *>(aligned_memory_start) + sizeof(Header);
  available_memory -= sizeof(Header);

  // Recompute the number of slots & buckets using the actual available memory.
  // Most likely, we got some extra free bucket space due to "rounding up" to
  // the storage blob's size. It's also possible (though very unlikely) that we
  // will wind up with fewer buckets than we initially wanted because of screwy
  // alignment requirements for ValueT.
  std::size_t num_buckets_tmp =
      available_memory /
      (kHashTableLoadFactor * sizeof(std::atomic<std::size_t>) + bucket_size_ +
       key_manager_.getEstimatedVariableKeySize());
  num_slots_tmp =
      get_previous_prime_number(num_buckets_tmp * kHashTableLoadFactor);
  num_buckets_tmp = num_slots_tmp / kHashTableLoadFactor;
  DEBUG_ASSERT(num_slots_tmp > 0);
  DEBUG_ASSERT(num_buckets_tmp > 0);

  // Locate the slot array.
  slots_ = static_cast<std::atomic<std::size_t> *>(aligned_memory_start);
  aligned_memory_start = static_cast<char *>(aligned_memory_start) +
                         sizeof(std::atomic<std::size_t>) * num_slots_tmp;
  available_memory -= sizeof(std::atomic<std::size_t>) * num_slots_tmp;

  // Locate the buckets.
  buckets_ = aligned_memory_start;
  // Extra-paranoid: If ValueT has an alignment requirement greater than that
  // of std::atomic<std::size_t>, we may need to adjust the start of the bucket
  // array.
  if (align(kBucketAlignment, bucket_size_, buckets_, available_memory) ==
      nullptr) {
    FATAL_ERROR(
        "StorageBlob used to hold resizable "
        "SeparateChainingHashTable is too small to meet "
        "alignment requirements of buckets.");
  } else if (buckets_ != aligned_memory_start) {
    DEV_WARNING(
        "Bucket array start position adjusted to meet alignment "
        "requirement for SeparateChainingHashTable's value type.");
    if (num_buckets_tmp * bucket_size_ > available_memory) {
      --num_buckets_tmp;
    }
  }

  // Fill in the header.
  header_->num_slots = num_slots_tmp;
  header_->num_buckets = num_buckets_tmp;
  header_->buckets_allocated.store(0, std::memory_order_relaxed);
  header_->variable_length_bytes_allocated.store(0, std::memory_order_relaxed);
  available_memory -= bucket_size_ * (header_->num_buckets);

  // Locate variable-length key storage region, and give it all the remaining
  // bytes in the blob.
  key_manager_.setVariableLengthStorageInfo(
      static_cast<char *>(buckets_) + header_->num_buckets * bucket_size_,
      available_memory,
      &(header_->variable_length_bytes_allocated));
}
Exemplo n.º 2
0
bool NetSystem::Init()
{
	WSAData wsa_data;
	int error = WSAStartup(MAKEWORD(2, 2), &wsa_data);
	if (error == 0) {
		NetMessageDefinition pingDef;
		pingDef.m_callback = PingCallback;
		pingDef.m_name = "ping";
		pingDef.m_options |= eNMO_Connectionless;
		NetMessage::RegisterMessageDefinition(0, pingDef);

		NetMessageDefinition pongDef;
		pongDef.m_callback = PongCallback;
		pongDef.m_name = "pong";
		pongDef.m_options |= eNMO_Connectionless;
		NetMessage::RegisterMessageDefinition(1, pongDef);

		NetMessageDefinition heartbeatDef;
		heartbeatDef.m_callback = HeartbeatCallback;
		heartbeatDef.m_name = "heartbeat";
		NetMessage::RegisterMessageDefinition(2, heartbeatDef);

		NetMessageDefinition ackDef;
		ackDef.m_callback = AckCallback;
		ackDef.m_name = "ack";
		NetMessage::RegisterMessageDefinition(3, ackDef);

		NetMessageDefinition joinRequest;
		joinRequest.m_callback = JoinRequestCallback;
		joinRequest.m_name = "joinrequest";
		joinRequest.m_options |= eNMO_Reliable;
		joinRequest.m_options |= eNMO_Connectionless;
		NetMessage::RegisterMessageDefinition(4, joinRequest);

		NetMessageDefinition joinAccept;
		joinAccept.m_callback = JoinAcceptCallback;
		joinAccept.m_name = "joinaccept";
		joinAccept.m_options |= eNMO_Reliable;
		NetMessage::RegisterMessageDefinition(5, joinAccept);

		NetMessageDefinition joinDeny;
		joinDeny.m_callback = JoinDenyCallback;
		joinDeny.m_name = "joindeny";
		joinDeny.m_options |= eNMO_Connectionless;
		NetMessage::RegisterMessageDefinition(6, joinDeny);

		NetMessageDefinition leave;
		leave.m_callback = LeaveCallback;
		leave.m_name = "leave";
		NetMessage::RegisterMessageDefinition(7, leave);

		NetMessageDefinition startTest;
		startTest.m_callback = StartTestCallback;
		startTest.m_name = "starttest";
		startTest.m_options |= eNMO_Reliable;
		NetMessage::RegisterMessageDefinition(8, startTest);


		NetMessageDefinition inOrderTest;
		inOrderTest.m_callback = InOrderTestCallback;
		inOrderTest.m_name = "inordertest";
		inOrderTest.m_options |= eNMO_Reliable;
		inOrderTest.m_options |= eNMO_InOrder;
		NetMessage::RegisterMessageDefinition(9, inOrderTest);

		NetMessageDefinition forceTest;
		forceTest.m_callback = ForceTestCallback;
		forceTest.m_name = "forcetest";
		forceTest.m_options |= eNMO_Reliable;
		NetMessage::RegisterMessageDefinition(10, forceTest);

		return true;
	}
	else {
		FATAL_ERROR("Could not setup WSA System");
	}

	//Create netmessage definitions here
}
 /**
  * @brief For Numeric TypeInstances, get this TypeInstance's value as a C++
  *        double.
  * @warning supportsNumericInterface() must be true and isNull() must be
  *          false for this method to be usable.
  *
  * @return The value as a double.
  **/
 virtual double numericGetDoubleValue() const {
   FATAL_ERROR("Used a Numeric interface method on a non-numeric TypeInstance.");
 }
 /**
  * @brief For Numeric TypeInstances, get this TypeInstance's value as an
  *        int64_t.
  * @warning supportsNumericInterface() must be true and isNull() must be
  *          false for this method to be usable.
  *
  * @return The value as an int64_t.
  **/
 virtual std::int64_t numericGetLongValue() const {
   FATAL_ERROR("Used a Numeric interface method on a non-numeric TypeInstance.");
 }
Exemplo n.º 5
0
std::string PlayerSAO::getStaticData()
{
	FATAL_ERROR("Deprecated function (?)");
	return "";
}
Exemplo n.º 6
0
/**
* pm_execute
* @params
*   int should_wait - Indicates if this execute should be inline or asynchronous
*   const char* command - The command to run
*   const char* cd - Run in this directory unless it's a NULL pointer
*   int nice - Special nice level
*   const char** env - Environment variables to run in the shell
* @output
    pid_t pid - output pid of the new process
**/
pid_t pm_execute(
  int should_wait, const char* command, const char *cd, int nice, const char** env, int *child_stdin, const char* p_stdout, const char *p_stderr
) {
  // Setup execution
  char **command_argv = {0};
  int command_argc = 0;
  int running_script = 0;
  int countdown = 200;
  
  // If there is nothing here, don't run anything :)
  if (strlen(command) == 0) return -1;
  
  char* chomped_string = str_chomp(command);
  char* safe_chomped_string = str_safe_quote(chomped_string);
  if (expand_command((const char*)safe_chomped_string, &command_argc, &command_argv, &running_script, env)) ;
  command_argv[command_argc] = 0;
      
  // Now actually RUN it!
  pid_t pid;
  
#if USE_PIPES

  int child_fd[2];
  if ( pipe(child_fd) < 0 ) {// Create a pipe to the child (do we need this? I doubt it)
    perror("pipe failed");
  }
  // Setup the stdin so the parent can communicate!
  (*child_stdin) = child_fd[0];
#endif

    // Let's name it so we can get to it later
  int child_dev_null;
  
#if DEBUG
  if ((child_dev_null = open("debug.log", O_WRONLY|O_CREAT|O_TRUNC,S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)) < 0) {
    syslog(LOG_ERR, "babysitter (fatal): Could not open debug.log: errno: %d\n", errno);
  };
#else
  if ((child_dev_null = open("/dev/null", O_RDWR)) < 0) {
    syslog(LOG_ERR, "babysitter (fatal): Could not open /dev/null: errno: %d\n", errno);
  };
#endif
    
  // Setup fork
  pm_setup_fork();
  
  if (should_wait)
    pid = vfork();
  else
    pid = fork();
    
  switch (pid) {
  case -1: 
    return -1;
  case 0: {
    // Child process
    pm_setup_child();
    
    if (cd != NULL && cd[0] != '\0')
      safe_chdir(cd);
    else
      safe_chdir("/tmp");
        
    int child_stdout, child_stderr;
    // Set everything to dev/null first
    child_stdout = child_stderr = child_dev_null;
    
    // If we've passed in a stdout filename, then open it
    if(p_stdout)
      if ((child_stdout = open(p_stdout, O_WRONLY|O_CREAT|O_TRUNC,S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)) < 0) {
        perror("child stdout");
        child_stdout = child_dev_null;
      }
    // If we've been passed a stderr filename, then open that
    if(p_stderr)
      if ((child_stderr = open(p_stderr, O_WRONLY|O_CREAT|O_TRUNC,S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)) < 0) {
        perror("child stderr");
        child_stderr = child_dev_null;
      }
    
    // Parent doesn't write anything to the child, so just close this right away
    // REDIRECT TO DEV/NULL
    // Replace the stdout/stderr with the child_write fd
#if USE_PIPES
    if (dup2(child_fd[0], STDIN_FILENO) < 0)       FATAL_ERROR("could not dup STDIN_FILENO", -1);
    close(child_fd[1]); // We are using a different stdout
#endif

#if DEBUG
#else
    // Setup the different stdout/stderr
    if (dup2(child_stdout, STDOUT_FILENO) < 0)  FATAL_ERROR("could not dup STDOUT_FILENO", -1);
    if (dup2(child_stderr, STDERR_FILENO) < 0)  FATAL_ERROR("could not dup STDERR_FILENO", -1);

    if (child_stdout != child_dev_null) close(child_stdout);
    if (child_stderr != child_dev_null) close(child_stderr);
#endif

    if (execve((const char*)command_argv[0], command_argv, (char* const*) env) < 0) {
      perror("execve");
      exit(-1);
    }
  }
  default:
    // In parent process
    // set the stdout back
    close(child_dev_null); // Child write never gets used outside the child
  
#if USE_PIPES
    if (dup2(child_fd[1], STDOUT_FILENO) < 0)
      perror("dup2");
    
    close(child_fd[0]);
#endif
    
    if (nice != INT_MAX && setpriority(PRIO_PROCESS, pid, nice) < 0) 
      ;
    if (running_script) {
      while (countdown > 0) {
        if (kill(pid, 0) != 0) break;
        usleep(100);
        countdown--;
      }
      struct stat buffer;
      if (stat(command_argv[0], &buffer) != 0) {
        printf("file doesn't exist when it should because: %s\n", strerror(errno));
      }
      if( unlink( command_argv[0] ) != 0 ) perror( "Error deleting file" );
    }
    // These are free'd later, anyway
    // if (chomped_string) free(chomped_string); 
    // if (safe_chomped_string) free(safe_chomped_string);
    return pid;
  }
}
void SampleLoopTask::Task(){
		
	int cnt = 0;
	int region;
	int attempt = 0;
	
	static int dout = 1;
	static double error = 0;
	
	int last_status = 0;
	double pos_prev = 0;
	double pCmd_prev = 0;
	double vCmd_prev = 0;
		
	int obj_ang_index = 0; // to keep continuous angle value when acrossing pi(or -pi).
	uint64_t cycle, cycle_prev;

	// for acceleration calculation
	double u = 0; 
	double alpha = 0;
	double DuDeta1Bar =0;
	double DuDeta2 =0; 
	double DalphaDeta1Bar =0;
	double DalphaDeta2 =0; 
	double eta1Bar = 0; 
	double z = 0;
	
	// to use eta2D in calculation of shD
	double eta2_prev = 0; 
	double eta2D = 0; 
	double eta2D_prev = 0; 
	
	double elapsedSec = 0;

	//test
	double feedforwardVal = 0;
	uint64_t cycle1, cycle2;

	while(!lost){
		TimerWait();
		
		ncycles = ClockCycles();
		sec=(double)(ncycles - ncycles_prev)/cps;
		ncycles_prev = ncycles;
		
		TimingProcess();
		
		// Read Inputs
		HW->ProcessInput(); // all digital & analog, encoders reading.
		
		// Get status of camera
		last_status = HW->ReadDigitalBit(IoHardware::FRAME_STATUS);
		
		// Send out pulse to trigger camera
		HW->WriteDigitalBit(IoHardware::CAMERA_TRIGGER, 1);
		HW->WriteDigitalBit(IoHardware::CAMERA_TRIGGER, 0);
		
		// test
		//cycle1 = ClockCycles();

		if(camera) {// && !lost){
			// Wait for camera to process data, with timeout counter
			while(HW->ReadDigitalBit(IoHardware::FRAME_STATUS) == last_status){
				if(++attempt == (int)(6.0e5/SAMPLE_RATE)) { // 5.0e5 must be found out by experiments to give the smallest time to determine an error status
					HW->SetAnalogOut(IoHardware::AMP_SIGNAL, 0.0); 
					HW->WriteDigitalBit(IoHardware::MOTOR_ENABLE, MOTOR_OFF);
					HW->motorStatus = MOTOR_OFF;
					lost = 1;
					FATAL_ERROR("Frame not received -");
					//strcpy(err_msg, "Frame not received -"); // // not work this way.
				}
			}
			attempt = 0;
			
			vnum[0] = -99;
			int n = VNET->Recv();

			region = (int)vnum[0];
			switch(region){
				case 0: //ROI_0:
					obj.x0 = vnum[1]; //mm
					obj.y0 = vnum[2]; //mm
					break;
				case 1: //ROI_1:
					obj.x1 = vnum[1]; //mm
					obj.y1 = vnum[2]; //mm
					break;
				default:
					HW->SetAnalogOut(IoHardware::AMP_SIGNAL, 0.0); 
					HW->WriteDigitalBit(IoHardware::MOTOR_ENABLE, MOTOR_OFF);
					HW->motorStatus = MOTOR_OFF;
					printf("roi-vnum[0]:%d\n", region);
					FATAL_ERROR("Object lost -");
					lost = 1;
			}
			
			obj.x = (obj.x0 + obj.x1)/2/1000; // convert to m
			obj.y = (obj.y0 + obj.y1)/2/1000;
			double obj_raw_angle = atan2(obj.y1-obj.y0, obj.x1-obj.x0); // within -pi to pi

			// to keep continuous angle value when acrossing pi(or -pi).
			obj.theta = obj_raw_angle + obj_ang_index*2*3.141592; // converted angle
			if ( fabs(obj.theta - obj.theta_prev) > 3.141592 ) {
				if (obj.theta_prev > obj.theta) // pi to -pi region change
					obj_ang_index++;
				else
					obj_ang_index--;
				obj.theta = obj_raw_angle + obj_ang_index*2*3.141592; // newly converted angle
			}
				
			// calculation of the object angular velocity
			obj.angVel = (obj.theta - obj.theta_prev) / sec; // the use of SAMPLE_RATE may not be a big difference.
			// low pass filter
			double alpha = 0.038; //0.02
			obj.angVel = alpha*obj.angVel + (1-alpha)*obj.angVel_prev;
			
			// calculation of the hand angular velocity
			handTheta = -(HW->GetEncoderCount(IoHardware::ENC_0)) * ENC_RAD_PER_CNT / GR / 4; // just access the data previously read by GetEnc...()
			handVel = (handTheta - handTheta_prev) /sec; //* SAMPLE_RATE;
			handVel = alpha*handVel + (1-alpha)*handVel_prev;
			
			// calculation of sh and \dot sh (=shD)
			sh = (obj.theta - handTheta) / K_R;
			eta2 = asin(-(obj.x-OBJ_X_OFFSET)/(RHO_H+RHO_O)); // alternative way to get eta2;

			/// test, eta2 compensation
			//eta2 = eta2 - 0.004*sin(obj.theta + 1.885); 
			
			// new method for shD, thus eta1 feedback
			eta2D = (eta2 - eta2_prev) / sec;
			eta2D = alpha*eta2D + (1-alpha)*eta2D_prev;
			shD = RHO_H*(eta2D - handVel);
			eta1 = M22*shD + M12*handVel;
			

			/*************************************************************/
			// calculation of the control input (acceleration command)
			eta1Bar = eta1 - COEFF_ETA1_STAR;
			z = handVel - TARGET_THETAHD;
			if (eta2 == 0) {
				u = -GAIN_K1*eta1Bar;
			}
			else {
				u = -GAIN_K1*eta1Bar*sin(eta2)/eta2 - GAIN_K2*eta2;
			}
			alpha = (u - COEFF_sig2*eta1Bar)/COEFF_sig3;
			if (eta2 == 0) {
				DuDeta1Bar = -GAIN_K1;
				DuDeta2 = -GAIN_K2;
			}
			else {
				DuDeta1Bar = -GAIN_K1*sin(eta2)/eta2;
				DuDeta2 = -GAIN_K1*eta1Bar*( (cos(eta2)*eta2 - sin(eta2))/(eta2*eta2) ) - GAIN_K2;
			}
			DalphaDeta1Bar = (DuDeta1Bar - COEFF_sig2)/COEFF_sig3;
			DalphaDeta2 = DuDeta2/COEFF_sig3;

			vInp = DalphaDeta1Bar*COEFF_sig1*sin(eta2) + DalphaDeta2*(COEFF_sig2*eta1Bar+COEFF_sig3*z) - eta2*COEFF_sig3 - GAIN_C*(z - alpha);
			/*************************************************************/
			aCmd = vInp; // calculated acceleration command
			
			obj.theta_prev = obj.theta;
			obj.angVel_prev = obj.angVel;
			handTheta_prev = handTheta;
			handVel_prev = handVel;
			eta2D_prev = eta2D;
			eta2_prev = eta2;
		}
		else { // Because the vision system keeps sending the data, QNX must read them, otherwise the vision system will get a send error.
			VNET->Process();
		}
		
		// test
		if (fabs(handVel) > 7.0 ) {//rad/sec
			HW->SetAnalogOut(IoHardware::AMP_SIGNAL, 0.0); 
			HW->WriteDigitalBit(IoHardware::MOTOR_ENABLE, MOTOR_OFF);
			HW->motorStatus = MOTOR_OFF;
			//VNET->Process();
			FATAL_ERROR("MOTOR RUNS TOO FAST");
			lost = 1;
		}
		
		//**************************************************************
		// reading & calculating output
		//
		// feedback
		cycle = ClockCycles();
		elapsedSec = (double)(cycle - cycle_prev)/cps;
		cycle_prev = cycle;
		
		//HW->ProcessInput(); // because of the encoder reading. Do not use this again. This takes a long time.
		enc = -(HW->ReadEncoder(IoHardware::ENC_0)); // direct read. Not working?
		pos = (enc * ENC_RAD_PER_CNT) / GR / 4; // convert to rad. GR:gear ratio (50). 4?
		vel = (pos - pos_prev) / elapsedSec; // to calculate more exact velocity.
				
		// This is necessary for not having motor run unexpectedly when swtiching from motor off to motor on.
		if(HW->motorStatus == MOTOR_ON) {
			cnt++;
	
			// acceleration inner loop
			// Notice that using no filtering velocity
			vCmd = vCmd_prev + aCmd / SAMPLE_RATE; 
			pCmd = pCmd_prev + vCmd_prev / SAMPLE_RATE + 0.5 * aCmd / (SAMPLE_RATE*SAMPLE_RATE);

			iCmd = calcI(vCmd, aCmd); // feedforward control. 
			feedforwardVal = iCmd;
			
			//iCmd += (150* (pCmd - pos) + 0.6 * (vCmd - vel) + Ki * error); // Ki 0
			//iCmd += (200* (pCmd - pos) + 0.6 * (vCmd - vel) + Ki * error); // Ki 0
			//iCmd += (350* (pCmd - pos) + 1.0 * (vCmd - vel) + Ki * error); // Ki 0
			iCmd += (150* (pCmd - pos) + 0.9 * (vCmd - vel) + Ki * error); // Ki 0
					
			pos_prev = pos;
			pCmd_prev = pCmd;
			vCmd_prev = vCmd;
		}
		else {
			iCmd = 0;
		}

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

		//**************************************************
		// control output
		// 
		//limit current based on motor specs
		if(iCmd > (MAX_CURRENT_MA) ){ // 1.6 mA
			HW->SetAnalogOut(IoHardware::AMP_SIGNAL, 0.0); 
			HW->WriteDigitalBit(IoHardware::MOTOR_ENABLE, MOTOR_OFF);
			HW->motorStatus = MOTOR_OFF;
			//VNET->Process();
			printf("iCmd:%f, pCmd:%f, pos:%f, vCmd:%f, vel:%f, aCmd:%f feedforwardVal:%f cnt:%d\n", iCmd, pCmd, pos, vCmd, vel, aCmd, feedforwardVal, cnt);
			FATAL_ERROR("MOTOR CURRENT TOO HIGH");
			lost = 1;
			iCmd = MAX_CURRENT_MA;
		}
		else if(iCmd < (-MAX_CURRENT_MA) ){
			HW->SetAnalogOut(IoHardware::AMP_SIGNAL, 0.0); 
			HW->WriteDigitalBit(IoHardware::MOTOR_ENABLE, MOTOR_OFF);
			HW->motorStatus = MOTOR_OFF;
			//VNET->Process();
			printf("iCmd:%f, pCmd:%f, pos:%f, vCmd:%f, vel:%f, aCmd:%f feedforwardVal:%f cnt:%d%f\n", iCmd, pCmd, pos, vCmd, vel, aCmd, feedforwardVal, cnt);
			FATAL_ERROR("MOTOR CURRENT TOO HIGH");
			lost = 1;
			iCmd = -MAX_CURRENT_MA;
		}
		
		ampVCmd =-iCmd * AMP_GAIN; // convert to analog signal. +-10 V.  -0.86 for 4.5 rad/s. for test use -0.8
		// sign change to agree with camera
		
		// output signal to amp
		if(!done){
			HW->WriteAnalogCh(IoHardware::AMP_SIGNAL, ampVCmd);
			//HW->WriteAnalogCh(IoHardware::AMP_SIGNAL, 0.0);
		}
		else{
			HW->WriteAnalogCh(IoHardware::AMP_SIGNAL, 0.0);
		}
		//*******************************************************

		//**************************************************
	
		HW->ProcessOutput(); // all digital & analog writing.

		// set outputs
		/*num[0] = obj.theta; 
		num[1] = obj.angVel;
		*/
		num[0] = vInp;//obj.theta; //vInp; //correctedAcc; //eta1; //handVel; //pos; //handTheta; //pos; // angle in rad
		num[1] = eta1;//obj.angVel; //eta1; //feedforwardVal; //pCmd; //eta2; //obj.theta; //vnum[0]; //obj.theta; //vel; //obj.theta;

		num[2] = pos; //feedbackVal; //vCmd; //obj.angVel; //obj.x; //vnum[1]; //obj.x1; //ampVCmd; //obj.x1; // position in m, *10 for cm
		num[3] = eta2; //handTheta; //iCmd; //sec; //elapsedSec; //sec; //vnum[2]; //obj.y1;
	
		MNET->Process();

	} // while()
	
	// for some reason, this does not work.
	HW->SetAnalogOut(IoHardware::AMP_SIGNAL, 0.0); 
	HW->WriteDigitalBit(IoHardware::MOTOR_ENABLE, MOTOR_OFF);
	HW->motorStatus = MOTOR_OFF;
	delay(10);
	FATAL_ERROR(err_msg);
	
}
Exemplo n.º 8
0
OCLAcceleratorMatrixCOO<ValueType>::OCLAcceleratorMatrixCOO() {

  // no default constructors
  FATAL_ERROR(__FILE__, __LINE__);

}
Exemplo n.º 9
0
static bool ParseFile(FILE *pFile) {
    uint8_t size;

    if(pFile == NULL) {
        FATAL_ERROR();
        return false;
    }

    fread(&size, sizeof(char), 1, pFile);
    fread(room.title, sizeof(char), size, pFile);
    room.title[size] = '\0';
    fread(&size, sizeof(char), 1, pFile);
    if(size == 0) {
        room.itemRequirements = 0;
    } else {
        fread(&room.itemRequirements, sizeof(char), size, pFile);
    }

    while(!FindInInventory(room.itemRequirements) || room.itemRequirements) {
        fread(&size, sizeof(char), 1, pFile);
        fseek(pFile, size, SEEK_CUR);

        fread(&size, sizeof(char), 1, pFile);
        fread(&room.itemsContained, sizeof(char), size, pFile);

        fseek(pFile, 4, SEEK_CUR);
        fread(&size, sizeof(char), 1, pFile);
        if(size == 0) {
            room.itemRequirements = 0;
        } else {
            fread(&room.itemRequirements, sizeof(char), size, pFile);
        }
    }
    fread(&size, sizeof(char), 1, pFile);
    fread(room.description, sizeof(char), size, pFile);
    room.description[size] = '\0';

    fread(&size, sizeof(char), 1, pFile);
    if(size != 0) {
        fread(&room.itemsContained, sizeof(char), size, pFile);
        AddToInventory(room.itemsContained);
    } else {
        room.itemsContained = 0;
    }

    fread(&room.north, sizeof(uint8_t), 1, pFile);
    fread(&room.east, sizeof(uint8_t), 1, pFile);
    fread(&room.south, sizeof(uint8_t), 1, pFile);
    fread(&room.west, sizeof(uint8_t), 1, pFile);

    room.roomExits = 0;

    if(room.north) {
        room.roomExits |= GAME_ROOM_EXIT_NORTH_EXISTS;
    }
    if(room.east) {
        room.roomExits |= GAME_ROOM_EXIT_NORTH_EXISTS;
    }
    if(room.south) {
        room.roomExits |= GAME_ROOM_EXIT_SOUTH_EXISTS;
    }
    if(room.west) {
        room.roomExits |= GAME_ROOM_EXIT_WEST_EXISTS;
    }

    fclose(pFile);
    return true;
}
Exemplo n.º 10
0
void load_conf(void)
{
    FILE *fc;
    char line[128];
    char *p, *q, **tmp;
    int lineno = 0;
    struct conf_entry *curr_section = NULL;
    void *value = NULL;

    /* initialize the structures */
    init_structures();

    DEBUG_MSG("load_conf");

    /* the user has specified an alternative config file */
    if (GBL_CONF->file) {
        DEBUG_MSG("load_conf: alternative config: %s", GBL_CONF->file);
        fc = fopen(GBL_CONF->file, FOPEN_READ_TEXT);
        ON_ERROR(fc, NULL, "Cannot open %s", GBL_CONF->file);
    } else {
        /* errors are handled by the function */
        fc = open_data("etc", ETTER_CONF, FOPEN_READ_TEXT);
        ON_ERROR(fc, NULL, "Cannot open %s", ETTER_CONF);
    }

    /* read the file */
    while (fgets(line, 128, fc) != 0) {

        /* update the line count */
        lineno++;

        /* trim out the comments */
        if ((p = strchr(line, '#')))
            *p = '\0';

        /* trim out the new line */
        if ((p = strchr(line, '\n')))
            *p = '\0';

        q = line;

        /* trim the initial spaces */
        while (q < line + sizeof(line) && *q == ' ')
            q++;

        /* skip empty lines */
        if (line[0] == '\0' || *q == '\0')
            continue;

        /* here starts a new section [...] */
        if (*q == '[') {

            /* remove the square brackets */
            if ((p = strchr(line, ']')))
                *p = '\0';
            else
                FATAL_ERROR("Missing ] in %s line %d", ETTER_CONF, lineno);

            p = q + 1;

            DEBUG_MSG("load_conf: SECTION: %s", p);

            /* get the pointer to the right structure */
            if ( (curr_section = search_section(p)) == NULL)
                FATAL_ERROR("Invalid section in %s line %d", ETTER_CONF, lineno);

            /* read the next line */
            continue;
        }

        /* variable outside a section */
        if (curr_section == NULL)
            FATAL_ERROR("Entry outside a section in %s line %d", ETTER_CONF, lineno);

        /* sanity check */
        if (!strchr(q, '='))
            FATAL_ERROR("Parse error %s line %d", ETTER_CONF, lineno);

        p = q;

        /* split the entry name from the value */
        do {
            if (*p == ' ' || *p == '=') {
                *p = '\0';
                break;
            }
        } while (p++ < line + sizeof(line) );

        /* move p to the value */
        p++;
        do {
            if (*p != ' ' && *p != '=')
                break;
        } while (p++ < line + sizeof(line) );

        /*
         * if it is the "dissector" section,
         * do it in a different way
         */
        if (curr_section == (struct conf_entry *)&dissectors) {
            set_dissector(q, p, lineno);
            continue;
        }

        /* search the entry name */
        if ( (value = search_entry(curr_section, q)) == NULL)
            FATAL_ERROR("Invalid entry in %s line %d", ETTER_CONF, lineno);

        /* strings must be handled in a different way */
        if (curr_section == (struct conf_entry *)&strings) {
            /* trim the quotes */
            if (*p == '\"')
                p++;

            /* set the string value */
            tmp = (char **)value;
            *tmp = strdup(p);

            /* trim the ending quotes */
            p = *tmp;
            do {
                if (*p == '\"')
                    *p = 0;
            } while (p++ < *tmp + strlen(*tmp) );

            DEBUG_MSG("load_conf: \tENTRY: %s  [%s]", q, *tmp);
        } else {
            /* set the integer value */
            *(int *)value = strtol(p, (char **)NULL, 10);
            DEBUG_MSG("load_conf: \tENTRY: %s  %d", q, *(int *)value);
        }
    }

    fclose(fc);
}
Exemplo n.º 11
0
  /*
   * Each processor:
   *   owns a set of pins (nonzeros)
   *   may provide some edge weights
   *
   * We assume that no two processes will supply the same pin.
   * But more than one process may supply pins for the same edge.
   */
static int
matrix_get_edges(ZZ *zz, Zoltan_matrix *matrix, ZOLTAN_ID_PTR *yGID, ZOLTAN_ID_PTR *pinID, int nX,
		 ZOLTAN_ID_PTR *xGID, ZOLTAN_ID_PTR *xLID, int **xGNO, float **xwgt)
{
  static char *yo = "Zoltan_Matrix_Build";
  int ierr = ZOLTAN_OK;
  int hypergraph_callbacks = 0, graph_callbacks = 0;
  int *nbors_proc = NULL; /* Pointers are global for the function to ensure proper free */
  int *edgeSize = NULL;

  ZOLTAN_TRACE_ENTER(zz, yo);
  if (zz->Get_HG_Size_CS && zz->Get_HG_CS) {
    hypergraph_callbacks = 1;
  }
  if ((zz->Get_Num_Edges != NULL || zz->Get_Num_Edges_Multi != NULL) &&
           (zz->Get_Edge_List != NULL || zz->Get_Edge_List_Multi != NULL)) {
    graph_callbacks = 1;
  }

  if (graph_callbacks && hypergraph_callbacks){
/*     if (hgraph_model == GRAPH) */
/*       hypergraph_callbacks = 0; */
    graph_callbacks = 1; /* I prefer graph (allow to do "inplace") ! */
  }

  if (hypergraph_callbacks) {
    matrix->redist = 1;
    if (matrix->opts.speed == MATRIX_FULL_DD)
      ZOLTAN_FREE(xGID);
    else
      *xGID = NULL;
    ZOLTAN_FREE(xLID);
    ZOLTAN_FREE(xGNO);

    ierr = Zoltan_Hypergraph_Queries(zz, &matrix->nY,
				     &matrix->nPins, yGID, &matrix->ystart,
				     pinID);
    CHECK_IERR;
    matrix->yend = matrix->ystart + 1;
  }
  else if (graph_callbacks) {
    int max_edges = 0;
    int vertex;
    int numGID, numLID;


    matrix->opts.enforceSquare = 1;
    matrix->nY = nX; /* It is square ! */
    matrix->yGNO = *xGNO;
    *xGNO = NULL;
    *yGID = NULL;
    matrix->ywgtdim = zz->Obj_Weight_Dim;
    *xwgt = NULL;

    numGID = zz->Num_GID;
    numLID = zz->Num_LID;

    /* TODO : support local graphs */
    /* TODO : support weights ! */
    /* Get edge data */
    Zoltan_Get_Num_Edges_Per_Obj(zz, matrix->nY, *xGID, *xLID,
				 &edgeSize, &max_edges, &matrix->nPins);

    (*pinID) = ZOLTAN_MALLOC_GID_ARRAY(zz, matrix->nPins);
    nbors_proc = (int *)ZOLTAN_MALLOC(matrix->nPins * sizeof(int));

    if (matrix->nPins && ((*pinID) == NULL || nbors_proc == NULL))
      MEMORY_ERROR;

    matrix->pinwgt = (float*)ZOLTAN_MALLOC(matrix->nPins*matrix->pinwgtdim*sizeof(float));
    if (matrix->nPins && matrix->pinwgtdim && matrix->pinwgt == NULL)
      MEMORY_ERROR;

    if (zz->Get_Edge_List_Multi) {
      zz->Get_Edge_List_Multi(zz->Get_Edge_List_Multi_Data,
			      numGID, numLID,
			      matrix->nY, *xGID, *xLID,
			      edgeSize,
			      (*pinID), nbors_proc, matrix->pinwgtdim,
			      matrix->pinwgt, &ierr);
    }
    else {
      int edge;
      for (vertex = 0, edge = 0 ; vertex < matrix->nY ; ++vertex) {
	zz->Get_Edge_List(zz->Get_Edge_List_Data, numGID, numLID,
                          (*xGID)+vertex*numGID, (*xLID)+vertex*numLID,
                          (*pinID)+edge*numGID, nbors_proc+edge, matrix->pinwgtdim,
                          matrix->pinwgt+edge*matrix->pinwgtdim, &ierr);
	edge += edgeSize[vertex];
      }
    }
    CHECK_IERR;

    /* Not Useful anymore */
    ZOLTAN_FREE(xLID);
    if (matrix->opts.speed == MATRIX_FULL_DD)
      ZOLTAN_FREE(xGID);
    else
      *xGID = NULL;
    ZOLTAN_FREE(&nbors_proc);

    /* Now construct CSR indexing */
    matrix->ystart = (int*) ZOLTAN_MALLOC((matrix->nY+1)*sizeof(int));
    if (matrix->ystart == NULL)
      MEMORY_ERROR;

    matrix->ystart[0] = 0;
    matrix->yend = matrix->ystart + 1;
    for (vertex = 0 ; vertex < matrix->nY ; ++vertex)
      matrix->ystart[vertex+1] = matrix->ystart[vertex] + edgeSize[vertex];
  }
  else {
    FATAL_ERROR ("You have to define Hypergraph or Graph queries");
  }

  if (matrix->opts.enforceSquare) {
    matrix->globalY = matrix->globalX;
    matrix->ddY = matrix->ddX;
    matrix->ywgtdim = zz->Obj_Weight_Dim;
  }

 End:
  ZOLTAN_FREE(&edgeSize);
  ZOLTAN_FREE(&nbors_proc);
  ZOLTAN_FREE(xLID);
  ZOLTAN_FREE(xGID);
  ZOLTAN_FREE(xGNO);
  ZOLTAN_FREE(xwgt);

  ZOLTAN_TRACE_EXIT(zz, yo);

  return (ierr);
}
Exemplo n.º 12
0
/**
 * This function calls ButtonsCheckEvents() once per call and returns which, if any,
 * of the Morse code events listed in the enum above have been encountered. It checks for BTN4
 * events in its input and should be called at 100Hz so that the timing works. The
 * length that BTN4 needs to be held down for a dot is >= 0.25s and < 0.50s with a dash being a button
 * down event for >= 0.5s. The button uptime various between dots/dashes (>= .5s), letters
 * (>= 1s), and words (>= 2s).
 *
 * @note This function assumes that the buttons are all unpressed at startup, so that the first
 *       event it will see is a BUTTON_EVENT_*DOWN.
 *
 * So pressing the button for 0.1s, releasing it for 0.1s, pressing it for 0.3s, and then waiting
 * will decode the string '.-' (A). It will trigger the following order of events:
 * 9 MORSE_EVENT_NONEs, 1 MORSE_EVENT_DOT, 39 MORSE_EVENT_NONEs, a MORSE_EVENT_DASH, 69
 * MORSE_EVENT_NONEs, a MORSE_EVENT_END_CHAR, and then MORSE_EVENT_INTER_WORDs.
 *
 * @return The MorseEvent that occurred.
 */
MorseEvent MorseCheckEvents(void) {

    switch (myState) {
        case(WAITING):
        {// if in the state of waiting
            if (ButtonsCheckEvents() == BUTTON_EVENT_4DOWN) {
                myState = DOT;
                myCount = 0;
            }
            return MORSE_EVENT_NONE;
            break;
        }
        case(DOT):
        {
            // in the state of dot
            myCount += 1;
            if (myCount >= MORSE_EVENT_LENGTH_DOWN_DOT) {
                myState = DASH;
            }
            if (ButtonsCheckEvents() == BUTTON_EVENT_4UP) {
                // Chenge into Inter letter
                myState = INTER_LETTER;
                myCount = 0;
                return MORSE_EVENT_DOT;

            }
            return MORSE_EVENT_NONE;
            break;
        }
        case(DASH):
        {
            //in Dash state
            if (ButtonsCheckEvents() == BUTTON_EVENT_4UP) {
                // change my state to Inter letter
                myState = INTER_LETTER;
                myCount = 0;
                return MORSE_EVENT_DASH;

            }
            return MORSE_EVENT_NONE;
            break;
        }
        case(INTER_LETTER):
        {
            //In the inter letter state
            myCount += 1;
            if (myCount > MORSE_EVENT_LENGTH_UP_INTER_WORD) {
                //if inter letter time out, we go to
                myState = WAITING;
                return MORSE_EVENT_INTER_WORD;
            } else if (ButtonsCheckEvents() == BUTTON_EVENT_4DOWN) {
                //
                if (myCount > MORSE_EVENT_LENGTH_UP_INTER_LETTER) {
                    myCount = 0;
                    myState = DOT;
                    // return inter ltter event 
                    return MORSE_EVENT_INTER_LETTER;
                }
                myCount = 0;
                myState = DOT;
            }
            return MORSE_EVENT_NONE;
            break;
        }
        default:
        {
            //In the deflaut state
            FATAL_ERROR();
            break;
        }
    }
}
Exemplo n.º 13
0
int main(void)
{
    // Watchdog Timer Enabled/disabled by user software
    // (LPRC can be disabled by clearing SWDTEN bit in RCON registe

    // Configure Oscillator to operate the device at 40Mhz
    // Fosc= Fin*M/(N1*N2), Fcy=Fosc/2
    // Fosc= 8M*40/(2*2)=80Mhz for 8M input clock
    PLLFBD = 38; // M=40
    CLKDIVbits.PLLPOST = 0; // N1=2
    CLKDIVbits.PLLPRE = 0; // N2=2
    OSCTUN = 0; // Tune FRC oscillator, if FRC is used

    RCONbits.SWDTEN = 0; /* Disable Watch Dog Timer*/

    // Clock switch to incorporate PLL
    __builtin_write_OSCCONH(0x03); // Initiate Clock Switch to Primary
    // Oscillator with PLL (NOSC=0b011)
    __builtin_write_OSCCONL(0x01); // Start clock switching
    while (OSCCONbits.COSC != 0b011); // Wait for Clock switch to occur

    while (OSCCONbits.LOCK != 1) {
    }; /* Wait for PLL to lock*/

//    bufferPointer = NULL;
    Uart2Init(InterruptRoutine);

    if (!CB_Init(&circBuf, cbData, CB_SIZE)) FATAL_ERROR();

    // Generate a fake input to record to the circular buffer
    // give beginning and end special characters
    unsigned char goodData[512];
    int i;
    for (i=0; i<512; i++) {
        goodData[i] = (char)i;
    }
    goodSum = checksum(goodData, 512);
    
    Uart2PrintStr("Begin.\n");
    file = NewSDInit("newfile.txt");

    int SDConnected = 0;
    while(1)
    {
//        if (bufferPointer != NULL) { TODO implement this?
//            CB_WriteMany(&circBuf, bufferPointer, UART2_BUFFER_SIZE, 1); // the 1 is arbitrary
//            bufferPointer = NULL;
//        }
        if (SD_IN)
        {
            // if the board was just plugged in try to reinitialize
            if(!SDConnected) {
                MEDIA_INFORMATION * Minfo;
                do {
                    Minfo = MDD_MediaInitialize();
                } while(Minfo->errorCode == MEDIA_CANNOT_INITIALIZE);
                SDConnected = 1;
            }
            // When we are connected and initialized, poll the buffer, if there
            // is data, write it.
            unsigned char outData[SD_SECTOR_SIZE];
            if (CB_PeekMany(&circBuf, outData, SD_SECTOR_SIZE)){
                if(NewSDWriteSector(file, outData)){
                    // Remove the data we just written.
                    if(checksum(outData, 512) != goodSum) {
                        FATAL_ERROR();
                    }
                    CB_Remove(&circBuf, SD_SECTOR_SIZE);
                }
            }
        } else {
            SDConnected = 0;
        }
    }
}
Exemplo n.º 14
0
/*
 * concatenate two (or more) files into one single file 
 */
void concatenate(int argc, char **argv)
{
   int zerr;
   gzFile fd;
   struct log_global_header hdr, tmp;

   memset(&hdr, 0, sizeof(struct log_global_header));

   /* open the output file for writing */
   fd = gzopen(GBL_LOGFILE, "wb");
   ON_ERROR(fd, NULL, "%s", gzerror(fd, &zerr));

   /* 
    * use GBL_LOG_FD here so the get_header function
    * will use this file 
    */
   GBL_LOG_FD = gzopen(argv[argc], "rb");
   ON_ERROR(GBL_LOG_FD, NULL, "%s", gzerror(GBL_LOG_FD, &zerr));
   
   /* get the file header */
   if (get_header(&hdr) != E_SUCCESS)
      FATAL_ERROR("Invalid log file (%s)", argv[argc]);

   /* write the header */
   put_header(fd, &hdr);
      
   printf("Concatenating file [%s]", argv[argc]);
   
   /* copy the first file into the output */
   dump_file(fd, &hdr);
     
   /* move the pointer to the next file */
   argc++;
   
   /* cicle thru the file list */
   while(argv[argc] != NULL) {
   
      GBL_LOG_FD = gzopen(argv[argc], "rb");
      ON_ERROR(GBL_LOG_FD, NULL, "%s", gzerror(GBL_LOG_FD, &zerr));
   
      /* get the file header */
      if (get_header(&tmp) != E_SUCCESS)
         FATAL_ERROR("Invalid log file (%s)", argv[argc]);
     
      /* check if the files are compatible */
      if (hdr.type != tmp.type)
         FATAL_ERROR("Cannot concatenate different type of file");

      printf("Concatenating file [%s]", argv[argc]);
      
      /* concatenate this file */
      dump_file(fd, &tmp);

      gzclose(GBL_LOG_FD);
      argc++;
   }

   gzclose(fd);

   printf("\nAll files concatenated into: %s\n\n", GBL_LOGFILE);

   exit(0);
}
Exemplo n.º 15
0
void initializePaths()
{
#if RUN_IN_PLACE
	char buf[BUFSIZ];

	infostream << "Using relative paths (RUN_IN_PLACE)" << std::endl;

	bool success =
		getCurrentExecPath(buf, sizeof(buf)) ||
		getExecPathFromProcfs(buf, sizeof(buf));

	if (success) {
		pathRemoveFile(buf, DIR_DELIM_CHAR);
		std::string execpath(buf);

		path_share = execpath + DIR_DELIM "..";
		path_user  = execpath + DIR_DELIM "..";

		if (detectMSVCBuildDir(execpath)) {
			path_share += DIR_DELIM "..";
			path_user  += DIR_DELIM "..";
		}
	} else {
		errorstream << "Failed to get paths by executable location, "
			"trying cwd" << std::endl;

		if (!getCurrentWorkingDir(buf, sizeof(buf)))
			FATAL_ERROR("Ran out of methods to get paths");

		size_t cwdlen = strlen(buf);
		if (cwdlen >= 1 && buf[cwdlen - 1] == DIR_DELIM_CHAR) {
			cwdlen--;
			buf[cwdlen] = '\0';
		}

		if (cwdlen >= 4 && !strcmp(buf + cwdlen - 4, DIR_DELIM "bin"))
			pathRemoveFile(buf, DIR_DELIM_CHAR);

		std::string execpath(buf);

		path_share = execpath;
		path_user  = execpath;
	}
	path_cache = path_user + DIR_DELIM + "cache";
#else
	infostream << "Using system-wide paths (NOT RUN_IN_PLACE)" << std::endl;

	if (!setSystemPaths())
		errorstream << "Failed to get one or more system-wide path" << std::endl;

	// Initialize path_cache
	// First try $XDG_CACHE_HOME/PROJECT_NAME
	const char *cache_dir = getenv("XDG_CACHE_HOME");
	const char *home_dir = getenv("HOME");
	if (cache_dir) {
		path_cache = std::string(cache_dir) + DIR_DELIM + PROJECT_NAME;
	} else if (home_dir) {
		// Then try $HOME/.cache/PROJECT_NAME
		path_cache = std::string(home_dir) + DIR_DELIM + ".cache"
			+ DIR_DELIM + PROJECT_NAME;
	} else {
		// If neither works, use $PATH_USER/cache
		path_cache = path_user + DIR_DELIM + "cache";
	}
	// Migrate cache folder to new location if possible
	migrateCachePath();
#endif

	infostream << "Detected share path: " << path_share << std::endl;
	infostream << "Detected user path: " << path_user << std::endl;
	infostream << "Detected cache path: " << path_cache << std::endl;

#if USE_GETTEXT
	bool found_localedir = false;
#  ifdef STATIC_LOCALEDIR
	if (STATIC_LOCALEDIR[0] && fs::PathExists(STATIC_LOCALEDIR)) {
		found_localedir = true;
		path_locale = STATIC_LOCALEDIR;
		infostream << "Using locale directory " << STATIC_LOCALEDIR << std::endl;
	} else {
		path_locale = getDataPath("locale");
		if (fs::PathExists(path_locale)) {
			found_localedir = true;
			infostream << "Using in-place locale directory " << path_locale
				<< " even though a static one was provided "
				<< "(RUN_IN_PLACE or CUSTOM_LOCALEDIR)." << std::endl;
		}
	}
#  else
	path_locale = getDataPath("locale");
	if (fs::PathExists(path_locale)) {
		found_localedir = true;
	}
#  endif
	if (!found_localedir) {
		warningstream << "Couldn't find a locale directory!" << std::endl;
	}
#endif  // USE_GETTEXT
}
Exemplo n.º 16
0
void parse_options(int argc, char **argv)
{
   int c;

   static struct option long_options[] = {
      { "help", no_argument, NULL, 'h' },
      { "version", no_argument, NULL, 'v' },
      
      { "iface", required_argument, NULL, 'i' },
      { "iflist", no_argument, NULL, 'I' },
      { "netmask", required_argument, NULL, 'n' },
      { "write", required_argument, NULL, 'w' },
      { "read", required_argument, NULL, 'r' },
      { "pcapfilter", required_argument, NULL, 'f' },
      
      { "reversed", no_argument, NULL, 'R' },
      { "proto", required_argument, NULL, 't' },
      
      { "plugin", required_argument, NULL, 'P' },
      
      { "filter", required_argument, NULL, 'F' },
      
      { "superquiet", no_argument, NULL, 'Q' },
      { "quiet", no_argument, NULL, 'q' },
      { "script", required_argument, NULL, 's' },
      { "silent", no_argument, NULL, 'z' },
      { "unoffensive", no_argument, NULL, 'u' },
      { "load-hosts", required_argument, NULL, 'j' },
      { "save-hosts", required_argument, NULL, 'k' },
      { "wep-key", required_argument, NULL, 'W' },
      { "config", required_argument, NULL, 'a' },
      
      { "dns", no_argument, NULL, 'd' },
      { "regex", required_argument, NULL, 'e' },
      { "visual", required_argument, NULL, 'V' },
      { "ext-headers", no_argument, NULL, 'E' },
      
      { "log", required_argument, NULL, 'L' },
      { "log-info", required_argument, NULL, 'l' },
      { "log-msg", required_argument, NULL, 'm' },
      { "compress", no_argument, NULL, 'c' },
      
      { "text", no_argument, NULL, 'T' },
      { "curses", no_argument, NULL, 'C' },
      { "gtk", no_argument, NULL, 'G' },
      { "daemon", no_argument, NULL, 'D' },
      
      { "mitm", required_argument, NULL, 'M' },
      { "only-mitm", no_argument, NULL, 'o' },
      { "bridge", required_argument, NULL, 'B' },
      { "promisc", no_argument, NULL, 'p' },
      
      { 0 , 0 , 0 , 0}
   };


#ifdef HAVE_GTK 
      if (strcmp(argv[0], "ettercap-gtk") == 0)
          select_gtk_interface();
#endif
#ifdef HAVE_NCURSES 
      if (strcmp(argv[0], "ettercap-curses") == 0)
          select_curses_interface();
#endif
      if (strcmp(argv[0], "ettercap-text") == 0)
          select_text_interface();

   for (c = 0; c < argc; c++)
      DEBUG_MSG("parse_options -- [%d] [%s]", c, argv[c]);

   
/* OPTIONS INITIALIZATION */
   
   GBL_PCAP->promisc = 1;
   GBL_FORMAT = &ascii_format;

/* OPTIONS INITIALIZED */
   
   optind = 0;

   while ((c = getopt_long (argc, argv, "a:B:CchDdEe:F:f:GhIi:j:k:L:l:M:m:n:oP:pQqiRr:s:Tt:UuV:vW:w:z", long_options, (int *)0)) != EOF) {

      switch (c) {

         case 'M':
                  GBL_OPTIONS->mitm = 1;
                  if (mitm_set(optarg) != ESUCCESS)
                     FATAL_ERROR("MITM method '%s' not supported...\n", optarg);
                  break;
                  
         case 'o':
                  GBL_OPTIONS->only_mitm = 1;
                  //select_text_interface();
                  break;
                  
         case 'B':
                  GBL_OPTIONS->iface_bridge = strdup(optarg);
                  set_bridge_sniff();
                  break;
                  
         case 'p':
                  GBL_PCAP->promisc = 0;
                  break;
                 
         case 'T':
                  select_text_interface();
                  break;
                  
         case 'C':
#ifdef HAVE_NCURSES 
                  select_curses_interface();
#else
            fprintf(stdout, "\nncurses-interface not supported.\n\n");
            clean_exit(-1);
#endif
                  break;
         case 'G':
#ifdef HAVE_GTK
                  select_gtk_interface();
#else
            fprintf(stdout, "\nGTK-Interface not supported.\n\n");
            clean_exit(-1);
#endif
                  break;
         
         case 'D':
                  select_daemon_interface();
                  break;
                  
         case 'R':
                  GBL_OPTIONS->reversed = 1;
                  break;
                  
         case 't':
                  GBL_OPTIONS->proto = strdup(optarg);
                  break;
                  
         case 'P':
                  /* user has requested the list */
                  if (!strcasecmp(optarg, "list")) {
                     plugin_list();
                     clean_exit(0);
                  }
                  /* else set the plugin */
                  GBL_OPTIONS->plugin = strdup(optarg);
                  break;
                  
         case 'i':
                  GBL_OPTIONS->iface = strdup(optarg);
                  break;
                  
         case 'I':
                  /* this option is only useful in the text interface */
                  select_text_interface();
                  GBL_OPTIONS->iflist = 1;
                  break;
         
         case 'n':
                  GBL_OPTIONS->netmask = strdup(optarg);
                  break;
                  
         case 'r':
                  /* we don't want to scan the lan while reading from file */
                  GBL_OPTIONS->silent = 1;
                  GBL_OPTIONS->read = 1;
                  GBL_OPTIONS->pcapfile_in = strdup(optarg);
                  break;
                 
         case 'w':
                  GBL_OPTIONS->write = 1;
                  GBL_OPTIONS->pcapfile_out = strdup(optarg);
                  break;
                  
         case 'f':
                  GBL_PCAP->filter = strdup(optarg);
                  break;
                  
         case 'F':
                  if (filter_load_file(optarg, GBL_FILTERS) != ESUCCESS)
                     FATAL_ERROR("Cannot load filter file \"%s\"", optarg);
                  break;
                  
         case 'L':
                  if (set_loglevel(LOG_PACKET, optarg) == -EFATAL)
                     clean_exit(-EFATAL);
                  break;

         case 'l':
                  if (set_loglevel(LOG_INFO, optarg) == -EFATAL)
                     clean_exit(-EFATAL);
                  break;

         case 'm':
                  if (set_msg_loglevel(LOG_TRUE, optarg) == -EFATAL)
                     clean_exit(-EFATAL);
                  break;
                  
         case 'c':
                  GBL_OPTIONS->compress = 1;
                  break;

         case 'e':
                  if (set_regex(optarg) == -EFATAL)
                     clean_exit(-EFATAL);
                  break;
         
         case 'Q':
                  GBL_OPTIONS->superquiet = 1;
                  /* no break, quiet must be enabled */
         case 'q':
                  GBL_OPTIONS->quiet = 1;
                  break;
                  
         case 's':
                  GBL_OPTIONS->script = strdup(optarg);
                  break;
                  
         case 'z':
                  GBL_OPTIONS->silent = 1;
                  break;
                  
         case 'u':
                  GBL_OPTIONS->unoffensive = 1;
                  break;
                  
         case 'd':
                  GBL_OPTIONS->resolve = 1;
                  break;
                  
         case 'j':
                  GBL_OPTIONS->silent = 1;
                  GBL_OPTIONS->load_hosts = 1;
                  GBL_OPTIONS->hostsfile = strdup(optarg);
                  break;
                  
         case 'k':
                  GBL_OPTIONS->save_hosts = 1;
                  GBL_OPTIONS->hostsfile = strdup(optarg);
                  break;
                  
         case 'V':
                  if (set_format(optarg) != ESUCCESS)
                     clean_exit(-EFATAL);
                  break;
                  
         case 'E':
                  GBL_OPTIONS->ext_headers = 1;
                  break;
                  
         case 'W':
                  set_wep_key(optarg);
                  break;
                  
         case 'a':
                  GBL_CONF->file = strdup(optarg);
                  break;
                  
         case 'h':
                  ec_usage();
                  break;

         case 'v':
                  printf("%s %s\n", GBL_PROGRAM, GBL_VERSION);
                  clean_exit(0);
                  break;

         case ':': // missing parameter
            fprintf(stdout, "\nTry `%s --help' for more options.\n\n", GBL_PROGRAM);
            clean_exit(-1);
         break;

         case '?': // unknown option
            fprintf(stdout, "\nTry `%s --help' for more options.\n\n", GBL_PROGRAM);
            clean_exit(-1);
         break;
      }
   }

   DEBUG_MSG("parse_options: options parsed");
   
   /* TARGET1 and TARGET2 parsing */
   if (argv[optind]) {
      GBL_OPTIONS->target1 = strdup(argv[optind]);
      DEBUG_MSG("TARGET1: %s", GBL_OPTIONS->target1);
      
      if (argv[optind+1]) {
         GBL_OPTIONS->target2 = strdup(argv[optind+1]);
         DEBUG_MSG("TARGET2: %s", GBL_OPTIONS->target2);
      }
   }

   /* create the list form the TARGET format (MAC/IPrange/PORTrange) */
   compile_display_filter();
   
   DEBUG_MSG("parse_options: targets parsed");
   
   /* check for other options */
   
   if (GBL_SNIFF->start == NULL)
      set_unified_sniff();
   
   if (GBL_OPTIONS->read && GBL_PCAP->filter)
      FATAL_ERROR("Cannot read from file and set a filter on interface");
   
   if (GBL_OPTIONS->read && GBL_SNIFF->type != SM_UNIFIED )
      FATAL_ERROR("You can read from a file ONLY in unified sniffing mode !");
   
   if (GBL_OPTIONS->mitm && GBL_SNIFF->type != SM_UNIFIED )
      FATAL_ERROR("You can't do mitm attacks in bridged sniffing mode !");

   if (GBL_SNIFF->type == SM_BRIDGED && GBL_PCAP->promisc == 0)
      FATAL_ERROR("During bridged sniffing the iface must be in promisc mode !");
   
   if (GBL_OPTIONS->quiet && GBL_UI->type != UI_TEXT)
      FATAL_ERROR("The quiet option is useful only with text only UI");
  
   if (GBL_OPTIONS->load_hosts && GBL_OPTIONS->save_hosts)
      FATAL_ERROR("Cannot load and save at the same time the hosts list...");
  
   if (GBL_OPTIONS->unoffensive && GBL_OPTIONS->mitm)
      FATAL_ERROR("Cannot use mitm attacks in unoffensive mode");
   
   if (GBL_OPTIONS->read && GBL_OPTIONS->mitm)
      FATAL_ERROR("Cannot use mitm attacks while reading from file");
   
   if (GBL_UI->init == NULL) {
      FATAL_ERROR("Please select an User Interface");
    }
     
   /* force text interface for only mitm attack */
   //if (GBL_OPTIONS->only_mitm) {
   //   if (GBL_OPTIONS->mitm)
   //      select_text_interface();
   //   else
   //      FATAL_ERROR("Only mitm requires at least one mitm method");
   //}

   DEBUG_MSG("parse_options: options combination looks good");
   
   return;
}
Exemplo n.º 17
0
void OCLAcceleratorMatrixCOO<ValueType>::CopyTo(BaseMatrix<ValueType> *dst) const {

  OCLAcceleratorMatrixCOO<ValueType> *ocl_cast_mat;
  HostMatrix<ValueType> *host_cast_mat;

  // copy only in the same format
  assert(this->get_mat_format() == dst->get_mat_format());

  // OCL to OCL copy
  if ((ocl_cast_mat = dynamic_cast<OCLAcceleratorMatrixCOO<ValueType>*> (dst)) != NULL) {

    ocl_cast_mat->set_backend(this->local_backend_);       

    if (this->get_nnz() == 0)
      ocl_cast_mat->AllocateCOO(dst->get_nnz(), dst->get_nrow(), dst->get_ncol() );

    assert((this->get_nnz()  == dst->get_nnz())  &&
	   (this->get_nrow() == dst->get_nrow()) &&
	   (this->get_ncol() == dst->get_ncol()) );

    if (this->get_nnz() > 0) {

      // Copy object from device to device memory (internal copy)
      ocl_dev2dev<int>(this->get_nnz(), // size
                       this->mat_.row,         // src
                       ocl_cast_mat->mat_.row, // dst
                       OCL_HANDLE(this->local_backend_.OCL_handle)->OCL_cmdQueue );

      // Copy object from device to device memory (internal copy)
      ocl_dev2dev<int>(this->get_nnz(), // size
                       this->mat_.col,         // src
                       ocl_cast_mat->mat_.col, // dst
                       OCL_HANDLE(this->local_backend_.OCL_handle)->OCL_cmdQueue );

      // Copy object from device to device memory (internal copy)
      ocl_dev2dev<ValueType>(this->get_nnz(), // size
                             this->mat_.val,         // src
                             ocl_cast_mat->mat_.val, // dst
                             OCL_HANDLE(this->local_backend_.OCL_handle)->OCL_cmdQueue );

    }
    
  } else {

    //OCL to CPU
    if ((host_cast_mat = dynamic_cast<HostMatrix<ValueType>*> (dst)) != NULL) {
      
      this->CopyToHost(host_cast_mat);

    } else {
      
      LOG_INFO("Error unsupported OCL matrix type");
      this->info();
      dst->info();
      FATAL_ERROR(__FILE__, __LINE__);
      
    }

  }


}
Exemplo n.º 18
0
void PackedPayloadHashTable::resize(const std::size_t extra_buckets,
                                    const std::size_t extra_variable_storage,
                                    const std::size_t retry_num) {
  // A retry should never be necessary with this implementation of HashTable.
  // Separate chaining ensures that any resized hash table with more buckets
  // than the original table will be able to hold more entries than the
  // original.
  DEBUG_ASSERT(retry_num == 0);

  SpinSharedMutexExclusiveLock<true> write_lock(this->resize_shared_mutex_);

  // Recheck whether the hash table is still full. Note that multiple threads
  // might wait to rebuild this hash table simultaneously. Only the first one
  // should do the rebuild.
  if (!isFull(extra_variable_storage)) {
    return;
  }

  // Approximately double the number of buckets and slots.
  //
  // TODO(chasseur): It may be worth it to more than double the number of
  // buckets here so that we can maintain a good, sparse fill factor for a
  // longer time as more values are inserted. Such behavior should take into
  // account kHashTableLoadFactor.
  std::size_t resized_num_slots = get_next_prime_number(
      (header_->num_buckets + extra_buckets / 2) * kHashTableLoadFactor * 2);
  std::size_t variable_storage_required =
      (resized_num_slots / kHashTableLoadFactor) *
      key_manager_.getEstimatedVariableKeySize();
  const std::size_t original_variable_storage_used =
      header_->variable_length_bytes_allocated.load(std::memory_order_relaxed);
  // If this resize was triggered by a too-large variable-length key, bump up
  // the variable-length storage requirement.
  if ((extra_variable_storage > 0) &&
      (extra_variable_storage + original_variable_storage_used >
       key_manager_.getVariableLengthKeyStorageSize())) {
    variable_storage_required += extra_variable_storage;
  }

  const std::size_t resized_memory_required =
      sizeof(Header) + resized_num_slots * sizeof(std::atomic<std::size_t>) +
      (resized_num_slots / kHashTableLoadFactor) * bucket_size_ +
      variable_storage_required;
  const std::size_t resized_storage_slots =
      this->storage_manager_->SlotsNeededForBytes(resized_memory_required);
  if (resized_storage_slots == 0) {
    FATAL_ERROR(
        "Storage requirement for resized SeparateChainingHashTable "
        "exceeds maximum allocation size.");
  }

  // Get a new StorageBlob to hold the resized hash table.
  const block_id resized_blob_id =
      this->storage_manager_->createBlob(resized_storage_slots);
  MutableBlobReference resized_blob =
      this->storage_manager_->getBlobMutable(resized_blob_id);

  // Locate data structures inside the new StorageBlob.
  void *aligned_memory_start = resized_blob->getMemoryMutable();
  std::size_t available_memory = resized_storage_slots * kSlotSizeBytes;
  if (align(alignof(Header),
            sizeof(Header),
            aligned_memory_start,
            available_memory) == nullptr) {
    // Should be impossible, as noted in constructor.
    FATAL_ERROR(
        "StorageBlob used to hold resized SeparateChainingHashTable "
        "is too small to meet alignment requirements of "
        "LinearOpenAddressingHashTable::Header.");
  } else if (aligned_memory_start != resized_blob->getMemoryMutable()) {
    // Again, should be impossible.
    DEV_WARNING("In SeparateChainingHashTable::resize(), StorageBlob "
                << "memory adjusted by "
                << (resized_num_slots * kSlotSizeBytes - available_memory)
                << " bytes to meet alignment requirement for "
                << "LinearOpenAddressingHashTable::Header.");
  }

  Header *resized_header = static_cast<Header *>(aligned_memory_start);
  aligned_memory_start =
      static_cast<char *>(aligned_memory_start) + sizeof(Header);
  available_memory -= sizeof(Header);

  // As in constructor, recompute the number of slots and buckets using the
  // actual available memory.
  std::size_t resized_num_buckets =
      (available_memory - extra_variable_storage) /
      (kHashTableLoadFactor * sizeof(std::atomic<std::size_t>) + bucket_size_ +
       key_manager_.getEstimatedVariableKeySize());
  resized_num_slots =
      get_previous_prime_number(resized_num_buckets * kHashTableLoadFactor);
  resized_num_buckets = resized_num_slots / kHashTableLoadFactor;

  // Locate slot array.
  std::atomic<std::size_t> *resized_slots =
      static_cast<std::atomic<std::size_t> *>(aligned_memory_start);
  aligned_memory_start = static_cast<char *>(aligned_memory_start) +
                         sizeof(std::atomic<std::size_t>) * resized_num_slots;
  available_memory -= sizeof(std::atomic<std::size_t>) * resized_num_slots;

  // As in constructor, we will be extra paranoid and use align() to locate the
  // start of the array of buckets, as well.
  void *resized_buckets = aligned_memory_start;
  if (align(
          kBucketAlignment, bucket_size_, resized_buckets, available_memory) ==
      nullptr) {
    FATAL_ERROR(
        "StorageBlob used to hold resized SeparateChainingHashTable "
        "is too small to meet alignment requirements of buckets.");
  } else if (resized_buckets != aligned_memory_start) {
    DEV_WARNING(
        "Bucket array start position adjusted to meet alignment "
        "requirement for SeparateChainingHashTable's value type.");
    if (resized_num_buckets * bucket_size_ + variable_storage_required >
        available_memory) {
      --resized_num_buckets;
    }
  }
  aligned_memory_start = static_cast<char *>(aligned_memory_start) +
                         resized_num_buckets * bucket_size_;
  available_memory -= resized_num_buckets * bucket_size_;

  void *resized_variable_length_key_storage = aligned_memory_start;
  const std::size_t resized_variable_length_key_storage_size = available_memory;

  const std::size_t original_buckets_used =
      header_->buckets_allocated.load(std::memory_order_relaxed);

  // Initialize the header.
  resized_header->num_slots = resized_num_slots;
  resized_header->num_buckets = resized_num_buckets;
  resized_header->buckets_allocated.store(original_buckets_used,
                                          std::memory_order_relaxed);
  resized_header->variable_length_bytes_allocated.store(
      original_variable_storage_used, std::memory_order_relaxed);

  // Bulk-copy buckets. This is safe because:
  //     1. The "next" pointers will be adjusted when rebuilding chains below.
  //     2. The hash codes will stay the same.
  //     3. For key components:
  //       a. Inline keys will stay exactly the same.
  //       b. Offsets into variable-length storage will remain valid, because
  //          we also do a byte-for-byte copy of variable-length storage below.
  //       c. Absolute external pointers will still point to the same address.
  //       d. Relative pointers are not used with resizable hash tables.
  //     4. If values are not trivially copyable, then we invoke ValueT's copy
  //        or move constructor with placement new.
  // NOTE(harshad) - Regarding point 4 above, as this is a specialized
  // hash table implemented for aggregation, the values are trivially copyable,
  // therefore we don't need to invoke payload values' copy/move constructors.
  std::memcpy(resized_buckets, buckets_, original_buckets_used * bucket_size_);

  // Copy over variable-length key components, if any.
  if (original_variable_storage_used > 0) {
    DEBUG_ASSERT(original_variable_storage_used ==
                 key_manager_.getNextVariableLengthKeyOffset());
    DEBUG_ASSERT(original_variable_storage_used <=
                 resized_variable_length_key_storage_size);
    std::memcpy(resized_variable_length_key_storage,
                key_manager_.getVariableLengthKeyStorage(),
                original_variable_storage_used);
  }

  destroyPayload();

  // Make resized structures active.
  std::swap(this->blob_, resized_blob);
  header_ = resized_header;
  slots_ = resized_slots;
  buckets_ = resized_buckets;
  key_manager_.setVariableLengthStorageInfo(
      resized_variable_length_key_storage,
      resized_variable_length_key_storage_size,
      &(resized_header->variable_length_bytes_allocated));

  // Drop the old blob.
  const block_id old_blob_id = resized_blob->getID();
  resized_blob.release();
  this->storage_manager_->deleteBlockOrBlobFile(old_blob_id);

  // Rebuild chains.
  void *current_bucket = buckets_;
  for (std::size_t bucket_num = 0; bucket_num < original_buckets_used;
       ++bucket_num) {
    std::atomic<std::size_t> *next_ptr =
        static_cast<std::atomic<std::size_t> *>(current_bucket);
    const std::size_t hash_code = *reinterpret_cast<const std::size_t *>(
        static_cast<const char *>(current_bucket) +
        sizeof(std::atomic<std::size_t>));

    const std::size_t slot_number = hash_code % header_->num_slots;
    std::size_t slot_ptr_value = 0;
    if (slots_[slot_number].compare_exchange_strong(
            slot_ptr_value, bucket_num + 1, std::memory_order_relaxed)) {
      // This bucket is the first in the chain for this block, so reset its
      // next pointer to 0.
      next_ptr->store(0, std::memory_order_relaxed);
    } else {
      // A chain already exists starting from this slot, so put this bucket at
      // the head.
      next_ptr->store(slot_ptr_value, std::memory_order_relaxed);
      slots_[slot_number].store(bucket_num + 1, std::memory_order_relaxed);
    }
    current_bucket = static_cast<char *>(current_bucket) + bucket_size_;
  }
}
Exemplo n.º 19
0
int main(int argc, char *argv[])
{
   int ret;
   /* etterlog copyright */
   globals_alloc();
   fprintf(stdout, "\n" EC_COLOR_BOLD "%s %s" EC_COLOR_END " copyright %s %s\n\n", 
                      GBL_PROGRAM, EC_VERSION, EC_COPYRIGHT, EC_AUTHORS);
  
  
   /* allocate the global target */
   SAFE_CALLOC(GBL_TARGET, 1, sizeof(struct target_env));
  
   /* initialize to all target */
   GBL_TARGET->all_mac = 1;
   GBL_TARGET->all_ip = 1;
   GBL_TARGET->all_port = 1;
   
   /* getopt related parsing...  */
   parse_options(argc, argv);

   /* get the global header */
   ret = get_header(&GBL->hdr);
   if (ret == -EINVALID)
      FATAL_ERROR("Invalid log file");
   
   fprintf(stderr, "Log file version    : %s\n", GBL->hdr.version);
   /* display the date. ec_ctime() has no newline at end. */
   fprintf(stderr, "Timestamp           : %s [%lu]\n", ec_ctime(&GBL->hdr.tv), GBL->hdr.tv.tv_usec);
   fprintf(stderr, "Type                : %s\n\n", (GBL->hdr.type == LOG_PACKET) ? "LOG_PACKET" : "LOG_INFO" );
  
   
   /* analyze the logfile */
   if (GBL->analyze)
      analyze();

   /* rewind the log file and skip the global header */
   gzrewind(GBL_LOG_FD);
   get_header(&GBL->hdr);
   
   /* create the connection table (respecting the filters) */
   if (GBL->connections)
      conn_table_create();

   /* display the connection table */
   if (GBL->connections && !GBL->decode)
      conn_table_display();

   /* extract files from the connections */
   if (GBL->decode)
      conn_decode();
   
   /* not interested in the content... only analysis */
   if (GBL->analyze || GBL->connections)
      return 0;
   
   /* display the content of the logfile */
   display();
   
   globals_free();

   return 0;
}
Exemplo n.º 20
0
static void
read_directory_file (void)
{
  char *strp;
  FILE *fp;
  char buf[512];		/* FIXME: use a symbol */
  static char *path = NULL;

  if (path == NULL)
    path = xmalloc (PATH_MAX);
  time (&time_now);
  if (listed_incremental_option[0] != '/'
#if DOSWIN
      /* The case of DOSWIN absolute file name with a drive letter.  */
      && !(listed_incremental_option[0] && listed_incremental_option[1] == ':')
#endif
      )
    {
      char *current_directory = xgetcwd ();

      if (!current_directory)
	FATAL_ERROR ((0, 0, _("Could not get current directory")));

      listed_incremental_option
	= concat_with_slash (current_directory, listed_incremental_option);
    }
  fp = fopen (listed_incremental_option, "r");
  if (fp == 0 && errno != ENOENT)
    {
      ERROR ((0, errno, _("Cannot open %s"), listed_incremental_option));
      return;
    }
  if (!fp)
    return;
  fgets (buf, sizeof (buf), fp);

  /* FIXME: Using newer_ctime_option as a first time flag looks fairly dubious
     to me!  So, using -N with incremental might be buggy just because of the
     next few lines.  I saw a few unexplained, almost harsh advices from FSF
     people about *not* using -N with incremental dumps, and here might lie
     (part of) the reason.  */
  if (!newer_ctime_option)
    {
      time_option_threshold = atol (buf);
      newer_ctime_option = true;
    }

  while (fgets (buf, sizeof (buf), fp))
    {
      dev_t device_number;
      ino_t inode_number;

      strp = &buf[strlen (buf)];
      if (strp[-1] == '\n')
	strp[-1] = '\0';
      /* FIXME: For files ending with an incomplete line, maybe a NUL might
	 be missing, here...  */

      strp = buf;
      device_number = atol (strp);
      while (ISDIGIT (*strp))
	strp++;
      inode_number = atol (strp);
      while (ISSPACE (*strp))
	strp++;
      while (ISDIGIT (*strp))
	strp++;
      strp++;
      unquote_string (strp);
      note_directory (strp, device_number, inode_number, NULL);
    }
  if (fclose (fp) == EOF)
    ERROR ((0, errno, "%s", listed_incremental_option));
}
Exemplo n.º 21
0
void parse_options(int argc, char **argv)
{
   int c;
   struct in_addr ip;

   static struct option long_options[] = {
      { "help", no_argument, NULL, 'h' },
      { "version", no_argument, NULL, 'v' },
      
      { "binary", no_argument, NULL, 'B' },
      { "hex", no_argument, NULL, 'X' },
      { "ascii", no_argument, NULL, 'A' },
      { "text", no_argument, NULL, 'T' },
      { "ebcdic", no_argument, NULL, 'E' },
      { "html", no_argument, NULL, 'H' },
      { "utf8", required_argument, NULL, 'U' },
      { "zero", no_argument, NULL, 'Z' },
      { "xml", no_argument, NULL, 'x' },
      
      { "analyze", no_argument, NULL, 'a' },
      { "connections", no_argument, NULL, 'c' },
      { "filter", required_argument, NULL, 'f' },
      { "filcon", required_argument, NULL, 'F' },
      { "no-headers", no_argument, NULL, 'n' },
      { "only-source", no_argument, NULL, 's' },
      { "only-dest", no_argument, NULL, 'd' },
      { "show-mac", no_argument, NULL, 'm' },
      { "show-client", no_argument, NULL, 'i' },
      { "color", no_argument, NULL, 'k' },
      { "reverse", no_argument, NULL, 'r' },
      { "proto", required_argument, NULL, 't' },
      { "only-local", required_argument, NULL, 'l' },
      { "only-remote", required_argument, NULL, 'L' },
      
      { "outfile", required_argument, NULL, 'o' },
      { "concat", no_argument, NULL, 'C' },
      { "decode", no_argument, NULL, 'D' },
      
      { "user", required_argument, NULL, 'u' },
      { "regex", required_argument, NULL, 'e' },
      { "passwords", no_argument, NULL, 'p' },
      { "client", required_argument, NULL, 'I' },
      
      { 0 , 0 , 0 , 0}
   };

   
   optind = 0;

   while ((c = getopt_long (argc, argv, "AaBCcDdEe:F:f:HhiI:kLlmno:prsTt:U:u:vXxZ", long_options, (int *)0)) != EOF) {

      switch (c) {

         case 'a':
                  GBL.analyze = 1;
                  break;
                  
         case 'c':
                  GBL.connections = 1;
                  break;
                  
         case 'D':
                  GBL.connections = 1;
                  GBL.decode = 1;
                  NOT_IMPLEMENTED();
                  break;
         
         case 'f':
                  target_compile(optarg);
                  break;

         case 'F':
                  filcon_compile(optarg);
                  break;
                  
         case 's':
                  GBL.only_source = 1;
                  break;
                  
         case 'd':
                  GBL.only_dest = 1;
                  break;
                  
         case 'k':
                  GBL.color = 1;
                  break;
                     
         case 'r':
                  GBL.reverse = 1;
                  break;
                  
         case 't':
                  GBL_TARGET->proto = strdup(optarg);
                  break;
                  
         case 'n':
                  GBL.no_headers = 1;
                  break;
                  
         case 'm':
                  GBL.showmac = 1;
                  break;
                  
         case 'i':
                  GBL.showclient = 1;
                  break;
                  
         case 'I':
                  if (inet_aton(optarg, &ip) == 0) {
                     FATAL_ERROR("Invalid client ip address");
                     return;                    
                  }
                  ip_addr_init(&GBL.client, AF_INET, (u_char *)&ip);
                  break;

         case 'l':
                  GBL.only_local = 1;
                  break;
         
         case 'L':
                  GBL.only_remote = 1;
                  break;
                  
         case 'u':
                  GBL.user = strdup(optarg);
                  break;
                  
         case 'p':
                  GBL.passwords = 1;
                  break;

         case 'e':
                  set_display_regex(optarg);
                  break;
                 
         case 'o':
                  GBL_LOGFILE = strdup(optarg);
                  break;
                  
         case 'C':
                  GBL.concat = 1;
                  break;
                  
         case 'B':
                  GBL.format = &bin_format;
                  break;
                  
         case 'X':
                  GBL.format = &hex_format;
                  break;
                  
         case 'A':
                  GBL.format = &ascii_format;
                  break;
                  
         case 'T':
                  GBL.format = &text_format;
                  break;
                  
         case 'E':
                  GBL.format = &ebcdic_format;
                  break;
                  
         case 'H':
                  GBL.format = &html_format;
                  break;
                  
         case 'U':
                  set_utf8_encoding((u_char*)optarg);
                  GBL.format = &utf8_format;
                  break;
                  
         case 'Z':
                  GBL.format = &zero_format;
                  break;
                  
         case 'x':
                  GBL.xml = 1;
                  break;
                  
         case 'h':
                  el_usage();
                  break;

         case 'v':
                  printf("%s %s\n", GBL_PROGRAM, EC_VERSION);
                  exit(0);
                  break;

         case ':': // missing parameter
            fprintf(stdout, "\nTry `%s --help' for more options.\n\n", GBL_PROGRAM);
            exit(0);
         break;

         case '?': // unknown option
            fprintf(stdout, "\nTry `%s --help' for more options.\n\n", GBL_PROGRAM);
            exit(0);
         break;
      }
   }

   /* file concatenation */
   if (GBL.concat) {
      if (argv[optind] == NULL)
         FATAL_ERROR("You MUST specify at least one logfile");
   
      /* this function does not return */
      concatenate(optind, argv);
   }

   /* normal file operation */
   if (argv[optind])
      open_log(argv[optind]);
   else
      FATAL_ERROR("You MUST specify a logfile\n");
  
   /* default to ASCII view */ 
   if (GBL.format == NULL)
      GBL.format = &ascii_format;

   return;
}
Exemplo n.º 22
0
void PlayerSAO::getStaticData(std::string *result) const
{
	FATAL_ERROR("Deprecated function");
}
Exemplo n.º 23
0
/**
 * 
 * @author Petr Djakow
 */
void Utils::reuseSocketAddr(int sockfd)
{
	int opt = 1;
	if(setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) == -1)
		FATAL_ERROR(("Could not reuse socket addr"));
}
static void stdin_read_complete(GObject *src, GAsyncResult *res, gpointer data)
{
    char *s, *ep;
    GError *err = NULL;
    gsize len;

    s = g_data_input_stream_read_line_finish(G_DATA_INPUT_STREAM(src), res,
                                             &len, &err);
    if (!s) {
        if (err) {
            FATAL_ERROR("Reading from stdin: %s\n", err->message);
            g_error_free(err);
            return;
        }

        switch (state) {
        case STATE_WAITING_FOR_BUS_N_DEV:
            FATAL_ERROR("EOF while waiting for bus and device num\n");
            break;
        case STATE_WAITING_FOR_POL_KIT:
            ERROR("Cancelled while waiting for authorization\n");
            break;
        case STATE_WAITING_FOR_STDIN_EOF:
            cleanup();
            break;
        }
        return;
    }

    switch (state) {
    case STATE_WAITING_FOR_BUS_N_DEV:
        busnum = strtol(s, &ep, 10);
        if (!isspace(*ep)) {
            FATAL_ERROR("Invalid busnum / devnum: %s\n", s);
            break;
        }
        devnum = strtol(ep, &ep, 10);
        if (*ep != '\0') {
            FATAL_ERROR("Invalid busnum / devnum: %s\n", s);
            break;
        }

        /*
         * The set_facl() call is a no-op for root, so no need to ask PolKit
         * and then if ok call set_facl(), when called by a root process.
         */
        if (getuid() != 0) {
            polkit_cancellable = g_cancellable_new();
            polkit_authority_check_authorization(
                authority, subject, "org.spice-space.lowlevelusbaccess", NULL,
                POLKIT_CHECK_AUTHORIZATION_FLAGS_ALLOW_USER_INTERACTION,
                polkit_cancellable,
                (GAsyncReadyCallback)check_authorization_cb, NULL);
            state = STATE_WAITING_FOR_POL_KIT;
        } else {
            fprintf(stdout, "SUCCESS\n");
            fflush(stdout);
            state = STATE_WAITING_FOR_STDIN_EOF;
        }

        g_data_input_stream_read_line_async(stdin_stream, G_PRIORITY_DEFAULT,
                                            NULL, stdin_read_complete, NULL);
        break;
    default:
        FATAL_ERROR("Unexpected extra input in state %u: %s\n", state, s);
    }
    g_free(s);
}
Exemplo n.º 25
0
void
info_attach_exclist (struct tar_stat_info *dir)
{
  struct excfile *file;
  struct exclist *head = NULL, *tail = NULL, *ent;
  struct vcs_ignore_file *vcsfile;

  if (dir->exclude_list)
    return;
  for (file = excfile_head; file; file = file->next)
    {
      if (faccessat (dir ? dir->fd : chdir_fd, file->name, F_OK, 0) == 0)
	{
	  FILE *fp;
	  struct exclude *ex = NULL;
	  int fd = subfile_open (dir, file->name, O_RDONLY);
	  if (fd == -1)
	    {
	      open_error (file->name);
	      continue;
	    }
	  fp = fdopen (fd, "r");
	  if (!fp)
	    {
	      ERROR ((0, errno, _("%s: fdopen failed"), file->name));
	      close (fd);
	      continue;
	    }

	  if (!ex)
	    ex = new_exclude ();

	  vcsfile = get_vcs_ignore_file (file->name);

	  if (vcsfile->initfn)
	    vcsfile->data = vcsfile->initfn (vcsfile->data);

	  if (add_exclude_fp (vcsfile->addfn, ex, fp,
			      EXCLUDE_WILDCARDS|EXCLUDE_ANCHORED, '\n',
			      vcsfile->data))
	    {
	      int e = errno;
	      FATAL_ERROR ((0, e, "%s", quotearg_colon (file->name)));
	    }
	  fclose (fp);

	  ent = xmalloc (sizeof (*ent));
	  ent->excluded = ex;
	  ent->flags = file->flags == EXCL_DEFAULT
	               ? file->flags : vcsfile->flags;
	  ent->prev = tail;
	  ent->next = NULL;

	  if (tail)
	    tail->next = ent;
	  else
	    head = ent;
	  tail = ent;
	}
    }
  dir->exclude_list = head;
}
Exemplo n.º 26
0
void LocalStencil<ValueType>::MoveToHost(void) {

  LOG_INFO("The function is not implemented (yet)!");
  FATAL_ERROR(__FILE__, __LINE__);

}
 /**
  * @brief For Numeric TypeInstances, get this TypeInstance's value as a C++
  *        float.
  * @warning supportsNumericInterface() must be true and isNull() must be
  *          false for this method to be usable.
  *
  * @return The value as a float.
  **/
 virtual float numericGetFloatValue() const {
   FATAL_ERROR("Used a Numeric interface method on a non-numeric TypeInstance.");
 }
Exemplo n.º 28
0
void initializePaths()
{
#if RUN_IN_PLACE
	/*
		Use relative paths if RUN_IN_PLACE
	*/

	infostream<<"Using relative paths (RUN_IN_PLACE)"<<std::endl;

	/*
		Windows
	*/
	#if defined(_WIN32)

	const DWORD buflen = 1000;
	char buf[buflen];
	DWORD len;

	// Find path of executable and set path_share relative to it
	len = GetModuleFileName(GetModuleHandle(NULL), buf, buflen);
	assert(len < buflen);
	pathRemoveFile(buf, '\\');

	if(detectMSVCBuildDir(buf)){
		infostream<<"MSVC build directory detected"<<std::endl;
		path_share = std::string(buf) + "\\..\\..";
		path_user = std::string(buf) + "\\..\\..";
	}
	else{
		path_share = std::string(buf) + "\\..";
		path_user = std::string(buf) + "\\..";
	}

	/*
		Linux
	*/
	#elif defined(linux)

	char buf[BUFSIZ];
	memset(buf, 0, BUFSIZ);
	// Get path to executable
	FATAL_ERROR_IF(readlink("/proc/self/exe", buf, BUFSIZ-1) == -1, "Failed to get cwd");

	pathRemoveFile(buf, '/');

	path_share = std::string(buf) + "/..";
	path_user = std::string(buf) + "/..";

	/*
		OS X
	*/
	#elif defined(__APPLE__)

	CFBundleRef main_bundle = CFBundleGetMainBundle();
	CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle);
	char path[PATH_MAX];
	if (CFURLGetFileSystemRepresentation(resources_url, TRUE, (UInt8 *)path, PATH_MAX)) {
		path_share = std::string(path);
		path_user = std::string(path) + "/../User";
	} else {
		dstream << "WARNING: Could not determine bundle resource path" << std::endl;
	}
	CFRelease(resources_url);

	/*
		FreeBSD
	*/
	#elif defined(__FreeBSD__)

	int mib[4];
	char buf[BUFSIZ];
	size_t len = sizeof(buf);

	mib[0] = CTL_KERN;
	mib[1] = KERN_PROC;
	mib[2] = KERN_PROC_PATHNAME;
	mib[3] = -1;
	FATAL_ERROR_IF(sysctl(mib, 4, buf, &len, NULL, 0) == -1, "");

	pathRemoveFile(buf, '/');

	path_share = std::string(buf) + "/..";
	path_user = std::string(buf) + "/..";

	#else

	//TODO: Get path of executable. This assumes working directory is bin/
	dstream<<"WARNING: Relative path not properly supported on this platform"
			<<std::endl;

	/* scriptapi no longer allows paths that start with "..", so assuming that
	   the current working directory is bin/, strip off the last component. */
	char *cwd = getcwd(NULL, 0);
	pathRemoveFile(cwd, '/');
	path_share = std::string(cwd);
	path_user = std::string(cwd);

	#endif

#else // RUN_IN_PLACE

	/*
		Use platform-specific paths otherwise
	*/

	infostream<<"Using system-wide paths (NOT RUN_IN_PLACE)"<<std::endl;

	/*
		Windows
	*/
	#if defined(_WIN32)

	const DWORD buflen = 1000; // FIXME: Surely there is a better way to do this
	char buf[buflen];
	DWORD len;

	// Find path of executable and set path_share relative to it
	len = GetModuleFileName(GetModuleHandle(NULL), buf, buflen);
	FATAL_ERROR_IF(len >= buflen, "Overlow");
	pathRemoveFile(buf, '\\');

	// Use ".\bin\.."
	path_share = std::string(buf) + "\\..";

	// Use "C:\Documents and Settings\user\Application Data\<PROJECT_NAME>"
	len = GetEnvironmentVariable("APPDATA", buf, buflen);
	FATAL_ERROR_IF(len >= buflen, "Overlow");
	path_user = std::string(buf) + DIR_DELIM + lowercase(PROJECT_NAME);

	/*
		Linux
	*/
	#elif defined(linux)

	// Get path to executable
	std::string bindir = "";
	{
		char buf[BUFSIZ];
		memset(buf, 0, BUFSIZ);
		if (readlink("/proc/self/exe", buf, BUFSIZ-1) == -1) {
			errorstream << "Unable to read bindir "<< std::endl;
#ifndef __ANDROID__
			FATAL_ERROR("Unable to read bindir");
#endif
		} else {
			pathRemoveFile(buf, '/');
			bindir = buf;
		}
	}

	// Find share directory from these.
	// It is identified by containing the subdirectory "builtin".
	std::list<std::string> trylist;
	std::string static_sharedir = STATIC_SHAREDIR;
	if(static_sharedir != "" && static_sharedir != ".")
		trylist.push_back(static_sharedir);
	trylist.push_back(
			bindir + DIR_DELIM + ".." + DIR_DELIM + "share" + DIR_DELIM + lowercase(PROJECT_NAME));
	trylist.push_back(bindir + DIR_DELIM + "..");
#ifdef __ANDROID__
	trylist.push_back(path_user);
#endif

	for(std::list<std::string>::const_iterator i = trylist.begin();
			i != trylist.end(); i++)
	{
		const std::string &trypath = *i;
		if(!fs::PathExists(trypath) || !fs::PathExists(trypath + DIR_DELIM + "builtin")){
			dstream<<"WARNING: system-wide share not found at \""
					<<trypath<<"\""<<std::endl;
			continue;
		}
		// Warn if was not the first alternative
		if(i != trylist.begin()){
			dstream<<"WARNING: system-wide share found at \""
					<<trypath<<"\""<<std::endl;
		}
		path_share = trypath;
		break;
	}
#ifndef __ANDROID__
	path_user = std::string(getenv("HOME")) + DIR_DELIM + "." + lowercase(PROJECT_NAME);
#endif

	/*
		OS X
	*/
	#elif defined(__APPLE__)

	CFBundleRef main_bundle = CFBundleGetMainBundle();
	CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle);
	char path[PATH_MAX];
	if (CFURLGetFileSystemRepresentation(resources_url, TRUE, (UInt8 *)path, PATH_MAX)) {
		path_share = std::string(path);
	} else {
		dstream << "WARNING: Could not determine bundle resource path" << std::endl;
	}
	CFRelease(resources_url);

	path_user = std::string(getenv("HOME")) + "/Library/Application Support/" + lowercase(PROJECT_NAME);

	#else // FreeBSD, and probably many other POSIX-like systems.

	path_share = STATIC_SHAREDIR;
	path_user = std::string(getenv("HOME")) + DIR_DELIM + "." + lowercase(PROJECT_NAME);

	#endif

#endif // RUN_IN_PLACE
}
 /**
  * @brief Actually determine whether the string represented by this
  *        particular type instance has a terminating NULL-character.
  * @note If asciiStringGuaranteedNullTerminated() is false, then this method
  *       actually scans the string for a NULL-terminator.
  * @warning supportsAsciiStringInterface() must be true and isNull() must be
  *          false for this method to be usable.
  *
  * @return Whether the underlying string is has a NULL-terminator.
  **/
 virtual bool asciiStringNullTerminated() const {
   FATAL_ERROR("Used an AsciiString interface method on a non-AsciiString TypeInstance.");
 }
Exemplo n.º 30
0
/* Set ARCHIVE for writing, then compressing an archive.  */
void
sys_child_open_for_compress (void)
{
  FATAL_ERROR ((0, 0, _("Cannot use compressed or remote archives")));
}