//Initialize application void ac_init_app( int ac, char* av[]){ int size; char *appname=0; extern int ac_argc; extern char** ac_argv; ac_argc = ac-1; //Skiping program's name ac_argv = av; while(ac > 1){ size = strlen(av[1]); //Checking if an application needs to be loaded if( (size>11) && (!strncmp( av[1], "--load_obj=", 11))){ //Loading a binary app appname = (char*)malloc(size - 10); strcpy(appname, av[1]+11); ac_argv[1] = appname; appfilename = (char*) malloc(sizeof(char)*(size - 6)); strcpy(appfilename, appname); //ac_load_obj( appname ); } else if( (size>7) && (!strncmp( av[1], "--load=", 7))){ //Loading hex file in the ArchC Format appname = (char*)malloc(size - 6); strcpy(appname, av[1]+7); ac_argv[1] = appname; appfilename = (char*) malloc(sizeof(char)*(size - 6)); strcpy(appfilename, appname); } #ifdef USE_GDB if( (size>=5) && (!strncmp( av[1], "--gdb", 5))){ //Enable GDB support int port = 0; if ( size > 6 ) { port = atoi( av[1] + 6 ); if ( ( port > 1024 ) && gdbstub ) gdbstub->set_port( port ); } if ( gdbstub ) gdbstub->enable(); } #endif /* USE_GDB */ ac --; av ++; } if (!appname) { AC_ERROR("No application provided."); AC_ERROR("Use --load=<prog_path> option to load a target application."); AC_ERROR("Try --help for more options."); exit(1); } ac_argv++; }
bool SendTestCmd(string ip,int port){ //socket通讯 int sockfd; if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { AC_ERROR("create socket error"); return false; } struct sockaddr_in dest; bzero(&dest, sizeof(dest)); dest.sin_family = AF_INET; dest.sin_port = htons(port); if (inet_aton(ip.c_str(), (struct in_addr *) &dest.sin_addr.s_addr) == 0) { AC_ERROR("inet_aton error:%d",errno); close(sockfd); return false; } int ret = connect(sockfd, (struct sockaddr *) &dest, sizeof(dest)); if (ret != 0) { AC_ERROR("connect to trSrv error :%d",ret); close(sockfd); return false; } struct timeval tv = {60 , 0}; if((setsockopt(sockfd,SOL_SOCKET,SO_RCVTIMEO,&tv,sizeof(tv)) == -1) || (setsockopt(sockfd,SOL_SOCKET,SO_SNDTIMEO,&tv,sizeof(tv)) == -1)){ close(sockfd); AC_ERROR("setsockopt error:%d",errno); return false; } //ssl 通讯 SSL_CTX *ctx; ctx = SSL_CTX_new(SSLv23_client_method()); if (ctx == NULL) { ERR_print_errors_fp(stdout); close(sockfd); SSL_CTX_free(ctx); return false; } SSL *ssl = SSL_new(ctx); SSL_set_fd(ssl,sockfd); if (SSL_connect(ssl) == -1){ ERR_print_errors_fp(stderr); AC_ERROR("ssl_connect error"); close(sockfd); SSL_free(ssl); SSL_CTX_free(ctx); return false; } bool bret = Login_Fund(ssl); close(sockfd); SSL_free(ssl); SSL_CTX_free(ctx); return bret; }
int CRmqCli::ReadMessage(char *cachebuf/*8192*/, int cachesize, int timeout) { int iCode = 0; char acErrMsg[300]; int datalen = 0; TAG_RMQHANDLE RMQtagHnd; //内部自动重连一次 if (false == Connect()) return -1; if (FALSE == ::RmqReadMessage(cachebuf, cachesize, &datalen, m_Handle, &RMQtagHnd, &iCode, acErrMsg, timeout)) { switch (iCode) { case ERROR_READ_TIMEOUT: datalen = 0; return datalen; default: datalen = -1; Disconnect(); //char acMsg[512]; AC_ERROR("RMQCli客户端读数据失败:%d,%s\n", iCode, acErrMsg); //MT_ERROR(iCode, acMsg); } } return datalen; }
int sendbusinessEmial() { string strConn = ServerConf::Instance()->m_dbcfg.m_dbip+ ":"+ "@" + ServerConf::Instance()->m_dbcfg.m_dbname; ConnectDb *ConnectHandle = new ConnectDb(strConn, ServerConf::Instance()->m_dbcfg.m_dbuser, ServerConf::Instance()->m_dbcfg.m_dbpwd, "gb2312"); if (!ConnectHandle->connect()) return -1; string jsonString; string ret; ServerConf::Instance()->m_sendcfg.sendtime = time(NULL); while (!g_exit) { if (onTime()) { if(ConnectHandle->execCommand(ServerConf::Instance()->m_spcfg.spname,ServerConf::Instance()->m_spcfg.numDay,jsonString)) { parseJosnString(jsonString,ret); sendQueryMail(ret); ServerConf::Instance()->m_sendcfg.sendtime = time(NULL); AC_INFO("Send business mail :%s",ret.c_str()); } else { AC_ERROR("Send business mail failed\n"); } } sleep(300); } return 0; }
void ConnectDb::closeConnect() { try { DBConnection.Disconnect(); } catch (SAException & ex) { AC_ERROR("close db connection failed [%s]\n", (const char *)ex.ErrText()); } }
/*commit config to kernel*/ int do_commit_config(const char *config_str, unsigned int len) { int ret = -1; if (config_str == NULL || len <= 0) { return -1; } if (do_parse_config(config_str, len) != 0) { AC_ERROR("do_parse_config failed\n"); return -1; } if (s_config.control->rule.updated) { struct ac_table_info *table_info = generate_ac_table(&s_config.control->rule); display_ac_table(table_info); if (table_info) { if (do_rule_ipc_set(AC_SO_SET_REPLACE_CONTROL, table_info, table_info->size) != 0) { goto out; } } } if (s_config.control->set.updated) { struct ac_set_info *set_info = generate_ac_set(&s_config.control->set); if (set_info) { if (do_rule_ipc_set(AC_SO_SET_REPLACE_CONTROL_SET, set_info, set_info->size) != 0) { goto out; } } } if (s_config.audit->rule.updated) { struct ac_table_info *table_info = generate_ac_table(&s_config.audit->rule); if (table_info) { if (do_rule_ipc_set(AC_SO_SET_REPLACE_AUDIT, table_info, table_info->size) != 0) { goto out; } } } if (s_config.audit->set.updated) { struct ac_set_info *set_info = generate_ac_set(&s_config.audit->set); if (set_info) { if (do_rule_ipc_set(AC_SO_SET_REPLACE_AUDIT_SET, set_info, set_info->size) != 0) { goto out; } } } ret = 0; out: free_global_config(); return ret; }
float BaseScriptComponent::GetYOrientationRadians(void) const { shared_ptr<TransformComponent> pTransformComponent = MakeStrongPtr(m_pOwner->GetComponent<TransformComponent>(TransformComponent::g_Name)); if (pTransformComponent) { return (GetYRotationFromVector(pTransformComponent->GetLookAt())); } else { AC_ERROR("Attempting to call GetYOrientationRadians() on actor with no physical component"); return 0; } }
bool Login_Fund( SSL *ssl){ char szbuf[256]; sprintf(szbuf,"{\"loginacc\":\"%s\",\"token\":\"%s\"}",ServerConf::Instance()->m_TrAcc.c_str(),ServerConf::Instance()->m_PassWord.c_str()); string body1= szbuf; string strjson=body1; unsigned short wCmd=50001; NtPkgHead head; memset(&head,0,sizeof(head)); head.bStartFlag=0xFF; head.bVer=1; head.bEncryptFlag=0; head.bFrag=0; head.wLen= htons(sizeof(NtPkgHead)+body1.size()) ; head.wCmd=htons(wCmd); head.wSeq=0; head.wCrc=0; head.dwSID=0; string outbuf1; outbuf1.append((const char *)&head,sizeof(head)); outbuf1.append((char*)body1.data(),body1.size()); int len1 = SSL_write(ssl,outbuf1.data(),outbuf1.size()); if(len1 != (int)outbuf1.size()){ AC_ERROR("SSL_write buf:%s error erron:%d",body1.c_str(),errno); return false; } char acbuf[8192]; memset(acbuf,0x0,8192); int len = SSL_read(ssl,acbuf,8192); if(len < 0){ AC_ERROR("SSL_read read buf error erron:%d",errno); return false; } RUNLOG("SSL_read ret Data:%s\n",acbuf+sizeof(NtPkgHead)); return true; }
void BaseScriptComponent::SetPos(LuaPlus::LuaObject newPos) { shared_ptr<TransformComponent> pTransformComponent = MakeStrongPtr(m_pOwner->GetComponent<TransformComponent>(TransformComponent::g_Name)); if (pTransformComponent) { Vec3 pos; LuaStateManager::Get()->ConvertTableToVec3(newPos, pos); pTransformComponent->SetPosition(pos); } else { AC_ERROR("Attempting to call SetPos() on an actor with no physcial component; ActorId: " + ToStr(m_pOwner->GetId())); } }
bool ConnectDb::connect() { try { SAClient = SA_MySQL_Client; DBConnection.setOption("MYSQL_OPT_RECONNECT") = "TRUE"; DBConnection.setOption("CharacterSet") = m_strCharset; DBConnection.Connect(m_strDBConnString, m_strUser, m_strPassword, (SAClient_t)SAClient); AC_INFO("connect mysql success!\n"); } catch(SAException & ex) { AC_ERROR("connect db error [%s]\n", (const char *)ex.ErrText()); return false; } return true; }
int CRmqCli::SendMessage(char* databuf, int datasize, int iBranchNo, int iFuncNo) { int iCode = 0; char acErrMsg[300]; int Prior = 3; //根据实际业务需要调整 //内部自动重连一次 if (false == Connect()) return -1; if (FALSE == ::RmqPostMessage(Prior, iBranchNo, iFuncNo, databuf, datasize, &iCode, acErrMsg, m_Handle)) { Disconnect(); //char acMsg[512]; AC_ERROR("RMQCli 客户端发送数据失败:%d,%s\n", iCode, acErrMsg); //MT_ERROR(iCode, acMsg); return -1; } return datasize; }
/* Transforms the data pointed by field (with size) to big endian */ unsigned int byte_get_big_endian(unsigned char *field, int size) { switch (size) { case 1: return *field; case 2: return ((unsigned int) (field[1])) | (((int) (field[0])) << 8); case 4: return ((unsigned long) (field[3])) | (((unsigned long) (field[2])) << 8) | (((unsigned long) (field[1])) << 16) | (((unsigned long) (field[0])) << 24); default: AC_ERROR("Internal error: Invalid byte size.\n"); exit(EXIT_FAILURE); } }
bool CRmqCli::Connect() { int iCode = 0; char acErrMsg[300]; if (false == m_Connected) { m_Handle = ::RmqConnect(m_RmqIP, m_RmqPort, &iCode, acErrMsg); if (m_Handle > 0) { m_Connected = true; } else { //char acMsg[512]; AC_ERROR( "RMQCli 连接RMQ失败! %d:%s", iCode, acErrMsg); //MT_ERROR(iCode, acMsg); } } return m_Connected; }
bool ConnectDb:: execCommand(string& spName,int timeParm,string& ret) { try { DBCommand.setConnection(&DBConnection); DBCommand.setCommandText(spName.c_str(), SA_CmdStoredProc); const char* m_param = "time"; DBCommand.CreateParam(m_param, SA_dtLong, SA_ParamInput); DBCommand.Param(m_param).setAsLong() = timeParm; DBCommand.Execute(); packageData(ret); DBCommand.DestroyParams(); } catch(SAException &ex) { AC_ERROR("error %d:%s\n", ex.ErrNativeCode(), (const char*)ex.ErrText()); return false; } return true; }
/* Parse json string to c data structure, and then store them in global config */ int do_parse_config(const char *json_str, unsigned int size) { int ret = -1; char *json_str_cpy = NULL; const nx_json *js = NULL, *js_elem = NULL; if (json_str == NULL || size <= 0) { AC_ERROR("invalid parameters."); return -1; } json_str_cpy = malloc(sizeof(char) * (size + 1)); if (json_str_cpy == NULL) { goto out; } bzero(json_str_cpy, size + 1); memcpy(json_str_cpy, json_str, size); js = nx_json_parse_utf8(json_str_cpy); if (js == NULL) { AC_ERROR("config parse failed.\n"); goto out; } if (nx_json_verify(js) != 0) { AC_ERROR("nxjson verify failed.\n"); goto out; } init_global_config(); /*parse control set*/ js_elem = nx_json_get(js, CONTROL_SET_KEY); if (js_elem->type != NX_JSON_NULL) { if (do_parse_control_set(js_elem, &s_config.control->set) == 0) { display_control_set(&s_config.control->set); } } /*parse audit set*/ js_elem = nx_json_get(js, AUDIT_SET_KEY); if (js_elem->type != NX_JSON_NULL) { if (do_parse_audit_set(js_elem, &s_config.audit->set) == 0) { display_audit_set(&s_config.audit->set); } } /*parse control rule*/ js_elem = nx_json_get(js, CONTROL_RULE_KEY); if (js_elem->type != NX_JSON_NULL) { if (do_parse_control_rule(js_elem, &s_config.control->rule) == 0) { display_control_rule(&s_config.control->rule); } else { goto out; } } /*parse audit rule*/ js_elem = nx_json_get(js, AUDIT_RULE_KEY); if (js_elem->type != NX_JSON_NULL) { if (do_parse_audit_rule(js_elem, &s_config.audit->rule) == 0) { display_audit_rule(&s_config.audit->rule); } else { goto out; } } ret = 0; out: if (js != NULL) { nx_json_free(js); } if (json_str_cpy) { free(json_str_cpy); } if (ret != 0) { free_global_config(); } return ret; }
bool BaseScriptComponent::VInit(TiXmlElement* pData) { LuaStateManager* pStateMgr = LuaStateManager::Get(); AC_ASSERT(pStateMgr); // load the <ScriptObject> tag and validate it TiXmlElement* pScriptObjectElement = pData->FirstChildElement("ScriptObject"); if (!pScriptObjectElement) { AC_ERROR("No <ScriptObject> tag in XML. This won't be a very useful script component."); return true; // technically it succeeded even though it won't be accessible } // read all the attributes const char* temp = NULL; temp = pScriptObjectElement->Attribute("var"); if (temp) m_scriptObjectName = temp; temp = pScriptObjectElement->Attribute("constructor"); if (temp) m_constructorName = temp; temp = pScriptObjectElement->Attribute("destructor"); if (temp) m_destructorName = temp; // Having a var attribute will export the instance of this object to that name. if (!m_scriptObjectName.empty()) { m_scriptObject = pStateMgr->CreatePath(m_scriptObjectName.c_str()); if (!m_scriptObject.IsNil()) { CreateScriptObject(); } } // The scriptConstructor attribute will also cause a Lua object to be created if one wasn't created in // the previous step. The scriptConstructor string is treated as a function of the form f(scriptObject) // and is called. if (!m_constructorName.empty()) { m_scriptConstructor = pStateMgr->GetGlobalVars().Lookup(m_constructorName.c_str()); if (m_scriptConstructor.IsFunction()) { // m_scriptObject could be nil if there was no scriptObject attribute. If this is the case, // the Lua object is created here. if (m_scriptObject.IsNil()) { m_scriptObject.AssignNewTable(pStateMgr->GetLuaState()); CreateScriptObject(); } } } // The scriptDestructor attribute is treated as a function in the form of f(scriptObject) and is called // when the C++ ScriptObject instance is destroyed. if (!m_destructorName.empty()) { m_scriptDestructor = pStateMgr->GetGlobalVars().Lookup(m_destructorName.c_str()); } // read the <ScriptData> tag TiXmlElement* pScriptDataElement = pData->FirstChildElement("ScriptData"); if (pScriptDataElement) { if (m_scriptObject.IsNil()) { AC_ERROR("m_scriptObject cannot be nil when ScriptData has been defined"); return false; } for (TiXmlAttribute* pAttribute = pScriptDataElement->FirstAttribute(); pAttribute != NULL; pAttribute = pAttribute->Next()) { m_scriptObject.SetString(pAttribute->Name(), pAttribute->Value()); } } return true; }
//=================================================================== // Win32 Specific Stuff // // InitInstance - this checks system resources, creates your window, and launches the game // // preprocessor macro setting in the C++ options of the project provides the base macro // C preprocessor string concatenation takes care of the rest. // // AlphaApp::InitInstance - Chapter 5, page 136 // //=================================================================== bool AlphaApp::InitInstance(HINSTANCE hInstance, LPWSTR lpCmdLine, HWND hWnd, int screenWidth, int screenHeight, bool windowed) { AC_LOG("Script","Init"); // Check for existing instance of the same window - Chapter 5, page 137 // #ifndef _DEBUG // Note - it can be really useful to debug network code to have // more than one instance of the game up at one time - so // feel free to comment these lines in or out as you wish! if (!IsOnlyInstance(VGetGameTitle())) return false; #endif // We don't need a mouse cursor by default, let the game turn it on SetCursor(NULL); // Check for adequate machine resources. // Check secondary storage space and memory. - Chapter 5, page 138-139 // Calculate the CPU speed. - Chapter 5, page 140 bool resourceCheck = false; while (!resourceCheck) { const DWORDLONG physicalRAM = 512 * MEGABYTE; const DWORDLONG virtualRAM = 1024 * MEGABYTE; const DWORDLONG diskSpace = 10 * MEGABYTE; if (!CheckStorage(diskSpace)) return false; const DWORD minCpuSpeed = 1300; // 1.3Ghz DWORD thisCPU = ReadCPUSpeed(); if (thisCPU < minCpuSpeed) { AC_ERROR("GetCPUSpeed reports CPU is too slow for this game."); return false; } resourceCheck = true; } m_hInstance = hInstance; // register all events RegisterEngineEvents(); VRegisterGameEvents(); // // Initialize the ResCache - Chapter 5, page 141 // // Note - this is a little different from the book. Here we have a speccial resource ZIP file class, DevelopmentResourceZipFile, // that actually reads directly from the source asset files, rather than the ZIP file. This is MUCH better during development, since // you don't want to have to rebuild the ZIP file every time you make a minor change to an asset. // IResourceFile *zipFile = (m_bIsEditorRunning || m_Options.m_useDevelopmentDirectories) ? AC_NEW DevelopmentResourceZipFile(L"Assets.zip", DevelopmentResourceZipFile::Editor) : AC_NEW ResourceZipFile(L"Assets.zip"); m_ResCache = AC_NEW ResCache(50, zipFile); if (!m_ResCache->Init()) { AC_ERROR("Failed to initialize resource cache! Are your paths set up correctly?"); return false; } //extern shared_ptr<IResourceLoader> CreateWAVResourceLoader(); //extern shared_ptr<IResourceLoader> CreateOGGResourceLoader(); extern shared_ptr<IResourceLoader> CreateDDSResourceLoader(); extern shared_ptr<IResourceLoader> CreateJPGResourceLoader(); extern shared_ptr<IResourceLoader> CreateXmlResourceLoader(); //extern shared_ptr<IResourceLoader> CreateSdkMeshResourceLoader(); extern shared_ptr<IResourceLoader> CreateScriptResourceLoader(); // Note - register these in order from least specific to most specific! They get pushed onto a list. // RegisterLoader is discussed in Chapter 5, page 142 //m_ResCache->RegisterLoader(CreateWAVResourceLoader()); //m_ResCache->RegisterLoader(CreateOGGResourceLoader()); m_ResCache->RegisterLoader(CreateDDSResourceLoader()); m_ResCache->RegisterLoader(CreateJPGResourceLoader()); m_ResCache->RegisterLoader(CreateXmlResourceLoader()); //m_ResCache->RegisterLoader(CreateSdkMeshResourceLoader()); m_ResCache->RegisterLoader(CreateScriptResourceLoader()); //// Load strings that will be presented to the player. - Chapter 5, page 142 //if(!LoadStrings("English")) //{ // AC_ERROR("Failed to load strings"); // return false; //} // Create the LUA script manager. - Chapter 5, page 144 if (!LuaStateManager::Create()) { AC_ERROR("Failed to initialize Lua"); return false; } // Load the preinit file. This is within braces to create a scope and destroy the resource once it's loaded. We // don't need to do anything with it, we just need to load it. { Resource resource(SCRIPT_PREINIT_FILE); shared_ptr<ResHandle> pResourceHandle = m_ResCache->GetHandle(&resource); // this actually loads the XML file from the zip file } // Register function exported from C++ ScriptExports::Register(); ScriptProcess::RegisterScriptClass(); BaseScriptComponent::RegisterScriptFunctions(); // Create the game's event manager. - Chapter 5, page 145 m_pEventManager = AC_NEW EventManager("AlphaApp Event Mgr", true); if (!m_pEventManager) { AC_ERROR("Failed to create EventManager."); return false; } // Inititalize DirectX, the application's window, and the D3D device. - Chapter 5, page 145 //DXUTInit(true, true, lpCmdLine, true); //Init DirectX11Wrapper class g_pDX11W->DX11WInit(lpCmdLine);// may need to be put in the alpha app init instance function if (hWnd==NULL) { //DXUTCreateWindow(VGetGameTitle(), hInstance, VGetIcon()); g_pDX11W->DX11WCreateWindow(VGetGameTitle(), hInstance, VGetIcon()); } else { //DXUTSetWindow( hWnd, hWnd, hWnd ); } if(!GetHwnd()) { return false; } SetWindowText(GetHwnd(), VGetGameTitle()); // initialize the directory location you can store save game files //_tcscpy_s(m_saveGameDirectory, GetSaveGameDirectory(GetHwnd(), VGetGameAppDirectory())); // DXUTCreateDevice - Chapter 5 - page 139 m_screenSize = Point(screenWidth, screenHeight); //DXUTCreateDevice( D3D_FEATURE_LEVEL_10_1, true, screenWidth, screenHeight); g_pDX11W->DX11WCreateDevice(windowed, screenWidth, screenHeight); m_Renderer = shared_ptr<IRenderer>(AC_NEW D3DRenderer11()); m_Renderer->VSetBackgroundColor(0, 50, 100, 255); m_Renderer->VOnRestore(); // You usually must have an HWND to initialize your game views... // VCreateGameAndView - Chapter 5, page 145 m_pGame = VCreateGameAndView(); if (!m_pGame) return false; // now that all the major systems are initialized, preload resources // Preload calls are discussed in Chapter 5, page 148 //m_ResCache->Preload("*.ogg", NULL); m_ResCache->Preload("*.dds", NULL); //m_ResCache->Preload("*.jpg", NULL); //if ( GameCodeApp::GetRendererImpl() == GameCodeApp::Renderer_D3D11 ) // m_ResCache->Preload("*.sdkmesh", NULL); m_bIsRunning = TRUE; return TRUE; }
/* Walks through object's relocations, finds out if the symbol is undefined. If it is, Look up for its definition in other nodes */ void link_node::resolve_symbols() { unsigned int i; Elf32_Word info, verhash; Elf_Symndx symndx; Elf32_Sym *elf_symbol, *def_elf_symbol; symbol_wrapper *symbol, *def_symbol; char *vername; unsigned char symbol_info = 0, weak = 0; if (!has_relocations) return; for (i = 0; i < dyn_relocs.get_size(); i++) { info = dyn_relocs.read_info(i); symndx = ELF32_R_SYM(info); elf_symbol = dyn_table.get_symbol(symndx); symbol = new symbol_wrapper(elf_symbol, match_endian); symbol_info = symbol->read_info(); if (ELF32_ST_TYPE(symbol_info) > STT_FUNC && ELF32_ST_TYPE(symbol_info) != STT_COMMON) { delete symbol; continue; /* Not a symbol type we need to resolve */ } if (ELF32_ST_BIND(symbol_info) == STB_LOCAL || ELF32_ST_BIND(symbol_info) > STB_WEAK) { delete symbol; continue; /* Not global or weak */ } if (ELF32_ST_BIND(symbol_info) == STB_WEAK) { weak = 1; } if (symbol->read_section_ndx() != SHN_UNDEF) { delete symbol; continue; /* Symbol is not undefined, no need to resolve */ } vername = NULL; verhash = 0; /* Are we requesting a special version? */ if (dyn_table.get_verneed() != NULL) { Elf32_Half verndx = dyn_table.get_verndx(symndx); vername = dyn_table.get_verneed()->lookup_version(verndx & 0x7fff); verhash = dyn_table.get_verneed()->get_cur_hash(); } def_elf_symbol = NULL; def_elf_symbol = find_symbol(dyn_table.get_name(symbol->read_name_ndx()), vername, verhash, false); if (def_elf_symbol == NULL) /* Symbol not found. */ { if (weak) { delete symbol; continue; /* Definition for this symbol is not a problem */ } AC_ERROR("Run-time dynamic linker: Symbol \"" << dyn_table.get_name(symbol->read_name_ndx()) << "\" unknown."); exit(EXIT_FAILURE); } /* Symbol found */ def_symbol = new symbol_wrapper(def_elf_symbol, match_endian); symbol->write_value(def_symbol->read_value()); symbol->write_size(def_symbol->read_size()); symbol->write_section_ndx(def_symbol->read_section_ndx()); symbol->write_info(def_symbol->read_info()); /* Done */ delete def_symbol; delete symbol; } /* for(i=0;i<dyn_relocs.get_size();i++) */ } /* resolve_symbols() */
//Loading binary application int ac_load_elf(char* filename, char* data_mem, unsigned int data_mem_size) { Elf32_Ehdr ehdr; Elf32_Shdr shdr; Elf32_Phdr phdr; FILE *fd; unsigned int i; /* Most code was taken from the Binutils readelf application */ /* Open up the file for reading */ fd = fopen (filename, "rb"); if (fd == NULL) { AC_ERROR("Opening application file '" << filename << "': " << strerror(errno) << endl); exit(EXIT_FAILURE); } /* Read in the identity array. */ if (fread (ehdr.e_ident, EI_NIDENT, 1, fd) != 1) { AC_ERROR("Error reading file '" << filename << endl); exit(EXIT_FAILURE); } /* Determine how to read the rest of the header. */ switch (ehdr.e_ident[EI_DATA]) { default: /* fall through */ case ELFDATANONE: /* fall through */ case ELFDATA2LSB: byte_get = byte_get_little_endian; // byte_put = byte_put_little_endian; break; case ELFDATA2MSB: byte_get = byte_get_big_endian; // byte_put = byte_put_big_endian; break; } // TODO: Consider the case when the file is not 32-bit /* Get the rest of the header data */ if (fread ((unsigned char *)&ehdr.e_type, sizeof (ehdr) - EI_NIDENT, 1, fd) != 1) { AC_ERROR("Error reading file %s\n" << filename << endl); exit(EXIT_FAILURE); } ehdr.e_type = BYTE_GET (&ehdr.e_type); ehdr.e_machine = BYTE_GET (&ehdr.e_machine); ehdr.e_version = BYTE_GET (&ehdr.e_version); ehdr.e_entry = BYTE_GET (&ehdr.e_entry); ehdr.e_phoff = BYTE_GET (&ehdr.e_phoff); ehdr.e_shoff = BYTE_GET (&ehdr.e_shoff); ehdr.e_flags = BYTE_GET (&ehdr.e_flags); ehdr.e_ehsize = BYTE_GET (&ehdr.e_ehsize); ehdr.e_phentsize = BYTE_GET (&ehdr.e_phentsize); ehdr.e_phnum = BYTE_GET (&ehdr.e_phnum); ehdr.e_shentsize = BYTE_GET (&ehdr.e_shentsize); ehdr.e_shnum = BYTE_GET (&ehdr.e_shnum); ehdr.e_shstrndx = BYTE_GET (&ehdr.e_shstrndx); /* Check if the file is in fact an ELF */ if ( ehdr.e_ident[EI_MAG0] != ELFMAG0 || ehdr.e_ident[EI_MAG1] != ELFMAG1 || ehdr.e_ident[EI_MAG2] != ELFMAG2 || ehdr.e_ident[EI_MAG3] != ELFMAG3) { fclose(fd); return EXIT_FAILURE; } //Set start address ac_start_addr = ehdr.e_entry; if (ac_start_addr > data_mem_size) { AC_ERROR("the start address of the application is beyond model memory\n"); fclose(fd); exit(EXIT_FAILURE); } if (ehdr.e_type == ET_EXEC) { //It is an ELF file AC_SAY("Reading ELF application file: " << filename << endl); //Get program headers and load segments // lseek(fd, convert_endian(4,ehdr.e_phoff), SEEK_SET); for (i=0; i < ehdr.e_phnum; i++) { //Get program headers and load segments fseek(fd, ehdr.e_phoff + ehdr.e_phentsize*i, SEEK_SET); if (fread(&phdr, sizeof(phdr), 1, fd) != 1) { AC_ERROR("reading ELF program header\n"); fclose(fd); exit(EXIT_FAILURE); } if (BYTE_GET (&phdr.p_type) == PT_LOAD) { Elf32_Word j; Elf32_Addr p_vaddr = BYTE_GET (&phdr.p_vaddr); Elf32_Word p_memsz = BYTE_GET (&phdr.p_memsz); Elf32_Word p_filesz = BYTE_GET (&phdr.p_filesz); Elf32_Off p_offset = BYTE_GET (&phdr.p_offset); //Error if segment greater then memory if (data_mem_size < p_vaddr + p_memsz) { AC_ERROR("not enough memory in ArchC model to load application.\n"); fclose(fd); exit(EXIT_FAILURE); } //Set heap to the end of the segment if (ac_heap_ptr < p_vaddr + p_memsz) ac_heap_ptr = p_vaddr + p_memsz; //Load and correct endian fseek(fd, p_offset, SEEK_SET); for (j=0; j < p_filesz; j+=sizeof(ac_fetch)) { int tmp; fread(&tmp, sizeof(ac_fetch), 1, fd); *(ac_fetch *) (data_mem + p_vaddr + j) = byte_get((unsigned char *)&tmp, sizeof(ac_fetch)); } memset(data_mem + p_vaddr + p_filesz, 0, p_memsz - p_filesz); } } } else if (ehdr.e_type == ET_REL) { AC_SAY("Reading ELF relocatable file: " << filename << endl); // first load the section name string table char *string_table; int shoff = ehdr.e_shoff; short shndx = ehdr.e_shstrndx; short shsize = ehdr.e_shentsize; fseek(fd, shoff+(shndx*shsize), SEEK_SET); if (fread(&shdr, sizeof(shdr), 1, fd) != 1) { AC_ERROR("reading ELF section header\n"); fclose(fd); exit(EXIT_FAILURE); } string_table = (char *) malloc(BYTE_GET (&shdr.sh_size)); fseek(fd, BYTE_GET (&shdr.sh_offset), SEEK_SET); fread(string_table, BYTE_GET (&shdr.sh_size), 1, fd); // load .text, .data and .bss sections for (i=0; i < ehdr.e_shnum; i++) { fseek(fd, shoff + shsize*i, SEEK_SET); if (fread(&shdr, sizeof(shdr), 1, fd) != 1) { AC_ERROR("reading ELF section header\n"); fclose(fd); exit(EXIT_FAILURE); } Elf32_Word name = BYTE_GET (&shdr.sh_name); if (!strcmp(string_table+name, ".text") || !strcmp(string_table+name, ".data") || !strcmp(string_table+name, ".bss")) { // printf("Section %s:\n", string_table+convert_endian(4,shdr.sh_name)); Elf32_Off tshoff = BYTE_GET (&shdr.sh_offset); Elf32_Word tshsize = BYTE_GET (&shdr.sh_size); Elf32_Addr tshaddr = BYTE_GET (&shdr.sh_addr); if (tshsize == 0) { // printf("--- empty ---\n"); continue; } if (data_mem_size < tshaddr + tshsize) { AC_ERROR("not enough memory in ArchC model to load application.\n"); fclose(fd); exit(EXIT_FAILURE); } //Set heap to the end of the segment if (ac_heap_ptr < tshaddr + tshsize) ac_heap_ptr = tshaddr + tshsize; if (!strcmp(string_table+BYTE_GET (&shdr.sh_name), ".bss")) { memset(data_mem + tshaddr, 0, tshsize); //continue; break; // .bss is supposed to be the last one } //Load and correct endian fseek(fd, tshoff, SEEK_SET); for (Elf32_Word j=0; j < tshsize; j+=sizeof(ac_fetch)) { int tmp; fread(&tmp, sizeof(ac_fetch), 1, fd); *(ac_fetch *) (data_mem + tshaddr + j) = byte_get((unsigned char *)&tmp, sizeof(ac_fetch)); // printf("0x%08x %08x \n", tshaddr+j, *(ac_fetch *) (data_mem+tshaddr+j)); } // printf("\n"); } } } //Close file fclose(fd); return EXIT_SUCCESS; }
/*!Check a device behavioral and structural logs in the end of simulation. Used for untimed verification. In this case, the logs need to have modifications in the same order, but not at the same time. \param pdevice A pointer to the device object being checked. \param pdevice A pointer to the structural change list for this device. */ void ac_verify::check_final( ac_mem *pbhvdevice, log_list *pdevchange){ log_list *pbhvchange; log_list::iterator bhvitor; log_list::iterator devitor; bool flag; pbhvchange = pbhvdevice->get_changes(); //Test if both logs have elements. if( pbhvchange->size() && pdevchange->size()){ //Sorting vectors. pbhvchange->sort(); pdevchange->sort(); bhvitor = pbhvchange->begin(); devitor = pdevchange->begin(); //Checking consistence. while( (bhvitor != pbhvchange->end()) && (devitor != pdevchange->end()) ){ flag = false; if( bhvitor->addr == devitor->addr && bhvitor->value == devitor->value ){ bhvitor = pbhvchange->erase( bhvitor ); devitor = pdevchange->erase( devitor ); flag = true; } if(!flag){ bhvitor++; devitor++; } } } if( pbhvchange->size() || pdevchange->size()){ bhvitor = pbhvchange->begin(); devitor = pdevchange->begin(); AC_ERROR( "Verification failed for device " << pbhvdevice->get_name() << "! See logs in ac_verification.log"); output << "************************************************************"<<endl; output << "* ArchC Storage Based Co-Verification ERROR Log *"<<endl; output << "************************************************************"<<endl; output << endl << "The following updates are inconsistent..."<<endl<<endl; output << "------------------------------------------------------------\n"; output << "=> Device: "<< pbhvdevice->get_name() <<endl; output << "------------------------------------------------------------\n"; output<< " Address \t\tValue \t\tTime"<<endl; output<<"Behavioral: "<<endl; while(bhvitor != pbhvchange->end()){ output << "\t\t"<< *bhvitor<< endl; bhvitor++; } output << "Structural: "<<endl; while(devitor != pdevchange->end()){ output << "\t\t"<< *devitor<< endl; devitor++; } output << endl << endl; } }