Ejemplo n.º 1
0
int main(int argc, char **argv)
{
	std::string outfilename;
	po::options_description desc("qvod_crack options");
	desc.add_options()
		("help,h", "display this help")
		(",c", "compile only")
		("ir", "generate llvm-IR and stop")
		("outfile,o", po::value<std::string>(&outfilename), "set outputname")
		;

	po::variables_map vm;
	po::store(po::parse_command_line(argc, argv, desc), vm);
	po::notify(vm);

	if (vm.count("help")) {
        std::cout << desc;
        return 0;
    }

    std::list<std::string> inputs = argv_getinputfiles(argc,argv);
	if(inputs.empty()){
		std::cerr <<  "no input file" << std::endl;
		return 1;
	}

	std::string input = inputs.begin()->c_str();
	
	// usage llvmqbc input.bas -o a.out
	// ./a.out
	std::cout << "openning: " << input << std::endl;
	yyin = std::fopen(input.c_str(),"r");
	
	if(!yyin)
	{
		printf("open %s failed\n",input.c_str());
		return 1;
	}

	qb::parser parser;

	parser.parse();
	
	std::cout << "parse done, no errors, generating llvm IR..." << std::endl;

	// Initialize targets first, so that --version shows registered targets.
	llvm::InitializeAllTargets();
	llvm::InitializeAllTargetMCs();
	llvm::InitializeAllAsmPrinters();
	llvm::InitializeAllAsmParsers();

	// 如果没有指定输出文件路径, 设置输出文件的路径为输入文件相同的路径下.
	if(outfilename.empty())
		outfilename = (fs::path(input).parent_path() / fs::basename(fs::path(input))).string();

	llvm::Module *module = new llvm::Module( fs::basename(fs::path(input)).c_str(), llvm::getGlobalContext());
	generateIR(program,module);

	// ir to generate llvm IR
	if(vm.count("ir")){
		module->dump();
		return 0;
	}
	
#if _WIN32
	std::string outobjname = outfilename + ".obj";
#else
	std::string outobjname = outfilename + ".o";
#endif
	std::string Err;

	boost::shared_ptr<llvm::tool_output_file> Out( new
		llvm::tool_output_file(outobjname.c_str(), Err, llvm::raw_fd_ostream::F_Binary) );

	if(generateobj(Out,module)==0)
		printf("======== object file writed to %s ===========\n", outobjname.c_str());

	if(!vm.count("-c"))
	{
		// compile to excuteable
#if _WIN32
		std::string cmd = boost::str(boost::format("link.exe /out:%s %s msvcrt.lib")
			% std::string(outfilename + ".exe") %  outobjname );
#else
		// invoke  gcc
		std::string libdir = fs::path(argv[0]).parent_path().string();
		std::string cmd = boost::str(boost::format("gcc -o %s %s -L%s -lbrt")
							% outfilename %  (outfilename + ".o") % libdir.c_str());
#endif
		printf("run linker: %s\n",cmd.c_str());
		if(std::system(cmd.c_str())==0)
			Out->keep(); // keep the file if linker runs fine

	} else {
		// no delete obj file
		Out->keep();
	}

	return 0;
}
Ejemplo n.º 2
0
Signer_Item::~Signer_Item()
{
	password.Wipe();
	if(InList())
		Out();
}
Ejemplo n.º 3
0
/* virtual */
int DOM_JILMediaPlayer::Open(ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime)
{
	DOM_CallState* call_state = DOM_CallState::FromReturnValue(return_value);
	OP_ASSERT(call_state); // We should always have call_state from security check earlier.
	if (call_state->GetPhase() < DOM_CallState::PHASE_EXECUTION_0)
	{
		DOM_CHECK_ARGUMENTS_JIL("s");
		if (m_state != PLAYER_STATE_BEGIN && m_state != PLAYER_STATE_STOPPED && m_state != PLAYER_STATE_COMPLETED && m_state != PLAYER_STATE_OPENED) // other entry states are not allowed
			return ES_FAILED;

		if (m_open_thread)
		{
			m_open_thread->Unblock();
			m_open_thread = NULL;
		}
		m_open_failed = FALSE;

		// Get media element
		JILMediaElement *media_element = GetJILMediaElement();

		if (!media_element)
			return CallException(DOM_Object::JIL_UNKNOWN_ERR, return_value, origining_runtime, UNI_L("Unable to open URL"));

		OpGadget* gadget = g_DOM_jilUtils->GetGadgetFromRuntime(origining_runtime);
		OP_ASSERT(gadget);

		const uni_char* resource_url = argv[0].value.string;

		OpString gadget_url_str;

		CALL_FAILED_IF_ERROR(gadget->GetGadgetUrl(gadget_url_str, FALSE, TRUE));
		URL gadget_url = g_url_api->GetURL(gadget_url_str.CStr(), gadget->UrlContextId());

		URL url = g_url_api->GetURL(gadget_url, resource_url);	// URL Context ID is inherited from gadget_url
		if (gadget_url.IsEmpty() || url.IsEmpty())
			return CallException(DOM_Object::JIL_INVALID_PARAMETER_ERR, return_value, origining_runtime, UNI_L("Unable to open URL"));

		if (url.Type() == URL_FILE)
		{
			if (!g_DAPI_jil_fs_mgr->IsFileAccessAllowed(url))
				return CallException(DOM_Object::JIL_INVALID_PARAMETER_ERR, return_value, origining_runtime, UNI_L("Could not access the file"));
		}

		OP_STATUS status = media_element->Open(url);

		if (OpStatus::IsError(status))
			return HandleJILError(status, return_value, origining_runtime);
		else if (m_open_failed)
			return CallException(DOM_Object::JIL_INVALID_PARAMETER_ERR, return_value, origining_runtime, UNI_L("Cannot open media URL."));

		m_open_thread = DOM_Object::GetCurrentThread(origining_runtime);
		OP_ASSERT(m_open_thread);

		// Unlink from any listeners' list and link
		// to new thread.
		Out();
		m_open_thread->AddListener(this);

		m_open_thread->Block();
		call_state->SetPhase(static_cast<DOM_CallState::CallPhase>(DOM_CallState::PHASE_EXECUTION_0));
		return ES_SUSPEND | ES_RESTART;
	}
	else
	{
		OP_ASSERT(call_state->GetPhase() ==  DOM_CallState::PHASE_EXECUTION_0);
		// If we make a call to open and then before it finishes we make the call to open in another ecmascript thread,
		// then this call fails.
		// The actual check for this is done by checking if the thread of latest call to open is the same as current thread
		if (DOM_Object::GetCurrentThread(origining_runtime) != m_open_thread)
			return HandleJILError(OpStatus::ERR, return_value, origining_runtime);

		// Detach from the thread and clear the pointer, won't be needed any more.
		ES_ThreadListener::Remove();
		m_open_thread = NULL;

		if (m_open_failed) // some error occured in opening
			return HandleJILError(OpStatus::ERR, return_value, origining_runtime);
		SetState(PLAYER_STATE_OPENED);
		return ES_FAILED;
	}
}
Ejemplo n.º 4
0
Error writeArchive(StringRef ArcName, ArrayRef<NewArchiveMember> NewMembers,
                   bool WriteSymtab, object::Archive::Kind Kind,
                   bool Deterministic, bool Thin,
                   std::unique_ptr<MemoryBuffer> OldArchiveBuf) {
  assert((!Thin || !isBSDLike(Kind)) && "Only the gnu format has a thin mode");

  SmallString<0> SymNamesBuf;
  raw_svector_ostream SymNames(SymNamesBuf);
  SmallString<0> StringTableBuf;
  raw_svector_ostream StringTable(StringTableBuf);

  Expected<std::vector<MemberData>> DataOrErr = computeMemberData(
      StringTable, SymNames, Kind, Thin, Deterministic, NewMembers);
  if (Error E = DataOrErr.takeError())
    return E;
  std::vector<MemberData> &Data = *DataOrErr;

  if (!StringTableBuf.empty())
    Data.insert(Data.begin(), computeStringTable(StringTableBuf));

  // We would like to detect if we need to switch to a 64-bit symbol table.
  if (WriteSymtab) {
    uint64_t MaxOffset = 0;
    uint64_t LastOffset = MaxOffset;
    for (const auto &M : Data) {
      // Record the start of the member's offset
      LastOffset = MaxOffset;
      // Account for the size of each part associated with the member.
      MaxOffset += M.Header.size() + M.Data.size() + M.Padding.size();
      // We assume 32-bit symbols to see if 32-bit symbols are possible or not.
      MaxOffset += M.Symbols.size() * 4;
    }

    // The SYM64 format is used when an archive's member offsets are larger than
    // 32-bits can hold. The need for this shift in format is detected by
    // writeArchive. To test this we need to generate a file with a member that
    // has an offset larger than 32-bits but this demands a very slow test. To
    // speed the test up we use this environment variable to pretend like the
    // cutoff happens before 32-bits and instead happens at some much smaller
    // value.
    const char *Sym64Env = std::getenv("SYM64_THRESHOLD");
    int Sym64Threshold = 32;
    if (Sym64Env)
      StringRef(Sym64Env).getAsInteger(10, Sym64Threshold);

    // If LastOffset isn't going to fit in a 32-bit varible we need to switch
    // to 64-bit. Note that the file can be larger than 4GB as long as the last
    // member starts before the 4GB offset.
    if (LastOffset >= (1ULL << Sym64Threshold)) {
      if (Kind == object::Archive::K_DARWIN)
        Kind = object::Archive::K_DARWIN64;
      else
        Kind = object::Archive::K_GNU64;
    }
  }

  Expected<sys::fs::TempFile> Temp =
      sys::fs::TempFile::create(ArcName + ".temp-archive-%%%%%%%.a");
  if (!Temp)
    return Temp.takeError();

  raw_fd_ostream Out(Temp->FD, false);
  if (Thin)
    Out << "!<thin>\n";
  else
    Out << "!<arch>\n";

  if (WriteSymtab)
    writeSymbolTable(Out, Kind, Deterministic, Data, SymNamesBuf);

  for (const MemberData &M : Data)
    Out << M.Header << M.Data << M.Padding;

  Out.flush();

  // At this point, we no longer need whatever backing memory
  // was used to generate the NewMembers. On Windows, this buffer
  // could be a mapped view of the file we want to replace (if
  // we're updating an existing archive, say). In that case, the
  // rename would still succeed, but it would leave behind a
  // temporary file (actually the original file renamed) because
  // a file cannot be deleted while there's a handle open on it,
  // only renamed. So by freeing this buffer, this ensures that
  // the last open handle on the destination file, if any, is
  // closed before we attempt to rename.
  OldArchiveBuf.reset();

  return Temp->keep(ArcName);
}
Ejemplo n.º 5
0
 static T InOut(T normalizedTime)
 {
     constexpr auto half = T(1) / 2;
     return (time < half) ? half * In(normalizedTime * 2)
         : half + half * Out(normalizedTime * 2 - 1);
 }
Ejemplo n.º 6
0
        void PreconditionerLinear::v_DoPreconditionerWithNonVertOutput(
            const Array<OneD, NekDouble>& pInput,
            Array<OneD, NekDouble>& pOutput,
            const Array<OneD, NekDouble>& pNonVertOutput,
            Array<OneD, NekDouble>& pVertForce)
            {
            GlobalSysSolnType solvertype=m_locToGloMap->GetGlobalSysSolnType();
            switch(solvertype)
            {
                case MultiRegions::eIterativeStaticCond:
                {
                    int i,val;
                    int nloc = m_vertLocToGloMap->GetNumLocalCoeffs();
                    int nglo = m_vertLocToGloMap->GetNumGlobalCoeffs();
                    // mapping from full space to vertices
                    Array<OneD, int> LocToGloBnd = m_vertLocToGloMap->GetLocalToGlobalBndMap();

                    // Global to local for linear solver (different from above)
                    Array<OneD, int> LocToGlo = m_vertLocToGloMap->GetLocalToGlobalMap();
                    
                    // number of Dir coeffs in from full problem
                    int nDirFull = m_locToGloMap->GetNumGlobalDirBndCoeffs();
                    
                    Array<OneD,NekDouble> In(nglo,0.0);
                    Array<OneD,NekDouble> Out(nglo,0.0);

                    // Gather rhs
                    for(i = 0; i < nloc; ++i)
                    {
                        val = LocToGloBnd[i];
                        if(val >= nDirFull)
                        {
                            In[LocToGlo[i]] = pInput[val-nDirFull];
                        }
                    }
                    
                    // Do solve without enforcing any boundary conditions. 
                    m_vertLinsys->SolveLinearSystem(
                        m_vertLocToGloMap->GetNumGlobalCoeffs(),
                        In,Out,m_vertLocToGloMap,
                        m_vertLocToGloMap->GetNumGlobalDirBndCoeffs());
                    
                    
                    if(pNonVertOutput != NullNekDouble1DArray)
                    {
                        ASSERTL1(pNonVertOutput.num_elements() >= pOutput.num_elements(),"Non Vert output is not of sufficient length");
                        Vmath::Vcopy(pOutput.num_elements(),pNonVertOutput,1,pOutput,1);
                    }
                    else
                    {
                        //Copy input to output as a unit preconditioner on
                        //any other value
                        Vmath::Vcopy(pInput.num_elements(),pInput,1,pOutput,1);
                    }
                    
                    if(pVertForce != NullNekDouble1DArray)
                    {
                        Vmath::Zero(pVertForce.num_elements(),pVertForce,1);
                        // Scatter back soln from linear solve
                        for(i = 0; i < nloc; ++i)
                        {
                            val = LocToGloBnd[i];
                            if(val >= nDirFull)
                            {
                                pOutput[val-nDirFull] = Out[LocToGlo[i]];
                                // copy vertex forcing into this vector
                                pVertForce[val-nDirFull] = In[LocToGlo[i]];
                            }
                        }
                    }
                    else
                    {
                        // Scatter back soln from linear solve
                        for(i = 0; i < nloc; ++i)
                        {
                            val = LocToGloBnd[i];
                            if(val >= nDirFull)
                            {
                                pOutput[val-nDirFull] = Out[LocToGlo[i]];
                            }
                        }
                    }
                }
                break;
            default:
                ASSERTL0(0,"Unsupported solver type");
                break;
	    }
        }
Ejemplo n.º 7
0
void In(const PingTwins__msg_impl * msg_data) {
	printf("In%i: Ping recv'd, sending pong.\n",ID);
	Out(msg_data);	
}
Ejemplo n.º 8
0
	void Actor::PrintPose() const
	{
		if (m_actor.dynamicActor)
		{
			Out(std::to_string(m_actor.dynamicActor->getGlobalPose().p.x).c_str());
			Out(" ");
			Out(std::to_string(m_actor.dynamicActor->getGlobalPose().p.y).c_str());
			Out(" ");
			Out(std::to_string(m_actor.dynamicActor->getGlobalPose().p.z).c_str());
			Out("\n");
		}
		else if (m_actor.staticActor)
		{
			Out(std::to_string(m_actor.staticActor->getGlobalPose().p.x).c_str());
			Out(" ");
			Out(std::to_string(m_actor.staticActor->getGlobalPose().p.y).c_str());
			Out(" ");
			Out(std::to_string(m_actor.staticActor->getGlobalPose().p.z).c_str());
			Out("\n");
		}
	}
Ejemplo n.º 9
0
static void OutNL()
{
    Out( "\r\n" );
}
Ejemplo n.º 10
0
bool CCommandObj::FormatResourceHander(PRESOURCEREQUIT pResourceRequit,PRESOURCESENDINFO pResourceObj,__out LPTSTR lpFileFullName)
{
	OutA(Dbg,("Format Resource[%s] Hander Starting."),pResourceRequit->szResourceID);
	bool bRet = TRUE;
	FILE * fConfigFile = NULL;
	CFileExpress cFileExpress;
	DATAPHOENIX dDataPhoenix;

	FormatResourceFullName(pResourceRequit->szResourceID,lpFileFullName,MAX_PATH);
	if (!stricmp(pResourceRequit->szResourceID,MANAGER_CLSID))
	{
		Out(Dbg,_T("Format Resource Config: [%s] Starting."),lpFileFullName);
		cFileExpress.Initialization(lpFileFullName);

		strcpy_s(dDataPhoenix.FilePath,".\\");
		strcpy_s(dDataPhoenix.MD5,cFileExpress.GetFileMD5(32));
		strcpy_s(dDataPhoenix.FileName,"System.Initialization.DLL");
		strcpy_s(dDataPhoenix.CLSID,pResourceRequit->szResourceID);

		dDataPhoenix.dwFileSize = cFileExpress.GetFileSize();
		Out(Dbg,_T("Format Resource Config:[%s] Success."),lpFileFullName);

		pResourceObj->dwResourceType = TYPE_RESOURCE_SYSTEM;
	}else
	{	
		PathRemoveExtension(lpFileFullName);
		PathAddExtension(lpFileFullName,_T(".Cfg"));

		Out(Dbg,_T("Format Resource Config: [%s] Starting."),lpFileFullName);
		if (0 !=_tfopen_s(&fConfigFile,lpFileFullName,_T("rb")))
		{
			Out(Dbg,_T("Format Resource Config: [%s] Failed."),lpFileFullName);
			bRet =  false;
			return bRet;
		}else
		{
			fseek(fConfigFile,sizeof(RESOURCEREQUIT),SEEK_SET);
			fread(&dDataPhoenix,1,sizeof(DATAPHOENIX),fConfigFile);
			fflush(fConfigFile);
			fclose(fConfigFile);
			bRet = true;
		}

		Out(Dbg,_T("Format Resource Config:[%s] Success."),lpFileFullName);

		FormatResourceFullName(pResourceRequit->szResourceID,lpFileFullName,MAX_PATH);


		pResourceObj->dwResourceType = TYPE_RESOURCE_EXECFILE;//TYPE_RESOURCE_DATAFILE;
	}


	pResourceObj->dwResourceLen = dDataPhoenix.dwFileSize;

//	memcpy_s(&pResourceObj->btResourceBag,MAX_BAG_LEN,&m_btResourceBag,MAX_BAG_LEN);

	strcpy_s(pResourceObj->szResourceID,dDataPhoenix.CLSID);

	strcpy_s(pResourceObj->szResourceMD5,dDataPhoenix.MD5);

	strcpy_s(pResourceObj->szResourcePath,dDataPhoenix.FilePath);
	PathAddBackslashA(pResourceObj->szResourcePath);
	strcat_s(pResourceObj->szResourcePath,dDataPhoenix.FileName);

	OutA(Dbg,("Resource[%s] Info: Size:%d MD5:%s FilePath:%s FileName:%s."),dDataPhoenix.CLSID,dDataPhoenix.dwFileSize,dDataPhoenix.MD5,dDataPhoenix.FilePath,dDataPhoenix.FileName);
	OutA(Dbg,("Format Resource[%s] Hander Successful."),pResourceRequit->szResourceID);

	return bRet;
}
Ejemplo n.º 11
0
	void SingleCacheChecker::check(const QString& cache, const QString& index)
	{
		loadIndex(index);
		Uint32 num_chunks = tor.getNumChunks();
		File fptr;
		if (!fptr.open(cache,"rb"))
		{
			throw Error(QString("Cannot open file : %1 : %2")
					.arg(cache).arg( fptr.errorString()));
		}

		Uint32 num_ok = 0,num_not_ok = 0,num_not_downloaded = 0,extra_ok = 0;

		Array<Uint8> buf((Uint32)tor.getChunkSize());
		for (Uint32 i = 0;i < num_chunks;i++)
		{
			if (i % 100 == 0)
				Out(SYS_GEN|LOG_DEBUG) << "Checked " << i << " chunks" << endl;
	//	Out() << "Chunk " << i << " : ";
			if (!fptr.eof())
			{
				Uint32 size = i == num_chunks - 1 && tor.getFileLength() % tor.getChunkSize() > 0 ?
						tor.getFileLength() % tor.getChunkSize() : (Uint32)tor.getChunkSize();
				fptr.seek(File::BEGIN,(Int64)i*tor.getChunkSize());
				fptr.read(buf,size);
				SHA1Hash h = SHA1Hash::generate(buf,size);
				bool ok = (h == tor.getHash(i));
				if (ok)
				{
					if (downloaded_chunks.count(i) == 0)
					{
						extra_ok++;
						extra_chunks.insert(i);
						continue;
					}
					num_ok++;
		//		Out() << "OK" << endl;
				}
				else
				{
					if (downloaded_chunks.count(i) == 0)
					{
						num_not_downloaded++;
						continue;
					}
					Out() << "Chunk " << i << " Failed :" << endl;
					Out() << "\tShould be : " << tor.getHash(i).toString() << endl;
					Out() << "\tIs        : " << h.toString() << endl;
					num_not_ok++;
					failed_chunks.insert(i);
				}
			
			}
			else
			{
				num_not_downloaded++;
			//Out() << "Not Downloaded" << endl;
			}
		}
		Out() << "Cache Check Summary" << endl;
		Out() << "===================" << endl;
		Out() << "Extra Chunks : " << extra_ok << endl;
		Out() << "Chunks OK : " << num_ok << endl;
		Out() << "Chunks Not Downloaded : " << num_not_downloaded << endl;
		Out() << "Chunks Failed : " << num_not_ok << endl;
	}
Ejemplo n.º 12
0
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int	CProcessor::StopoutsApply(const UserInfo *user, const ConGroup *group,
                              const char *comment)
{
    Out(CmdOK, "CProcessor::StopoutsApply - Applying stopout for user [%d]", user->login);

    TradeRecord    *trades,*trade;
    int            total, i;
    ConSymbol      symbol = {0};
    TradeTransInfo trans  = {0};
    time_t         currtime;
    char           stopout[64] = "[stopout]";
    const char	   *cp;

    // check
    if (user == NULL || group == NULL || comment == NULL)
    {
        Out(CmdOK, "CProcessor::StopoutsApply - check failed");
        return RET_OK;
    }
    // lock
    m_sync.Lock();

    // check user group
    if (CheckGroup(m_groups, group->group) == FALSE)
    {
        Out(CmdOK, "CProcessor::StopoutsApply - group check failed");
        m_sync.Unlock();
        return(RET_OK);
    }

    // receive all opened trades for user
    if ((trades = ExtServer->OrdersGetOpen(user, &total)) == NULL)
    {
        Out(CmdOK, "CProcessor::StopoutsApply - no open trade");
        return RET_OK;
    }
    // get current server time
    currtime = ExtServer->TradeTime();
    // prepare comment about stopout
    if ((cp = strrchr(comment, '[')) != NULL) COPY_STR(stopout, cp);
    // output to server log
    Out(CmdOK, "'%d': close all orders due stop out %s", user->login, stopout);
    // go trough trades
    for (i = 0, trade = trades; i < total; i++, trade++)
    {
        // it is opened trade
        if (trade->cmd > OP_SELL) continue;
        // check symbol - зачем?
        // if (CheckGroup(m_symbols, trade->symbol) == FALSE) continue;
        // check volume - зачем?
        // if (m_max_volume != 0 && trade->volume > m_max_volume) continue;
        // receive symbol information
        if (ExtServer->SymbolsGet(trade->symbol, &symbol) == FALSE)
        {
            Out(CmdAtt, "stopout: receiving information for %s symbol failed", trade->symbol);
            continue;
        }

        // check trade session for symbol
        if (ExtServer->TradesCheckSessions(&symbol, currtime) == FALSE) continue;
        // prepare transaction
        trans.order  = trade->order;
        trans.price  = trade->close_price;
        trans.volume = trade->volume;
        trans.type   = TT_ORDER_MK_CLOSE; // !
        // prepare comment
        if (trade->comment[0] != 0)
        {
            COPY_STR(trans.comment, trade->comment);
            if (strstr(trans.comment, stopout) == NULL)
                _snprintf(trans.comment, sizeof(trans.comment) - 1, "%s %s", trans.comment, "[stopout FXI]");
        }
        else
            COPY_STR(trans.comment, stopout);

        // отправить запрос на закрытие позиции на сервер
        // создать запрос
        RequestInfo inf = { 0 };
        memcpy(&(inf.trade), &trans, sizeof(TradeTransInfo));
        inf.login = user->login;
        inf.id = trade->order; // startStopoutRequestId++; // !!
        memcpy(&inf.group, &group->group, sizeof(inf.group));
        memcpy(&inf.trade.symbol, &trade->symbol, sizeof(trade->symbol));
        // добавить в очередь
        Add(&inf, TRUE);
    }
    m_sync.Unlock();
    // free memory
    HEAP_FREE(trades);
    // сервер больше не процессит стопаут
    return RET_OK_NONE;
}
Ejemplo n.º 13
0
int CProcessor::Add(const UserInfo *user, const ConGroup *group, const ConSymbol *symbol,
                    const TradeRecord *pending, TradeRecord *trade)
{
    Request *temp;
    UINT     id;
    static int uid = 1;
    CharString str;

    if (pending == NULL || trade == NULL) return(FALSE);
    // проверки - кто управляет счетом
    if (m_delay == 0 || CheckGroup(m_groups, group->group) == FALSE)
        return (TRUE);

    double    prices[2];
    // получим текущие цены для группы и установки символа
    if (ExtServer->HistoryPricesGroup(symbol->symbol, group, prices) != RET_OK)
    {
        str.Printf(FALSE, "CProcessor::Add Pending (symbol [%s], group [%s]) failed", symbol->symbol, group->group);
        ExtServer->LogsOut(CmdOK, PROGRAM_TITLE, str.ToArray());
        return FALSE;
    }

    m_sync.Lock();

    // проверить - нет ли такого запроса в списке
    Request  *reqTmp;
    if (m_requests != NULL)
    {
        int i = 0;
        for (reqTmp = m_requests; i < m_requests_total; i++, reqTmp++)
        {
            if (reqTmp->isPending)
                if (reqTmp->pendingId == pending->order)
                {
                    ExtServer->LogsOut(CmdOK, PROGRAM_TITLE, "Отложенный ордер уже в списке");
                    m_sync.Unlock();
                    return (TRUE);
                }
        }
    }

    // лог
    /*char reqCmdStr[64];
    FormatCommand(pending->cmd, reqCmdStr);
    str.Printf(FALSE, "CProcessor::Add Pending(order [%d], cmd [%s], req Id [%d])",
    	pending->order, reqCmdStr, startPendingRequestId);
    ExtServer->LogsOut(CmdOK, PROGRAM_TITLE, str.ToArray());*/


    //---- если место для запросов нет выделим
    if(m_requests == NULL)
    {
        if((m_requests = new Request[256]) == NULL)
        {
            m_sync.Unlock();
            return (FALSE);
        }
        m_requests_max = 256;
        m_requests_total = 0;
    }
    //---- посмотрим может надо перевыделить
    if (m_requests_total >= m_requests_max)
    {
        if((temp = new Request[m_requests_max + 256]) == NULL)
        {
            m_sync.Unlock();
            return(FALSE);
        }
        //---- скопируем старое
        memcpy(temp, m_requests, sizeof(Request) * m_requests_total);
        //---- удалим уже не нужное
        delete m_requests;

        m_requests = temp;
        m_requests_max += 256;
    }
    //---- вставляем запрос
    m_requests[m_requests_total].pendingId = pending->order;
    m_requests[m_requests_total].isPending = TRUE;
    m_requests[m_requests_total].id = startPendingRequestId++;
    m_requests[m_requests_total].time = GetTickCount();
    m_requests[m_requests_total].sent = FALSE;
    m_requests[m_requests_total].login = user->login;
    memcpy(&m_requests[m_requests_total].trans, pending, sizeof(TradeTransInfo));
    m_requests[m_requests_total].trans.volume = trade->volume;
    Out(CmdOK, "Pending order %d added of volume %d",
        m_requests[m_requests_total].id, trade->volume);
    COPY_STR(m_requests[m_requests_total].group, group->group);
    // поправить команду
    char origTradeCmd[32], newTradeCmd[32];
    FormatCommand(m_requests[m_requests_total].trans.cmd, origTradeCmd);

    int pendCmd = trade->cmd; //m_requests[m_requests_total].trans.cmd;
    pendCmd = (pendCmd == OP_BUY_LIMIT || pendCmd == OP_BUY_STOP) ? OP_BUY
              : (pendCmd == OP_SELL_LIMIT || pendCmd == OP_SELL_STOP) ? OP_SELL
              : pendCmd;
    m_requests[m_requests_total].trans.cmd = pendCmd;
    FormatCommand(m_requests[m_requests_total].trans.cmd, newTradeCmd);

    m_requests[m_requests_total].trans.type = TT_ORDER_MK_OPEN;
    m_requests[m_requests_total].trans.price = pendCmd == OP_BUY ? prices[1] : prices[0];
    strcpy(m_requests[m_requests_total].trans.symbol, symbol->symbol);
    m_requests[m_requests_total].trans.order = pending->order;

    str.Printf(FALSE, "Отложенный ордер %d добавлен, всего %d (%s, теперь %s)",
               pending->order, m_requests_total, origTradeCmd, newTradeCmd);
    ExtServer->LogsOut(CmdOK, PROGRAM_TITLE, str.ToArray());

    m_requests_total++;
    //---- запускаем поток
    if (m_thread == NULL)
        if ((m_thread = (HANDLE)_beginthreadex(NULL, 256000, ThreadFunction, this, 0, &id))==NULL)
        {
            m_sync.Unlock();
            return(FALSE);
        }

    m_sync.Unlock();
    return(TRUE);
}
Ejemplo n.º 14
0
long Gao(T now, long k) {
    if (k < 0) return
            Out(now) ? 0 : 1;
    double flag = S1(now.x - a[k].P1.x, now.y - a[k].P1.y, a[k].P2.x - a[k].P1.x, a[k].P2.y - a[k].P1.y);
    return More(flag, 0) ? 0 : Gao(now, k - 1) + Gao(Cross(now, a[k]), k - 1);
}
Ejemplo n.º 15
0
void DumpProperties(BaseEngine *engine)
{
    Out("\t<Properties\n");
    ScopedMem<char> str;
    str.Set(Escape((WCHAR *)engine->FileName(), true));
    Out("\t\tFilePath=\"%s\"\n", str.Get());
    str.Set(Escape(engine->GetProperty(Prop_Title)));
    if (str)
        Out("\t\tTitle=\"%s\"\n", str.Get());
    str.Set(Escape(engine->GetProperty(Prop_Subject)));
    if (str)
        Out("\t\tSubject=\"%s\"\n", str.Get());
    str.Set(Escape(engine->GetProperty(Prop_Author)));
    if (str)
        Out("\t\tAuthor=\"%s\"\n", str.Get());
    str.Set(Escape(engine->GetProperty(Prop_Copyright)));
    if (str)
        Out("\t\tCopyright=\"%s\"\n", str.Get());
    str.Set(Escape(engine->GetProperty(Prop_CreationDate)));
    if (str)
        Out("\t\tCreationDate=\"%s\"\n", str.Get());
    str.Set(Escape(engine->GetProperty(Prop_ModificationDate)));
    if (str)
        Out("\t\tModDate=\"%s\"\n", str.Get());
    str.Set(Escape(engine->GetProperty(Prop_CreatorApp)));
    if (str)
        Out("\t\tCreator=\"%s\"\n", str.Get());
    str.Set(Escape(engine->GetProperty(Prop_PdfProducer)));
    if (str)
        Out("\t\tProducer=\"%s\"\n", str.Get());
    str.Set(Escape(engine->GetProperty(Prop_PdfVersion)));
    if (str)
        Out("\t\tPdfVersion=\"%s\"\n", str.Get());
    str.Set(Escape(engine->GetProperty(Prop_PdfFileStructure)));
    if (str)
        Out("\t\tPdfFileStructure=\"%s\"\n", str.Get());
    if (!engine->IsPrintingAllowed())
        Out("\t\tPrintingAllowed=\"no\"\n");
    if (!engine->IsCopyingTextAllowed())
        Out("\t\tCopyingTextAllowed=\"no\"\n");
    if (engine->IsImageCollection())
        Out("\t\tImageCollection=\"yes\"\n");
    if (engine->PreferredLayout())
        Out("\t\tPreferredLayout=\"%d\"\n", engine->PreferredLayout());
    Out("\t/>\n");

    ScopedMem<WCHAR> fontlist(engine->GetProperty(Prop_FontList));
    if (fontlist) {
        WStrVec fonts;
        fonts.Split(fontlist, L"\n");
        str.Set(Escape(fonts.Join(L"\n\t\t")));
        Out("\t<FontList>\n\t\t%s\n\t</FontList>\n", str.Get());
    }
}
Ejemplo n.º 16
0
static void OutBuff( TRACEBUF far *buf )
{
    Out( "pid   = " ); OutNum( buf->pid ); Out( "\r\n" );
    Out( "tid   = " ); OutNum( buf->tid ); Out( "\r\n" );
    Out( "cmd   = " ); OutNum( buf->cmd ); Out( "\r\n" );
    Out( "value = " ); OutNum( buf->value ); Out( "\r\n" );
    Out( "offv  = " ); OutNum( buf->offv ); Out( "\r\n" );
    Out( "segv  = " ); OutNum( buf->segv ); Out( "\r\n" );
    Out( "mte   = " ); OutNum( buf->mte ); Out( "\r\n" );
}
Ejemplo n.º 17
0
int TableGenMain(char *argv0, TableGenAction &Action) {
  RecordKeeper Records;

  try {
    // Parse the input file.
    OwningPtr<MemoryBuffer> File;
    if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename.c_str(), File)) {
      errs() << "Could not open input file '" << InputFilename << "': "
             << ec.message() <<"\n";
      return 1;
    }
    MemoryBuffer *F = File.take();

    // Tell SrcMgr about this buffer, which is what TGParser will pick up.
    SrcMgr.AddNewSourceBuffer(F, SMLoc());

    // Record the location of the include directory so that the lexer can find
    // it later.
    SrcMgr.setIncludeDirs(IncludeDirs);

    TGParser Parser(SrcMgr, Records);

    if (Parser.ParseFile())
      return 1;

    std::string Error;
    tool_output_file Out(OutputFilename.c_str(), Error);
    if (!Error.empty()) {
      errs() << argv0 << ": error opening " << OutputFilename
        << ":" << Error << "\n";
      return 1;
    }
    if (!DependFilename.empty()) {
      if (OutputFilename == "-") {
        errs() << argv0 << ": the option -d must be used together with -o\n";
        return 1;
      }
      tool_output_file DepOut(DependFilename.c_str(), Error);
      if (!Error.empty()) {
        errs() << argv0 << ": error opening " << DependFilename
          << ":" << Error << "\n";
        return 1;
      }
      DepOut.os() << OutputFilename << ":";
      const std::vector<std::string> &Dependencies = Parser.getDependencies();
      for (std::vector<std::string>::const_iterator I = Dependencies.begin(),
                                                          E = Dependencies.end();
           I != E; ++I) {
        DepOut.os() << " " << (*I);
      }
      DepOut.os() << "\n";
      DepOut.keep();
    }

    if (Action(Out.os(), Records))
      return 1;

    // Declare success.
    Out.keep();
    return 0;

  } catch (const TGError &Error) {
    PrintError(Error);
  } catch (const std::string &Error) {
    PrintError(Error);
  } catch (const char *Error) {
    PrintError(Error);
  } catch (...) {
    errs() << argv0 << ": Unknown unexpected exception occurred.\n";
  }

  return 1;
}
Ejemplo n.º 18
0
// '#' 'version' NUMBER PROFILE?
void GLSLPreProcessor::ParseDirectiveVersion()
{
    /* Check if version was already defined */
    if (versionDefined_)
    {
        Error(R_GLSLVersionAlreadyDefined(versionNo_), true, false);
        IgnoreDirective();
        return;
    }

    versionDefined_ = true;

    /* Parse version number */
    IgnoreWhiteSpaces();

    auto versionTkn = Accept(Tokens::IntLiteral);
    versionNo_ = std::stoi(versionTkn->Spell());

    /* Parse profile */
    bool isESSL = false;
    bool isCompatibilityProfile = false;
    std::string profile;

    IgnoreWhiteSpaces();
    if (Is(Tokens::Ident))
    {
        profile = Accept(Tokens::Ident)->Spell();

        if (profile == "es")
        {
            /* Parse version for ESSL (OpenGL ES) */
            isESSL = true;
        }
        else
        {
            /* Parse version for GLSL (OpenGL or Vulkan) */
            if (profile == "compatibility")
                isCompatibilityProfile = true;
            else if (profile != "core")
                Error(R_InvalidGLSLVersionProfile(profile), true, false);
        }
    }

    if (isESSL)
    {
        /* Verify ESSL version number */
        static const int versionsESSL[] =
        {
            100, 300, 310, 320, 0
        };

        if (!VerifyVersionNo(versionsESSL))
            Error(R_UnknownESSLVersion(versionNo_), versionTkn.get(), false);
    }
    else
    {
        /* Verify GLSL version number */
        static const int versionsGLSL[] =
        {
            110, 120, 130, 140, 150, 330, 400, 410, 420, 430, 440, 450, 460, 0
        };

        if (!VerifyVersionNo(versionsGLSL))
            Error(R_UnknownGLSLVersion(versionNo_), versionTkn.get(), false);

        /* Only GLSL 150+ allows a profile */
        if (!profile.empty() && versionNo_ < 150)
            Error(R_NoProfileForGLSLVersionBefore150, true, false);
    }

    /* Write out version */
    Out() << "#version " << versionNo_;

    if (!profile.empty())
        Out() << ' ' << profile;

    /*
    Define standard macros: 'GL_core_profile', 'GL_es_profile', 'GL_compatibility_profile'
    see https://www.khronos.org/opengl/wiki/Core_Language_(GLSL)#Standard_macros
    */
    DefineStandardMacro("GL_core_profile");

    if (isESSL)
    {
        DefineStandardMacro("GL_es_profile");
        DefineStandardMacro("GL_ES");
    }
    else if (isCompatibilityProfile)
        DefineStandardMacro("GL_compatibility_profile");

    DefineStandardMacro("__VERSION__", versionNo_);
}
Ejemplo n.º 19
0
/*
 * AccLoadProg
 *
 * To load a app, we do the following:
 *
 *  Case 1: debugging an existing task
 *      - Find its current CS:IP.
 *      - Plant a breakpoint at the current CS:IP
 *
 *  Case 2: starting a task from scratch
 *      - Look up the start address from the .EXE
 *      - WinExec the app
 *      - Wait for the STARTASK notification for the app
 *      - Plant a breakpoint at its start address
 *
 *  - Wait for the app to hit the breakpoint
 *  - Check if the app is a 32-bit app (look for "DEADBEEF" in code seg).
 *     If it is a 32-bit app:
 *      - Flip the "DEADBEEF" to "BEEFDEAD".  If the extender see's the
 *        "BEEFDEAD", it executes a breakpoint right before it jumps to
 *        the 32-bit code
 *      - Let the app run until a breakpoint is hit
 *      - Trace one instruction. This leaves you at the first instruction
 *        of the 32-bit code
 */
unsigned ReqProg_load( void )
{
    char                exe_name[_MAX_PATH];
    char                drive[_MAX_DRIVE],directory[_MAX_DIR];
    char                buff[256];
    lm_parms            loadp;
    word_struct         cmdshow;
    char                *parm;
    char                *src;
    char                *dst;
    char                ch;
    unsigned            a,b;
    private_msg         pmsg;
    char                sig[sizeof(DWORD)];
    HTASK               tid;
    DWORD               csip;
    prog_load_req       *acc;
    prog_load_ret       *ret;
    char                *end;

    acc = GetInPtr( 0 );
    ret = GetOutPtr( 0 );
    ret->flags = LD_FLAG_IS_PROT | LD_FLAG_HAVE_RUNTIME_DLLS;
    parm = GetInPtr( sizeof( *acc ) );

    /*
     * reset flags
     */
    OutPos = 0;
    WasStarted = FALSE;
    LoadingDebugee = TRUE;
    Debugging32BitApp = FALSE;
    AddAllCurrentModules();

    /*
     * check for task id
     */
    tid = 0;
    src = parm;
    if( *src == '#' ) {
        src++;
        tid = (HTASK)strtol( src, NULL, 16 );
    } else {
        while( *src != 0 ) {
            if( !isdigit( *src ) ) {
                break;
            }
            src++;
        }
        if( *src == 0 && src != parm ) {
            tid = (HTASK)atoi( parm );
        }
    }
    if( tid != 0 ) {
        csip = GetRealCSIP( tid, &DebugeeModule );
        if( csip == 0 ) {
            tid = 0;
        } else {
            DebugeeTask = tid;
            StopNewTask.loc.segment = FP_SEG( (LPVOID) csip );
            StopNewTask.loc.offset = FP_OFF( (LPVOID) csip );
            ReadMem( StopNewTask.loc.segment, StopNewTask.loc.offset,
                    &StopNewTask.value, 1 );
            ch = 0xcc;
            WriteMem( StopNewTask.loc.segment, StopNewTask.loc.offset, &ch, 1 );
        }
    } else {
        tid = 0;
    }

    /*
     * get the file to execute
     */
    if( tid == 0 ) {
        if( TINY_ERROR( FindFilePath( parm, exe_name, ExtensionList ) ) ) {
            exe_name[0] = 0;
        } else {
            _splitpath( exe_name, drive, directory, NULL, NULL );
            a = tolower( drive[0] ) - 'a' + 1;
            _dos_setdrive( a, &b );
            directory[ strlen( directory ) - 1 ] = 0;
            chdir( directory );
        }

        /*
         * get the parm list
         */

        src = parm;
        while( *src != 0 )
            ++src;
        ++src;
        end = GetInPtr( GetTotalSize() - 1 );
        dst = &buff[1];
        for( ;; ) {
            if( src > end )
                break;
            ch = *src;
            if( ch == 0 )
                ch = ' ';
            *dst = ch;
            ++dst;
            ++src;
        }
        if( dst > &buff[1] )
            --dst;
        *dst = '\0';
        buff[0] = dst-buff-1;

        /*
         * get starting point in task
         */
        if( !GetStartAddress( exe_name, &StopNewTask.loc ) ) {
            Out((OUT_ERR,"Could not get starting address"));
            ret->err = WINERR_NOSTART;
            LoadingDebugee = FALSE;
            return( sizeof( *ret ) );
        }
        StopNewTask.segment_number = StopNewTask.loc.segment;
        Out((OUT_LOAD,"Loading %s, cs:ip = %04x:%04lx", exe_name, StopNewTask.loc.segment,
                            StopNewTask.loc.offset ));

        /*
         * load the task
         */
        loadp.cmdshow = &cmdshow;
        loadp.wEnvSeg = 0;
        loadp.lpCmdLine = (LPSTR) buff;
        loadp.cmdshow->mustbe2 = 2;
        loadp.cmdshow->cmdshow = SW_NORMAL;
        loadp.reserved = 0L;
        DebuggerState = LOADING_DEBUGEE;
        DebugeeInstance = LoadModule( exe_name, (LPVOID) &loadp );
        if( (UINT)DebugeeInstance < 32 ) {
            Out((OUT_ERR,"Debugee did not load %d", DebugeeInstance));
            ret->err = WINERR_NOLOAD;
            LoadingDebugee = FALSE;
            return( sizeof( *ret ) );
        }
        DebuggerWaitForMessage( WAITING_FOR_TASK_LOAD, NULL, RESTART_APP );
    }
    AddDebugeeModule();
    pmsg = DebuggerWaitForMessage( WAITING_FOR_BREAKPOINT, DebugeeTask, RESTART_APP );
    if( pmsg == START_BP_HIT ) {

        ret->err = 0;
        ret->task_id = (unsigned_32)DebugeeTask;

        /*
         * look for 32-bit windows application
         */
        ReadMem( IntResult.CS, SIG_OFF, sig, sizeof( DWORD ) );
        if( !StopOnExtender && (!memcmp( sig, win386sig, 4 ) ||
                !memcmp( sig, win386sig2, 4 )) ) {
            Out((OUT_LOAD,"Is Win32App" ));
            Debugging32BitApp = TRUE;
            /*
             * make sure that WDEBUG.386 is installed
             */
            if( !WDebug386 ) {
                ret->err = WINERR_NODEBUG32; /* Can't debug 32 bit app */
                LoadingDebugee = FALSE;
                return( sizeof( *ret ) );
            }
            ret->flags |= LD_FLAG_IS_32;
            if( tid == 0 ) {
                WriteMem( IntResult.CS, SIG_OFF, win386sig2, sizeof( DWORD ) );
                pmsg = DebuggerWaitForMessage( GOING_TO_32BIT_START,
                                DebugeeTask, RESTART_APP );
                if( pmsg == FAULT_HIT && IntResult.InterruptNumber == INT_3 ) {
                    IntResult.EIP++;
                    SingleStepMode();
                    pmsg = DebuggerWaitForMessage( GOING_TO_32BIT_START,
                                DebugeeTask, RESTART_APP );
                    if( pmsg != FAULT_HIT || IntResult.InterruptNumber != INT_1 ) {
                        Out((OUT_ERR,"Expected INT_1 not found"));
                        ret->err = WINERR_NOINT1;
                    }
                } else {
                    Out((OUT_ERR,"Expected INT_3 not found"));
                    ret->err = WINERR_NOINT3;
                }
            }
        }
        if( tid != 0 ) {
            ret->flags |= LD_FLAG_IS_STARTED;
            WasStarted = TRUE;
        }
    } else {
        Out((OUT_ERR,"Starting breakpoint not found, pmsg=%d", pmsg ));
        ret->err = WINERR_STARTNOTFOUND;
    }
#if 0
    if( DebugeeTask != NULL ) {
        InitASynchHook();
    }
#endif
    LoadingDebugee = FALSE;
    CurrentModule = 1;
    ret->mod_handle = 0;
    return( sizeof( *ret ) );
}
Ejemplo n.º 20
0
void	TriMesh::Process( uint32_t inStartOffset,
										uint32_t inEndOffset )
{
	uint32_t dataLen = inEndOffset - inStartOffset;
	
	if (dataLen < 52)
	{
		throw DataLengthException( Name(), inStartOffset, inEndOffset, 52 );
	}
	
	mFaces = FetchUInt32( inStartOffset );
	uint32_t numFaceAtts = FetchUInt32( inStartOffset+4 );
	mEdges = FetchUInt32( inStartOffset+8 );
	uint32_t numEdgeAtts = FetchUInt32( inStartOffset+12 );
	mPoints = FetchUInt32( inStartOffset+16 );
	uint32_t numPointAtts = FetchUInt32( inStartOffset+20 );
	
	int bytesPointIndex, bytesPerFaceIndex;
	if (mPoints - 1 <= 0xFE)
	{
		bytesPointIndex = 1;
	}
	else if (mPoints - 1 <= 0xFFFE)
	{
		bytesPointIndex = 2;
	}
	else
	{
		bytesPointIndex = 4;
	}

	if (mFaces - 1 <= 0xFE)
	{
		bytesPerFaceIndex = 1;
	}
	else if (mFaces - 1 <= 0xFFFE)
	{
		bytesPerFaceIndex = 2;
	}
	else
	{
		bytesPerFaceIndex = 4;
	}
	
	uint32_t trianglesSize = mFaces * 3 * bytesPointIndex;
	uint32_t edgesSize = mEdges * 2 * (bytesPointIndex + bytesPerFaceIndex);
	uint32_t pointsSize = mPoints * 12;
	uint32_t expectedLength = 52 + trianglesSize + edgesSize + pointsSize;
	if (dataLen != expectedLength)
	{
		throw DataLengthException( Name(), inStartOffset, inEndOffset,
			expectedLength );
	}
	
	Out() << Indent() << Name() << " (\n" <<
	
		Indent(1) << mFaces << " " << numFaceAtts << " " <<
			mEdges << " " << numEdgeAtts << " " <<
			mPoints << " " << numPointAtts << "\t" <<
			"# faces faceAtts edges edgeAtts pts ptAtts\n";

	WriteTriangles( inStartOffset+24, mFaces, bytesPointIndex );
	WriteEdges( inStartOffset+24+trianglesSize, mEdges, bytesPointIndex,
		bytesPerFaceIndex );
	WritePoints( inStartOffset+24+trianglesSize+edgesSize, mPoints );
	WriteBoundingBox( inStartOffset+24+trianglesSize+edgesSize+pointsSize );
	
	Out() << Indent() << ")\n";
}
Ejemplo n.º 21
0
/*
 * FaultHandler:
 *
 * Handle all faults.
 *
 * When we get a fault, the first thing we do is check if we are using
 * WDEBUG.386.  If we are, we call GetDebugInterruptData in WINT32.DLL
 * to see if the fault was a 32-bit one.  If it was, the structure
 * IntResult will be filled in.
 *
 * We make sure that we are not already handling a fault.  If we
 * are, we punt and give it to the next guy.
 *
 * We disable the hot key for doing CTRL_ALT_F (in WDEBUG.386), to make
 * sure that we are not interrupted while in the debugger!
 *
 * If we get an INT3, and it was NOT a 32-bit fault, we back up IP.
 * (If it was a 32-bit fault, it is communicated as a breakpoint, and
 * we don't need to back up IP). We then check if we were waiting for
 * the breakpoint, and if we were, we write back the original byte.
 *
 * If it was not a 32-bit fault, we call saveState, which copies the
 * correct data into the IntResult structure (this is the structure
 * that we use to access/update the registers, see accregs.c).
 *
 * We then directed yield to the debugger, and go into a message loop
 * for the debuggee.
 *
 * Once the debuggee exits its message loop, we check to see if we
 * need to do a special request (access a segment or do an I/O redirection).
 *
 * If there was no special request, we then reset the app's registers
 * (with restoreState for a 16-bit fault, and DoneWithInterreupt in WINT32.DLL
 * for a 32-bit fault), re-enable the hot key for async stopping,
 * and return to IntHandler to allow it to restart the debuggee.
 */
void __loadds __cdecl FaultHandler( volatile fault_frame ff )
{
    restart_opts        rc=CHAIN;
    private_msg         pmsg = FAULT_HIT;
    WORD                sig[2];

    WasInt32 = false;
    if( WDebug386 ) {
        WasInt32 = (bool)GetDebugInterruptData( &IntResult );
        if( WasInt32 ) {
            ff.intf.intnumber = IntResult.InterruptNumber;
            Out((OUT_RUN,"***** 32-bit fault %d, cs:eip=%04x:%08lx *****",
                IntResult.InterruptNumber, IntResult.CS, IntResult.EIP ));
        }
    }
    newStack( 0, 0L );

    /*
     * only one fault at a time
     */
    Out((OUT_RUN,"***** Fault %d, cs:ip=%04x:%04x, ent=%d, state=%d, WasInt32=%d *****",
        ff.intf.intnumber, ff.intf.CS, ff.intf.IP, FaultHandlerEntered,
        (WORD)DebuggerState, WasInt32 ));
    if( FaultHandlerEntered || DebuggerState == ACTIVE ) {
        if( ff.intf.intnumber == WGOD_ASYNCH_STOP_INT ) {
            setRetHow( RESTART_APP );
        } else {
            setRetHow( CHAIN );
        }
        return;
    }
    UseHotKey( 0 );

    ff.ESP = (WORD) ff.ESP;
    ff.intf.oldEBP = (WORD) ff.intf.oldEBP;

    if( ff.intf.intnumber == INT_3 ) {
        if( !WasInt32 ) {
            ff.intf.IP--;
        }
        Out((OUT_ERR,"BP at '(%d) %4.4x:%4.4x %4.4x:%8.8lx'",WasInt32,ff.intf.CS,ff.intf.IP,
        IntResult.CS,IntResult.EIP));
        if( ( WasInt32 && IntResult.CS == DLLLoadCS && IntResult.EIP == DLLLoadIP ) ||
            ( !WasInt32 && ff.intf.CS == DLLLoadCS && ff.intf.IP == DLLLoadIP ) ) {
            Out((OUT_RUN,"Caught DLL Loaded '%4.4x:%4.4x'",DLLLoadCS,DLLLoadIP));
            WriteMem( DLLLoadCS, DLLLoadIP, &DLLLoadSaveByte, 1 );
            ReadMem( IntResult.CS, SIG_OFF, sig, sizeof( DWORD ) );
            if( memcmp( sig, win386sig, 4 ) == 0 ) {
                Out((OUT_RUN,"Zapped sig"));
                WriteMem( IntResult.CS, SIG_OFF, win386sig2, sizeof( DWORD ) );
                pmsg = DLL_LOAD32;
                DLLLoadExpectingInt1 = TRUE;
            } else {
                pmsg = DLL_LOAD;
            }
            DLLLoadCS = 0;
            DLLLoadIP = 0;
        } else if( DebuggerState == WAITING_FOR_BREAKPOINT ) {
            if( (WasInt32 && IntResult.CS == StopNewTask.loc.segment &&
                        IntResult.EIP == StopNewTask.loc.offset ) ||
                (!WasInt32 && ff.intf.CS == StopNewTask.loc.segment &&
                        ff.intf.IP == StopNewTask.loc.offset) ) {
                WriteMem( StopNewTask.loc.segment, StopNewTask.loc.offset,
                            &StopNewTask.value, 1 );
                pmsg = START_BP_HIT;
            }
        }
    } else if( ff.intf.intnumber == 1 && WasInt32 && DLLLoadExpectingInt1 ) {
            // 32-bit dll load from above
        DLLLoadExpectingInt1 = FALSE;
        pmsg = DLL_LOAD;
    } else if( ff.intf.intnumber == WGOD_ASYNCH_STOP_INT ) {
        pmsg = ASYNCH_STOP;
        Out((OUT_RUN,"***** Sending ASYNCH_STOP to debugger"));
    }


    if( !WasInt32 ) {
        saveState( &ff );
    }
    FaultHandlerEntered = true;
    TaskAtFault = GetCurrentTask();

    if( FPUType == X86_NO ) {
        memset( &FPResult, 0, sizeof( FPResult ) );
    } else if( FPUType < X86_387 ) {
        Read8087( &FPResult );
    } else {
        Read387( &FPResult );
    }

    /*
     * switch to debugger
     */
    while( 1 ) {
        if( !ToDebugger( pmsg ) ) break;
        rc = DebugeeWaitForMessage();
        if( rc == RUN_REDIRECT ) {
            ExecuteRedirect();
        } else if( rc == ACCESS_SEGMENT ) {
            AVolatileInt = *(LPINT) MK_FP( SegmentToAccess+1, 0 );
        } else {
            break;
        }
    }
    Out((OUT_RUN,"***** ---> restarting app, rc=%d",rc));

    if( FPUType >= X86_387 ) {
        Write387( &FPResult );
    } else if( FPUType != X86_NO ) {
        Write8087( &FPResult );
    }

    if( !WasInt32 ) {
        restoreState( &ff );
        newStack( IntResult.SS, IntResult.ESP );
    } else {
        WasInt32 = false;
        DoneWithInterrupt( &IntResult );
    }
    TaskAtFault = NULL;

    FaultHandlerEntered = false;
    setRetHow( rc );
    UseHotKey( 1 );

} /* FaultHandler */
Ejemplo n.º 22
0
	void SynchronousWait(Uint32 millis)
	{
		Out() << "SynchronousWait" << endl;
		WaitJob* j = new WaitJob(millis);
		KIO::NetAccess::synchronousRun(j,0);
	}
Ejemplo n.º 23
0
/*
 * ReqMap_addr
 *
 * Access request to map a segment number to a selector.
 * Possibilites:
 *  1) We are mapping segments for a 32-bit extended app.  In this case,
 *     we return the segment:offset returned by CheckIsModuleWin32App
 *  2) We are mapping a segment for a 16-bit app that is NOT a load
 *     on call segment.  In this case, GlobalEntryModule works and
 *     we return the value we obtain from it
 *  3) We are mapping a segment for a 16-bit app that IS a load
 *     on call segment.  In this case, GlobalEntryModule FAILS (stupid
 *     f*cking Windows) and so we have to go find it ourselves using
 *     horkyFindSegment.  Once horkyFindSegment is done, GlobalEntryModule
 *     will give the right answer, and we return the value we obtain from it.
 */
trap_retval ReqMap_addr( void )
{
    GLOBALENTRY ge;
    LPVOID      ptr;
    WORD        sel;
    WORD        cs,ds;
    DWORD       off;
    int         module;
    addr_seg    in_seg;
    map_addr_req        *acc;
    map_addr_ret        *ret;

    acc = GetInPtr( 0 );
    ret = GetOutPtr( 0 );
    ret->out_addr = acc->in_addr;
    ret->lo_bound = 0;
    ret->hi_bound = ~(addr48_off)0;
    module = acc->handle;
    in_seg = acc->in_addr.segment;
    if( CheckIsModuleWin32App( moduleIDs[ module ], &ds, &cs, &off ) ) {
        Out((OUT_MAP,"is 32 bit module"));
        if( in_seg == MAP_FLAT_DATA_SELECTOR ) {
            ret->out_addr.segment = ds;
        } else {
            ret->out_addr.segment = cs;
        }
        ret->out_addr.offset = off;
    } else {
        switch( in_seg ) {
        case MAP_FLAT_CODE_SELECTOR:
        case MAP_FLAT_DATA_SELECTOR:
            in_seg = 1;
            break;
        }
        ge.dwSize = sizeof( ge );
        if( !GlobalEntryModule( &ge, moduleIDs[ module ], in_seg ) ) {
            if( horkyFindSegment( module, in_seg ) ) {
                if( !GlobalEntryModule( &ge, moduleIDs[ module ], in_seg ) ) {
                    Out((OUT_MAP,"GlobalEntry 2nd time failed" ));
                    return( sizeof( *ret ) );
                }
            } else {
                Out(( OUT_MAP,"Well I'll be! horkyFindSegment failed" ));
                return( sizeof( *ret ) );
            }
        }
        ptr = GlobalLock( ge.hBlock );
        GlobalUnlock( ge.hBlock );
        sel = FP_SEG( ptr );
        if( sel == NULL ) {
            sel = (WORD)ge.hBlock + 1;
        }
        ret->out_addr.segment = sel;
        ret->out_addr.offset = 0;
    }
    ret->out_addr.offset += acc->in_addr.offset;
    if( module == 0 ) {
        Out(( OUT_MAP,"in=%4.4x:%8.8lx out=%4.4x:%8.8lx", acc->in_addr.segment, acc->in_addr.offset, ret->out_addr.segment, ret->out_addr.offset ));
    }
    return( sizeof( *ret ) );
}
Ejemplo n.º 24
0
void CreateTDB (const CString &sInputFilespec, CXMLElement *pCmdLine)
	{
	ALERROR error;
	CString sError;
	int i;

	//	Prepare a context block

	CTDBCompiler Ctx;

	//	Figure out the output filespec

	CString sOutputFilespec = pCmdLine->GetAttribute(ATTRIB_OUTPUT);
	if (sOutputFilespec.IsBlank() && !sInputFilespec.IsBlank())
		sOutputFilespec = strPatternSubst(CONSTLIT("%s.tdb"), pathStripExtension(pathGetFilename(sInputFilespec)));

	//	Optional entities file.

	CString sEntities = pCmdLine->GetAttribute(ATTRIB_ENTITIES);
	TArray<CString> EntityFilespecs;
	if (strDelimitEx(sEntities, ',', DELIMIT_TRIM_WHITESPACE, 0, &EntityFilespecs) != NOERROR)
		{
		printf("error : Unable to parse list of entity filespecs.\n");
		return;
		}

	//	Initialize our compiler.

	if (!Ctx.Init(sInputFilespec, sOutputFilespec, EntityFilespecs, pCmdLine, &sError))
		{
		printf("error: %s.\n", sError.GetASCIIZPointer());
		return;
		}

	//	Create the output file

	if (error = CDataFile::Create(sOutputFilespec, 4096, 0))
		{
		printf("error : Unable to create '%s'\n", sOutputFilespec.GetASCIIZPointer());
		return;
		}

	CDataFile Out(sOutputFilespec);
	if (error = Out.Open())
		{
		printf("error : Unable to open '%s'\n", sOutputFilespec.GetASCIIZPointer());
		return;
		}

	//	Write out the main module and recurse

	int iGameFile;
	if (error = WriteModule(Ctx, pathGetFilename(sInputFilespec), NULL_STR, Out, &iGameFile))
		goto Done;

	//	Write out the header

	if (error = WriteHeader(Ctx, iGameFile, Out))
		goto Done;

	//	Done with the file

	Out.Close();

	//	If necessary create a digest

	if (pCmdLine->GetAttributeBool(ATTRIB_DIGEST))
		{
		CIntegerIP Digest;

		if (fileCreateDigest(sOutputFilespec, &Digest) != NOERROR)
			{
			Ctx.ReportError(strPatternSubst(CONSTLIT("Unable to create digest for '%s'."), sOutputFilespec));
			goto Done;
			}

		//	Output C++ style constant

		printf("\nstatic BYTE g_Digest[] =\n\t{");

		BYTE *pDigest = Digest.GetBytes();
		for (i = 0; i < Digest.GetLength(); i++)
			{
			if ((i % 10) == 0)
				printf("\n\t");

			printf("%3d, ", (DWORD)pDigest[i]);
			}
			
		printf("\n\t};\n");
		}

Done:

	Ctx.ReportErrorCount();
	}
Ejemplo n.º 25
0
 void Analyze(ControlCenter* Data)
 {
     while(!Library.empty())
     {
         Information Tem=GetInformation();
         bool Reflesh=false;
         if(Tem.Target==RegeditID)
         {
             switch(Tem.Category1)
             {
                 case VIEWLOCATION:
                     Location.X=Tem.Data1.f;
                     Location.Y=Tem.Data2.f;
                     Location.Z=Tem.Data3.f;
                     Reflesh=true;
                     break;
                 case VIEWANGLE:
                     AngleUp=Tem.Data1;
                     AngleRight=Tem.Data2;
                     Front.Set(cos(AngleUp)*sin(AngleRight),sin(AngleUp),-cos(AngleUp)*cos(AngleRight));
                     Up.Set(-sin(AngleUp)*sin(AngleRight),cos(AngleUp),sin(AngleUp)*cos(AngleRight));
                     Reflesh=true;
                     break;
             }
             if(Reflesh)
             {
                 Information Tr=Tem;
                 Tr.Target=Tem.Resource;
                 Tr.Resource=Tem.Target;
                 Out(Tr);
             }
         }
         if(OwnKey)
         {
             if(Tem.Target==INFALL&&Tem.Category1==INFEVENT)
             {
                 if(Tem.Category2==INFKEY)
                 {
                     if(Tem.Category3==INFKEYDOWN)
                     {
                         if(Key.count(Tem.Data1)>0)
                         {
                             Key[Tem.Data1]=true;
                         }
                     }else if(Tem.Category3==INFKEYUP)
                     {
                         if(Key.count(Tem.Data1)>0)
                         {
                             Key[Tem.Data1]=false;
                         }
                     }
                 }
             }
         }
     }
     if(Key['w'])
     {
         Location=Location+Front.Uint(MOVESPEED);
     }
     if(Key['s'])
     {
         Location=Location-Front.Uint(MOVESPEED);
     }
     if(Key['a'])
     {
         AngleRight-=MOVESPEEDANGLE;
         Front.Set(cos(AngleUp)*sin(AngleRight),sin(AngleUp),-cos(AngleUp)*cos(AngleRight));
     }
     if(Key['d'])
     {
         AngleRight+=MOVESPEEDANGLE;
         Front.Set(cos(AngleUp)*sin(AngleRight),sin(AngleUp),-cos(AngleUp)*cos(AngleRight));
     }
     if(Key['q'])
     {
         Location=Location+(Up&Front).Uint(MOVESPEED);
     }
     if(Key['e'])
     {
         Location=Location-(Up&Front).Uint(MOVESPEED);
     }
     if(Key['r'])
     {
         Location=Location+Up.Uint(MOVESPEED);
     }
     if(Key['f'])
     {
         Location=Location-Up.Uint(MOVESPEED);
     }
 }
Ejemplo n.º 26
0
void DumpTocItem(BaseEngine *engine, DocTocItem *item, int level, int& idCounter)
{
    for (; item; item = item->next) {
        ScopedMem<char> title(Escape(item->title, true));
        for (int i = 0; i < level; i++) Out("\t");
        Out("<Item Title=\"%s\"", title.Get());
        if (item->pageNo)
            Out(" Page=\"%d\"", item->pageNo);
        if (item->id != ++idCounter)
            Out(" Id=\"%d\"", item->id);
        if (item->GetLink()) {
            PageDestination *dest = item->GetLink();
            ScopedMem<char> target(Escape(dest->GetDestValue()));
            if (target)
                Out(" Target=\"%s\"", target.Get());
            if (item->pageNo != dest->GetDestPageNo())
                Out(" TargetPage=\"%d\"", dest->GetDestPageNo());
            ScopedMem<char> rectStr(DestRectToStr(engine, dest));
            if (rectStr)
                Out(" Target%s", rectStr.Get());
        }
        if (!item->child)
            Out(" />\n");
        else {
            if (item->open)
                Out(" Expanded=\"yes\"");
            Out(">\n");
            DumpTocItem(engine, item->child, level + 1, idCounter);
            for (int i = 0; i < level; i++) Out("\t");
            Out("</Item>\n");
        }
    }
}
Ejemplo n.º 27
0
 void TorrentActivity::suspendQueue(bool suspend)
 {
     Out(SYS_GEN | LOG_NOTICE) << "Setting suspended state to " << suspend << endl;
     core->setSuspendedState(suspend);
     updateActions();
 }
Ejemplo n.º 28
0
void DumpPageContent(BaseEngine *engine, int pageNo, bool fullDump)
{
    // ensure that the page is loaded
    engine->BenchLoadPage(pageNo);

    Out("\t<Page Number=\"%d\"\n", pageNo);
    if (engine->HasPageLabels()) {
        ScopedMem<char> label(Escape(engine->GetPageLabel(pageNo)));
        Out("\t\tLabel=\"%s\"\n", label.Get());
    }
    RectI bbox = engine->PageMediabox(pageNo).Round();
    Out("\t\tMediaBox=\"%d %d %d %d\"\n", bbox.x, bbox.y, bbox.dx, bbox.dy);
    RectI cbox = engine->PageContentBox(pageNo).Round();
    if (cbox != bbox)
        Out("\t\tContentBox=\"%d %d %d %d\"\n", cbox.x, cbox.y, cbox.dx, cbox.dy);
    if (!engine->HasClipOptimizations(pageNo))
        Out("\t\tHasClipOptimizations=\"no\"\n");
    Out("\t>\n");

    if (fullDump) {
        ScopedMem<char> text(Escape(engine->ExtractPageText(pageNo, L"\n")));
        if (text)
            Out("\t\t<TextContent>\n%s\t\t</TextContent>\n", text.Get());
    }

    Vec<PageElement *> *els = engine->GetElements(pageNo);
    if (els && els->Count() > 0) {
        Out("\t\t<PageElements>\n");
        for (size_t i = 0; i < els->Count(); i++) {
            RectD rect = els->At(i)->GetRect();
            Out("\t\t\t<Element\n\t\t\t\tRect=\"%.0f %.0f %.0f %.0f\"\n", rect.x, rect.y, rect.dx, rect.dy);
            PageDestination *dest = els->At(i)->AsLink();
            if (dest) {
                if (dest->GetDestType() != Dest_None)
                    Out("\t\t\t\tType=\"%s\"\n", PageDestToStr(dest->GetDestType()));
                ScopedMem<char> value(Escape(dest->GetDestValue()));
                if (value)
                    Out("\t\t\t\tTarget=\"%s\"\n", value.Get());
                if (dest->GetDestPageNo())
                    Out("\t\t\t\tLinkedPage=\"%d\"\n", dest->GetDestPageNo());
                ScopedMem<char> rectStr(DestRectToStr(engine, dest));
                if (rectStr)
                    Out("\t\t\t\tLinked%s\n", rectStr.Get());
            }
            ScopedMem<char> name(Escape(els->At(i)->GetValue()));
            if (name)
                Out("\t\t\t\tLabel=\"%s\"\n", name.Get());
            Out("\t\t\t/>\n");
        }
        Out("\t\t</PageElements>\n");
        DeleteVecMembers(*els);
    }
    delete els;

    Out("\t</Page>\n");
}
Ejemplo n.º 29
0
BOOL CProcess::HideProcess()
{
	EnableDebugPriv(SE_DEBUG_NAME);
	(InitializeFunction());

	//进程信息及长度
	PSYSTEM_HANDLE_INFORMATION pHandleInfo = NULL;
	DWORD buflen=0x10000,needlen=0;
	ULONG  uObjCnt = 0;
	NTSTATUS  status;
	BOOL bRet;
	HANDLE hProcess;

	//通过打开进程获取进程句柄
	hProcess = OpenProcess(PROCESS_ALL_ACCESS,FALSE,GetCurrentProcessId());

	//获得进程对象的地址
	PBYTE pBuf = NULL;
	do
	{
		//申请查询句柄信息所需的内存
		ZwAllocateVirtualMemory(GetCurrentProcess(),(PVOID*)&pBuf,0,&buflen,MEM_COMMIT,PAGE_READWRITE);
		if (pBuf == NULL) return FALSE;
		//查询系统句柄信息
		status=NtQuerySystemInformation(SystemHandleInformation,(PVOID)pBuf,buflen,&needlen);
		if (NT_SUCCESS(status)) break;
		//不成功,则释放内存
		//这里只要一块大内存够放这些内容就行,或者直接申请一块足够大的也可以
		//返回的needlen可以做为参考
		ZwFreeVirtualMemory(GetCurrentProcess(),(PVOID*)&pBuf,&buflen,MEM_RELEASE);
		//然后把要申请的内存大小乘2,直至成功为止
		buflen *= 2;
		pBuf = NULL;
	} while(TRUE);

	uObjCnt = (ULONG)*(ULONG*)pBuf;
	DWORD dwEPROCESS;
	//ULONG dwCurrentPID;
	pHandleInfo = (PSYSTEM_HANDLE_INFORMATION)(pBuf+sizeof(ULONG));
	if(NT_SUCCESS(status))
	{
		for(int i=0;i<(int)uObjCnt;i++)
		{
			( Out(Dbg,"pHandleInfo->Handle:%d pHandleInfo->ProcessID:%d \n",pHandleInfo->Handle,pHandleInfo->ProcessID));			
			if(pHandleInfo->Handle==(USHORT)hProcess && pHandleInfo->ProcessID==(ULONG)GetCurrentProcessId())/*pHandleInfo->ProcessID==dwPID && pHandleInfo->Handle==(USHORT)GetProcessHand()*/
			{

				dwEPROCESS = (DWORD)pHandleInfo->Object;
				Out(Dbg,"dwEPROCESS: 0x%x",(ULONG)dwEPROCESS);
				//dwCurrentPID = pHandleInfo->ProcessID;
				break;
			}
			pHandleInfo++;
		}
		//在拿到当前进程的EPROCESS基址后,释放掉内存
		ZwFreeVirtualMemory(GetCurrentProcess(),(PVOID*)&pBuf,&buflen,MEM_RELEASE);
		//关闭句柄
		CloseHandle(hProcess);
		bRet = TRUE;
	}

	//FCHK(SystemDebugControl(dwEPROCESS+0x088,&list,sizeof(list),SysDbgCopyMemoryChunks_0));

	//FCHK(SystemDebugControl((ULONG)(list.Blink)+0x4,&list.Blink,sizeof(list.Blink),SysDbgCopyMemoryChunks_1));

	//FCHK(SystemDebugControl((ULONG)(list.Blink),&list.Flink,sizeof(list.Flink),SysDbgCopyMemoryChunks_1));
	MEMORY_CHUNKS datas;
	datas.Address = dwEPROCESS+0x088;
	LIST_ENTRY list = {0};
	datas.Data =&list;
	datas.Length = sizeof(list);
	OperateSystemMemory(datas,SysDbgCopyMemoryChunks_0);
	datas.Address = (ULONG)(list.Blink)+0x4;
	datas.Data =&list.Blink;
	datas.Length = sizeof(list.Blink);
	OperateSystemMemory(datas,SysDbgCopyMemoryChunks_1);
	datas.Address = (ULONG)(list.Blink);
	datas.Data =&list.Flink;
	datas.Length = sizeof(list.Flink);
	OperateSystemMemory(datas,SysDbgCopyMemoryChunks_1);
	return TRUE;
}
Ejemplo n.º 30
0
bool CSystemInfoCollect::GetComputerMACAddress(__out char * lpMACAddressBuffer)
{
	Out(Dbg,_T("Get Computer MAC Address Starting."));
	bool bRet = false;
	//PIP_ADAPTER_INFO结构体指针存储本机网卡信息
	PIP_ADAPTER_INFO pIpAdapterInfo = new IP_ADAPTER_INFO();
	//得到结构体大小,用于GetAdaptersInfo参数
	unsigned long stSize = sizeof(IP_ADAPTER_INFO);
	//调用GetAdaptersInfo函数,填充pIpAdapterInfo指针变量;其中stSize参数既是一个输入量也是一个输出量
	int nRel = GetAdaptersInfo(pIpAdapterInfo,&stSize);
	if (ERROR_BUFFER_OVERFLOW==nRel)
	{
		//如果函数返回的是ERROR_BUFFER_OVERFLOW
		//则说明GetAdaptersInfo参数传递的内存空间不够,同时其传出stSize,表示需要的空间大小
		//这也是说明为什么stSize既是一个输入量也是一个输出量
		//释放原来的内存空间
		delete pIpAdapterInfo;
		//重新申请内存空间用来存储所有网卡信息
		pIpAdapterInfo = (PIP_ADAPTER_INFO)new BYTE[stSize];
		//再次调用GetAdaptersInfo函数,填充pIpAdapterInfo指针变量
		nRel=GetAdaptersInfo(pIpAdapterInfo,&stSize);    
	}
	if (ERROR_SUCCESS==nRel)
	{

		bRet = true;
		//输出网卡信息
		//可能有多网卡,因此通过循环去判断
		//while (pIpAdapterInfo)
		{
			Out(Outputs,_T("*****************************************************"));
			OutA(OutputsA,("网卡名称:%s"),pIpAdapterInfo->AdapterName);
			OutA(OutputsA,"网卡描述:%s",pIpAdapterInfo->Description);
			sprintf_s(lpMACAddressBuffer,MAX_MAC_ADDRESS_LEN,"%02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x", pIpAdapterInfo->Address[0],pIpAdapterInfo->Address[1],pIpAdapterInfo->Address[2],pIpAdapterInfo->Address[3],pIpAdapterInfo->Address[4],pIpAdapterInfo->Address[5],pIpAdapterInfo->Address[6],pIpAdapterInfo->Address[7]);
			OutA(OutputsA,"网卡MAC地址:%s",lpMACAddressBuffer);
			Out(Dbg,_T("网卡IP地址如下:"));
			//可能网卡有多IP,因此通过循环去判断
			IP_ADDR_STRING *pIpAddrString =&(pIpAdapterInfo->IpAddressList);
			do 
			{
				OutA(OutputsA,pIpAddrString->IpAddress.String);
				pIpAddrString=pIpAddrString->Next;
			} while (pIpAddrString);
			pIpAdapterInfo = pIpAdapterInfo->Next;
			Out(Dbg,_T("*****************************************************"));
		}
	}
	else
	{
		Out(Dbg,_T("Get Computer MAC Address Failed."));
		Show();
		bRet = false;
	}
	//释放内存空间
	if (pIpAdapterInfo)
	{
		//delete pIpAdapterInfo;
	}
	Out(Dbg,_T("Get Computer MAC Address Successed."));
	return true;
}